source: issm/trunk/externalpackages/export_fig/print2array.m

Last change on this file was 24686, checked in by Mathieu Morlighem, 5 years ago

merged trunk-jpl and trunk for revision 24684

File size: 10.2 KB
Line 
1function [A, bcol] = print2array(fig, res, renderer, gs_options)
2%PRINT2ARRAY Exports a figure to an image array
3%
4% Examples:
5% A = print2array
6% A = print2array(figure_handle)
7% A = print2array(figure_handle, resolution)
8% A = print2array(figure_handle, resolution, renderer)
9% A = print2array(figure_handle, resolution, renderer, gs_options)
10% [A bcol] = print2array(...)
11%
12% This function outputs a bitmap image of the given figure, at the desired
13% resolution.
14%
15% If renderer is '-painters' then ghostcript needs to be installed. This
16% can be downloaded from: http://www.ghostscript.com
17%
18% IN:
19% figure_handle - The handle of the figure to be exported. Default: gcf.
20% resolution - Resolution of the output, as a factor of screen
21% resolution. Default: 1.
22% renderer - string containing the renderer paramater to be passed to
23% print. Default: '-opengl'.
24% gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
25% multiple options are needed, enclose in call array: {'-a','-b'}
26%
27% OUT:
28% A - MxNx3 uint8 image of the figure.
29% bcol - 1x3 uint8 vector of the background color
30
31% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-
32%{
33% 05/09/11: Set EraseModes to normal when using opengl or zbuffer
34% renderers. Thanks to Pawel Kocieniewski for reporting the issue.
35% 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting it.
36% 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure size
37% and erasemode settings. Makes it a bit slower, but more reliable.
38% Thanks to Phil Trinh and Meelis Lootus for reporting the issues.
39% 09/12/11: Pass font path to ghostscript.
40% 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to
41% Ken Campbell for reporting it.
42% 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting it.
43% 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for
44% reporting the issue.
45% 26/02/15: If temp dir is not writable, use the current folder for temp
46% EPS/TIF files (Javier Paredes)
47% 27/02/15: Display suggested workarounds to internal print() error (issue #16)
48% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
49% 10/03/15: Fixed minor warning reported by Paul Soderlind; fixed code indentation
50% 28/05/15: Fixed issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() func)
51% 07/07/15: Fixed issue #83: use numeric handles in HG1
52% 11/12/16: Fixed cropping issue reported by Harry D.
53% 29/09/18: Fixed issue #254: error in print2array>read_tif_img
54%}
55
56 % Generate default input arguments, if needed
57 if nargin < 2
58 res = 1;
59 if nargin < 1
60 fig = gcf;
61 end
62 end
63 % Warn if output is large
64 old_mode = get(fig, 'Units');
65 set(fig, 'Units', 'pixels');
66 px = get(fig, 'Position');
67 set(fig, 'Units', old_mode);
68 npx = prod(px(3:4)*res)/1e6;
69 if npx > 30
70 % 30M pixels or larger!
71 warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx);
72 end
73 % Retrieve the background colour
74 bcol = get(fig, 'Color');
75 % Set the resolution parameter
76 res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))];
77 % Generate temporary file name
78 tmp_nam = [tempname '.tif'];
79 try
80 % Ensure that the temp dir is writable (Javier Paredes 26/2/15)
81 fid = fopen(tmp_nam,'w');
82 fwrite(fid,1);
83 fclose(fid);
84 delete(tmp_nam); % cleanup
85 isTempDirOk = true;
86 catch
87 % Temp dir is not writable, so use the current folder
88 [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
89 fpath = pwd;
90 tmp_nam = fullfile(fpath,[fname fext]);
91 isTempDirOk = false;
92 end
93 % Enable users to specify optional ghostscript options (issue #36)
94 if nargin > 3 && ~isempty(gs_options)
95 if iscell(gs_options)
96 gs_options = sprintf(' %s',gs_options{:});
97 elseif ~ischar(gs_options)
98 error('gs_options input argument must be a string or cell-array of strings');
99 else
100 gs_options = [' ' gs_options];
101 end
102 else
103 gs_options = '';
104 end
105 if nargin > 2 && strcmp(renderer, '-painters')
106 % First try to print directly to tif file
107 try
108 % Print the file into a temporary TIF file and read it into array A
109 [A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam);
110 if err, rethrow(ex); end
111 catch % error - try to print to EPS and then using Ghostscript to TIF
112 % Print to eps file
113 if isTempDirOk
114 tmp_eps = [tempname '.eps'];
115 else
116 tmp_eps = fullfile(fpath,[fname '.eps']);
117 end
118 print2eps(tmp_eps, fig, 0, renderer, '-loose');
119 try
120 % Initialize the command to export to tiff using ghostscript
121 cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc'];
122 % Set the font path
123 fp = font_path();
124 if ~isempty(fp)
125 cmd_str = [cmd_str ' -sFONTPATH="' fp '"'];
126 end
127 % Add the filenames
128 cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"' gs_options];
129 % Execute the ghostscript command
130 ghostscript(cmd_str);
131 catch me
132 % Delete the intermediate file
133 delete(tmp_eps);
134 rethrow(me);
135 end
136 % Delete the intermediate file
137 delete(tmp_eps);
138 % Read in the generated bitmap
139 A = imread(tmp_nam);
140 % Delete the temporary bitmap file
141 delete(tmp_nam);
142 end
143 % Set border pixels to the correct colour
144 if isequal(bcol, 'none')
145 bcol = [];
146 elseif isequal(bcol, [1 1 1])
147 bcol = uint8([255 255 255]);
148 else
149 for l = 1:size(A, 2)
150 if ~all(reshape(A(:,l,:) == 255, [], 1))
151 break;
152 end
153 end
154 for r = size(A, 2):-1:l
155 if ~all(reshape(A(:,r,:) == 255, [], 1))
156 break;
157 end
158 end
159 for t = 1:size(A, 1)
160 if ~all(reshape(A(t,:,:) == 255, [], 1))
161 break;
162 end
163 end
164 for b = size(A, 1):-1:t
165 if ~all(reshape(A(b,:,:) == 255, [], 1))
166 break;
167 end
168 end
169 bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1));
170 for c = 1:size(A, 3)
171 A(:,[1:l-1, r+1:end],c) = bcol(c);
172 A([1:t-1, b+1:end],:,c) = bcol(c);
173 end
174 end
175 else
176 if nargin < 3
177 renderer = '-opengl';
178 end
179 % Print the file into a temporary TIF file and read it into array A
180 [A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam);
181 % Throw any error that occurred
182 if err
183 % Display suggested workarounds to internal print() error (issue #16)
184 fprintf(2, 'An error occured with Matlab''s builtin print function.\nTry setting the figure Renderer to ''painters'' or use opengl(''software'').\n\n');
185 rethrow(ex);
186 end
187 % Set the background color
188 if isequal(bcol, 'none')
189 bcol = [];
190 else
191 bcol = bcol * 255;
192 if isequal(bcol, round(bcol))
193 bcol = uint8(bcol);
194 else
195 bcol = squeeze(A(1,1,:));
196 end
197 end
198 end
199 % Check the output size is correct
200 if isequal(res, round(res))
201 px = round([px([4 3])*res 3]); % round() to avoid an indexing warning below
202 if ~isequal(size(A), px)
203 % Correct the output size
204 A = A(1:min(end,px(1)),1:min(end,px(2)),:);
205 end
206 end
207end
208
209% Function to create a TIF image of the figure and read it into an array
210function [A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam)
211 A = []; % fix for issue #254
212 err = false;
213 ex = [];
214 % Temporarily set the paper size
215 old_pos_mode = get(fig, 'PaperPositionMode');
216 old_orientation = get(fig, 'PaperOrientation');
217 set(fig, 'PaperPositionMode','auto', 'PaperOrientation','portrait');
218 try
219 % Workaround for issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() function)
220 fp = []; % in case we get an error below
221 fp = findall(fig, 'Type','patch', 'LineWidth',0.75);
222 set(fp, 'LineWidth',0.5);
223 % Fix issue #83: use numeric handles in HG1
224 if ~using_hg2(fig), fig = double(fig); end
225 % Print to tiff file
226 print(fig, renderer, res_str, '-dtiff', tmp_nam);
227 % Read in the printed file
228 A = imread(tmp_nam);
229 % Delete the temporary file
230 delete(tmp_nam);
231 catch ex
232 err = true;
233 end
234 set(fp, 'LineWidth',0.75); % restore original figure appearance
235 % Reset the paper size
236 set(fig, 'PaperPositionMode',old_pos_mode, 'PaperOrientation',old_orientation);
237end
238
239% Function to return (and create, where necessary) the font path
240function fp = font_path()
241 fp = user_string('gs_font_path');
242 if ~isempty(fp)
243 return
244 end
245 % Create the path
246 % Start with the default path
247 fp = getenv('GS_FONTPATH');
248 % Add on the typical directories for a given OS
249 if ispc
250 if ~isempty(fp)
251 fp = [fp ';'];
252 end
253 fp = [fp getenv('WINDIR') filesep 'Fonts'];
254 else
255 if ~isempty(fp)
256 fp = [fp ':'];
257 end
258 fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
259 end
260 user_string('gs_font_path', fp);
261end
Note: See TracBrowser for help on using the repository browser.