erez
erez

Reputation: 419

Save axes in GUI as image MATLAB

I know there are a lot of answers regarding this issue but I didn’t found any one that help me.. I have a GUI in MATLAB with 2 axes and I want to save separately each axes as .jpeg or any other format. Any way I have tried – I got either image that including all the GUI or cut figure. Any idea how can I get 2 good images?

Upvotes: 2

Views: 2276

Answers (1)

Suever
Suever

Reputation: 65430

You could loop through all of the axes and call getframe to get just that axes. You can then save the cdata using imwrite.

% Get a list of all axes in the figure
allax = findall(gcf, 'type', 'axes');

for k = 1:numel(allax)
    % Get the axes as an image
    fr = getframe(allax(k));

    % Save the image
    imwrite(fr.cdata, sprintf('%d.png'));
end

If you already have axes handles you can just use those directly

fr = getframe(axes2);
imwrite(fr.cdata, 'axes2.png')

fr = getframe(axes1);
imwrite(fr.cdata, 'axes1.png')

If you want to include the X and Y axes labels, you could do something like

function axes2image(ax, filename)

    hfig = ancestor(ax, 'figure');

    rect = hgconvertunits(hfig, get(ax, 'OuterPosition'), ...
                          get(ax, 'Units'), 'pixels', get(ax, 'Parent'));

    fr = getframe(hfig, rect);
    imwrite(fr.cdata, filename);
end

axes2image(axes2, 'axes2.png')
axes2image(axes1, 'axes1.png')

Upvotes: 2

Related Questions