MATLAB Answers

Why does uiimage does not update when the file linked to ImageSource changes?

9 views (last 30 days)
I have an app with an uiimage and a button.
When I click on the button:
1. a random image is generated
2. the image is saved using imwrite
3. the ImageSoruce property of the uiimage is set to the name of the file that was just saved
When the object is empty, the image is set correctly.
After that, clicking on the button does not update the image anymore, even though the file has been modified.
To update the source image I follow the this workflow:
1. Generate the matrix that represents the image.
2. Save the matrix to a PNG using imwrite.
3. Set the image source to the name of that file.
This works for the first time (when uiimage is empty), and after that, even though the file is updated, the image is not.
Example code:
pixels = randi([0 255], 1, 2, 3, 'uint8');
img = repmat(repelem([pixels; pixels(:, [2 1], :)], 50, 50), 4, 4);
imwrite(img, 'ImageSourceDemo.png');
app.ImageFixedFile.ImageSource = 'ImageSourceDemo.png';

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 4 Jul 2019
This is due to an internal optimisation in uiimage to avoid unnecessarily reloading the same image. However, under very particular circumstances, the image can be inadvertently modified.
To circumvent this issue you can use any of the following options:
1. Use directly the data instead of the file path:
pixels = randi([0 255], 1, 2, 3, 'uint8');
img = repmat(repelem([pixels; pixels(:, [2 1], :)], 50, 50), 4, 4);
app.ImageFixedFile.ImageSource = img;
2. Load the data to a matrix form instead of using the file path:
pixels = randi([0 255], 1, 2, 3, 'uint8');
img = repmat(repelem([pixels; pixels(:, [2 1], :)], 50, 50), 4, 4);
imwrite(img, 'ImageSourceDemo.png');
imgLoad = imread('ImageSourceDemo.png');
app.ImageFixedFile.ImageSource = imgLoad;
3. Save data with a temporary name that always changes:
pixels = randi([0 255], 1, 2, 3, 'uint8');
img = repmat(repelem([pixels; pixels(:, [2 1], :)], 50, 50), 4, 4);
app.oldfilename = [tempname(pwd), '.png'];
imwrite(img, app.oldfilename);
app.ImageRandFile.ImageSource = app.oldfilename;
  3 Comments
Christian Idzik
Christian Idzik on 20 Jun 2021
Solution:
After updating the picture, I rename it by adding the using the current clock time (using movefile). I then loaded the renamed file into the uiimage directly (image.ImageSource = app.renamedFile;)
With this workaround it works well

Sign in to comment.

More Answers (0)

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!