Is possible to pass an input image from an html form to matlab using javascript?

7 views (last 30 days)
Hello everyone. I'm building a graphic interface using MATLAB with HTML, CSS, and JavaScript. I'm working on a small form where users can upload an image, and this image needs to be sent to MATLAB to be displayed using the imshow() function. This is what I'm doing:
fig = uifigure("Position",[100 100 900 500]);
h = uihtml(fig,"Position",[0 0 900 500]);
h.HTMLSource = 'immagineInput.html';
h.HTMLEventReceivedFcn = @displayNumber;
function displayNumber(src,event)
name = event.HTMLEventName;
if strcmp(name,'ButtonClicked')
number = event.HTMLEventData;
b64 = matlab.net.base64decode(number);
imshow(b64);
end
end
But the problem is that it displays an empty window, without the image.
The JavaScript code is the following:
function setup(htmlComponent) {
var input = document.getElementById("immagine");
var submit = document.getElementById("submit");
submit.addEventListener("click", function () {
var file = input.files[0];
var reader = new FileReader();
reader.onloadend = function () {
htmlComponent.sendEventToMATLAB("ButtonClicked", reader.result);
};
reader.readAsDataURL(file);
});
}

Accepted Answer

Shubham
Shubham on 5 Jun 2023
Hi MATTEO,
It looks like your JavaScript code is correctly reading the uploaded image file as a data URL and sending it to MATLAB using the sendEventToMATLAB function. However, the imshow function expects an image file path or a matrix of image data, not a data URL.
You can decode the data URL to obtain the raw image data, and then use the imread function to read the image data into a matrix that can be displayed with imshow. Here's an updated version of your MATLAB code that does this:
fig = uifigure("Position",[100 100 900 500]);
h = uihtml(fig,"Position",[0 0 900 500]);
h.HTMLSource = 'immagineInput.html';
h.HTMLEventReceivedFcn = @displayImage;
function displayImage(src, event)
name = event.HTMLEventName;
if strcmp(name, 'ButtonClicked')
dataUrl = event.HTMLEventData;
[~, ~, ext] = fileparts(dataUrl);
if strcmpi(ext, '.svg') % SVG images cannot be decoded, so display them directly
imgHtml = sprintf('<img src="%s" />', dataUrl);
h.executeJS(['document.body.innerHTML = ''' imgHtml ''';']);
else % Decode image data and display with imshow
imageData = base64decode(strrep(dataUrl, 'data:image/*;base64,', ''));
imageMatrix = imread(imageData);
imshow(imageMatrix);
end
end
end
In this code, we first check the file extension of the data URL. If it's an SVG file, we simply display it directly using an img HTML tag, since SVG images cannot be decoded. Otherwise, we decode the image data using base64decode and then read it into a matrix using imread. Finally, we display the image using imshow.

More Answers (0)

Categories

Find more on Image Processing Toolbox in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!