Why does IMWRITE produce an empty image when I try to save a figure to the disk folder?

I currently have a MATLAB figure that has a button to allow the user to save that image to the folder. I would like when the user clicks on the button, the save dialog window to appear so that the user can specify the name, type and location.
From the search that I did in here, I think I need to use uiputfile and imwrite to accomplish this. I tried the code below which is called when the user click on the save button but it saves an empty image. fh3 is the handle for the figure.
function pbsave_callback(source, eventdata, fh3)
[files, path, index] = uiputfile({'*.jpg';'*.gif';'*.*'},'Save As');
imwrite(fh3, files, 'jpg');
end

 채택된 답변

IMWRITE needs an array containing the captured pixels as input, not the figure handle:
function pbsave_callback(source, eventdata, fh3)
[FileName, FilePath] = uiputfile({'*.jpg';'*.gif';'*.*'},'Save As');
File = fullfile(FilePath, FileName);
Img = getframe(fh3);
imwrite(Img.cdata, File, 'jpg');
I've used FULLFILE to consider the chosen folder.
EDITED: "FileName" -> "File", 1 output for GETFRAME - omit support of Matlab 5.3

댓글 수: 2

Thanks Jan, the code saves the image perfectly with everything in place. I am just wondering what is the use of File as you are not using it in the code. Also why are you checking for Map if empty or not?
@S: I've fixed the FileName typo. Using GETFRAME with 2 outputs and catching an empty Map supports indexed colors of Matlab R11. I'll remove this immediately and hope, that this does not affect too many readers...

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Walter Roberson
Walter Roberson 2011년 2월 7일
imwrite() writes a matrix of data as an image. It is taking your fh3 as a single 1 x 1 pixel of image data.
Use saveas() to copy figures to image files.
S
S 2011년 2월 7일
Thanks Walter, I tried saveas() and it worked but it messed up my uicontrols on the figure (I had a button and dropdown at the top but the saved image shows them almost in the middle). Is there anyway I can have the saved image appear the same as it was before on the screen?

댓글 수: 2

What Units are you using for the controls?
When you saveas() or print() the figure PaperPosition and PaperPositionMode take effect, with an effective resize operation.
I recommend you use the matlab file exchange contribution "export_fig"
Im using the default units ( should be pixels). It could be true however with imwrite suggested by Jan's, it kept the positions of all the uicontrols in place. Thank you very much for you suggestions.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Images에 대해 자세히 알아보기

제품

질문:

S
S
2011년 2월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by