How do I specify the output sizes of JPEG, PNG, and TIFF images when using the PRINT function in MATLAB?

168 views (last 30 days)

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
The JPEG, PNG, and TIFF drivers in MATLAB 5.x and later rely upon a figure's "PaperPosition" to specify the size of the output file. In addition, since the drivers take a snapshot of the figure in order to generate the image, the resolution of the output is dependent on the "-r" specified when printing. For instance, if my figure's PaperPosition is set to the default for most computers:
[.25 2.5 8 6] (in inches) 8 is the width while 6 is the height.
The default -r value (resolution) is 150 dpi. Therefore "print -djpeg filename" will produce a:
8*150 X 6*150 = 1200 X 900 pixel image
There are two easy ways to make images the size you want (these examples are written for the JPEG driver but the TIFF driver can be substituted):
1) Specify the PaperPosition and resolution to get the desired output size.
For instance, if you want your figure to be of dimensions 400 X 300 pixels in the output file then execute the following code:
plot(1:10) % Example graph
set(gcf,'PaperUnits','inches','PaperPosition',[0 0 4 3])
print -djpeg filename.jpg -r100
The resulting JPEG file will have dimensions 4*100 X 3*100 or 400 X 300.
2) Make the output file the same size as the figure on the screen.
This is a little more involved than #1 but the results are consistent with what you see on the screen. The code to do this is included below. Save it as screen2jpeg.m:
function screen2jpeg(filename)
%SCREEN2JPEG Generate a JPEG file of the current figure with
% dimensions consistent with the figure's screen dimensions.
%
% SCREEN2JPEG('filename') saves the current figure to the
% JPEG file "filename".
%
% Sean P. McCarthy
% Copyright (c) 1984-98 by MathWorks, Inc. All Rights Reserved
if nargin < 1
error('Not enough input arguments!')
end
oldscreenunits = get(gcf,'Units');
oldpaperunits = get(gcf,'PaperUnits');
oldpaperpos = get(gcf,'PaperPosition');
set(gcf,'Units','pixels');
scrpos = get(gcf,'Position');
newpos = scrpos/100;
set(gcf,'PaperUnits','inches',...
'PaperPosition',newpos)
print('-djpeg', filename, '-r100');
drawnow
set(gcf,'Units',oldscreenunits,...
'PaperUnits',oldpaperunits,...
'PaperPosition',oldpaperpos)
Note that for improved image quality, you can create a SCREEN2PNG function based on the code above and change the PRINT command to use the '-dpng' argument instead of the '-djpeg' argument.
Please note that this program is provided "as is" without further support.

More Answers (0)

Categories

Find more on Printing and Saving in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!