From: Jkarretero Jkarretero on
I have written a function that does what you are asking for:

imageSize is a vector of 2 values indicating width & height.
fileName and imageSize are optionals.

function saveImage (figureHandle, fileName, imageSize)

if ~exist('fileName','var'), fileName='image.png'; end

if exist('imageSize','var')
% Adjust figure to size required
set(figureHandle, 'Position', [1 100 imageSize(1) imageSize(2)]);
end

% Convert figure to image
set(figureHandle, 'Visible', 'on');
frame = getframe(figureHandle);
set(figureHandle,'Visible','off');
imagen = frame.cdata;

% Save the image to disk
imwrite(imagen, fileName);
end