PageRenderTime 60ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/src/utils/exportfig.m

http://slac-lucretia.googlecode.com/
MATLAB | 500 lines | 364 code | 31 blank | 105 comment | 75 complexity | 3fb4cc687ce007f07fa078e88d2e0ab0 MD5 | raw file
Possible License(s): BSD-2-Clause
  1. function exportfig(varargin)
  2. %EXPORTFIG Export a figure to Encapsulated Postscript.
  3. % EXPORTFIG(H, FILENAME) writes the figure H to FILENAME. H is
  4. % a figure handle and FILENAME is a string that specifies the
  5. % name of the output file.
  6. %
  7. % EXPORTFIG(...,PARAM1,VAL1,PARAM2,VAL2,...) specifies
  8. % parameters that control various characteristics of the output
  9. % file.
  10. %
  11. % Format Paramter:
  12. % 'Format' one of the strings 'eps','eps2','jpeg','png','preview'
  13. % specifies the output format. Defaults to 'eps'.
  14. % The output format 'preview' does not generate an output
  15. % file but instead creates a new figure window with a
  16. % preview of the exported figure. In this case the
  17. % FILENAME parameter is ignored.
  18. %
  19. % 'Preview' one of the strings 'none', 'tiff'
  20. % specifies a preview for EPS files. Defaults to 'none'.
  21. %
  22. % Size Parameters:
  23. % 'Width' a positive scalar
  24. % specifies the width in the figure's PaperUnits
  25. % 'Height' a positive scalar
  26. % specifies the height in the figure's PaperUnits
  27. %
  28. % Specifying only one dimension sets the other dimension
  29. % so that the exported aspect ratio is the same as the
  30. % figure's current aspect ratio.
  31. % If neither dimension is specified the size defaults to
  32. % the width and height from the figure's PaperPosition.
  33. %
  34. % Rendering Parameters:
  35. % 'Color' one of the strings 'bw', 'gray', 'cmyk'
  36. % 'bw' specifies that lines and text are exported in
  37. % black and all other objects in grayscale
  38. % 'gray' specifies that all objects are exported in grayscale
  39. % 'cmyk' specifies that all objects are exported in color
  40. % using the CMYK color space
  41. % 'Renderer' one of the strings 'painters', 'zbuffer', 'opengl'
  42. % specifies the renderer to use
  43. % 'Resolution' a positive scalar
  44. % specifies the resolution in dots-per-inch.
  45. %
  46. % The default color setting is 'bw'.
  47. %
  48. % Font Parameters:
  49. % 'FontMode' one of the strings 'scaled', 'fixed'
  50. % 'FontSize' a positive scalar
  51. % in 'scaled' mode multiplies with the font size of each
  52. % text object to obtain the exported font size
  53. % in 'fixed' mode specifies the font size of all text
  54. % objects in points
  55. % 'FontEncoding' one of the strings 'latin1', 'adobe'
  56. % specifies the character encoding of the font
  57. %
  58. % If FontMode is 'scaled' but FontSize is not specified then a
  59. % scaling factor is computed from the ratio of the size of the
  60. % exported figure to the size of the actual figure. The minimum
  61. % font size allowed after scaling is 5 points.
  62. % If FontMode is 'fixed' but FontSize is not specified then the
  63. % exported font sizes of all text objects is 7 points.
  64. %
  65. % The default 'FontMode' setting is 'scaled'.
  66. %
  67. % Line Width Parameters:
  68. % 'LineMode' one of the strings 'scaled', 'fixed'
  69. % 'LineWidth' a positive scalar
  70. % the semantics of LineMode and LineWidth are exactly the
  71. % same as FontMode and FontSize, except that they apply
  72. % to line widths instead of font sizes. The minumum line
  73. % width allowed after scaling is 0.5 points.
  74. % If LineMode is 'fixed' but LineWidth is not specified
  75. % then the exported line width of all line objects is 1
  76. % point.
  77. %
  78. % Examples:
  79. % exportfig(gcf,'fig1.eps','height',3);
  80. % Exports the current figure to the file named 'fig1.eps' with
  81. % a height of 3 inches (assuming the figure's PaperUnits is
  82. % inches) and an aspect ratio the same as the figure's aspect
  83. % ratio on screen.
  84. %
  85. % exportfig(gcf, 'fig2.eps', 'FontMode', 'fixed',...
  86. % 'FontSize', 10, 'color', 'cmyk' );
  87. % Exports the current figure to 'fig2.eps' in color with all
  88. % text in 10 point fonts. The size of the exported figure is
  89. % the figure's PaperPostion width and height.
  90. if (nargin < 2)
  91. error('Too few input arguments');
  92. end
  93. % exportfig(H, filename, ...)
  94. H = varargin{1};
  95. if ~ishandle(H) | ~strcmp(get(H,'type'), 'figure')
  96. error('First argument must be a handle to a figure.');
  97. end
  98. filename = varargin{2};
  99. if ~ischar(filename)
  100. error('Second argument must be a string.');
  101. end
  102. paramPairs = varargin(3:end);
  103. % Do some validity checking on param-value pairs
  104. if (rem(length(paramPairs),2) ~= 0)
  105. error(['Invalid input syntax. Optional parameters and values' ...
  106. ' must be in pairs.']);
  107. end
  108. format = 'eps';
  109. preview = 'none';
  110. width = -1;
  111. height = -1;
  112. color = 'bw';
  113. fontsize = -1;
  114. fontmode='scaled';
  115. linewidth = -1;
  116. linemode=[];
  117. fontencoding = 'latin1';
  118. renderer = [];
  119. resolution = [];
  120. % Process param-value pairs
  121. args = {};
  122. for k = 1:2:length(paramPairs)
  123. param = lower(paramPairs{k});
  124. if (~ischar(param))
  125. error('Optional parameter names must be strings');
  126. end
  127. value = paramPairs{k+1};
  128. switch (param)
  129. case 'format'
  130. format = value;
  131. if (~strcmp(format,{'eps','eps2','jpeg','png','preview'}))
  132. error(['Format must be ''eps'', ''eps2'', ''jpeg'', ''png'' or' ...
  133. ' ''preview''.']);
  134. end
  135. case 'preview'
  136. preview = value;
  137. if (~strcmp(preview,{'none','tiff'}))
  138. error('Preview must be ''none'' or ''tiff''.');
  139. end
  140. case 'width'
  141. width = LocalToNum(value);
  142. if(~LocalIsPositiveScalar(width))
  143. error('Width must be a numeric scalar > 0');
  144. end
  145. case 'height'
  146. height = LocalToNum(value);
  147. if(~LocalIsPositiveScalar(height))
  148. error('Height must be a numeric scalar > 0');
  149. end
  150. case 'color'
  151. color = lower(value);
  152. if (~strcmp(color,{'bw','gray','cmyk'}))
  153. error('Color must be ''bw'', ''gray'' or ''cmyk''.');
  154. end
  155. case 'fontmode'
  156. fontmode = lower(value);
  157. if (~strcmp(fontmode,{'scaled','fixed'}))
  158. error('FontMode must be ''scaled'' or ''fixed''.');
  159. end
  160. case 'fontsize'
  161. fontsize = LocalToNum(value);
  162. if(~LocalIsPositiveScalar(fontsize))
  163. error('FontSize must be a numeric scalar > 0');
  164. end
  165. case 'fontencoding'
  166. fontencoding = lower(value);
  167. if (~strcmp(fontencoding,{'latin1','adobe'}))
  168. error('FontEncoding must be ''latin1'' or ''adobe''.');
  169. end
  170. case 'linemode'
  171. linemode = lower(value);
  172. if (~strcmp(linemode,{'scaled','fixed'}))
  173. error('LineMode must be ''scaled'' or ''fixed''.');
  174. end
  175. case 'linewidth'
  176. linewidth = LocalToNum(value);
  177. if(~LocalIsPositiveScalar(linewidth))
  178. error('LineWidth must be a numeric scalar > 0');
  179. end
  180. case 'renderer'
  181. renderer = lower(value);
  182. if (~strcmp(renderer,{'painters','zbuffer','opengl'}))
  183. error('Renderer must be ''painters'', ''zbuffer'' or ''opengl''.');
  184. end
  185. case 'resolution'
  186. resolution = LocalToNum(value);
  187. if ~(isnumeric(value) & (prod(size(value)) == 1) & (value >= 0));
  188. error('Resolution must be a numeric scalar >= 0');
  189. end
  190. otherwise
  191. error(['Unrecognized option ' param '.']);
  192. end
  193. end
  194. allLines = findall(H, 'type', 'line');
  195. allText = findall(H, 'type', 'text');
  196. allAxes = findall(H, 'type', 'axes');
  197. allImages = findall(H, 'type', 'image');
  198. allLights = findall(H, 'type', 'light');
  199. allPatch = findall(H, 'type', 'patch');
  200. allSurf = findall(H, 'type', 'surface');
  201. allRect = findall(H, 'type', 'rectangle');
  202. allFont = [allText; allAxes];
  203. allColor = [allLines; allText; allAxes; allLights];
  204. allMarker = [allLines; allPatch; allSurf];
  205. allEdge = [allPatch; allSurf];
  206. allCData = [allImages; allPatch; allSurf];
  207. old.objs = {};
  208. old.prop = {};
  209. old.values = {};
  210. % Process format and preview parameter
  211. showPreview = strcmp(format,'preview');
  212. if showPreview
  213. format = 'png';
  214. filename = [tempName '.png'];
  215. end
  216. if strncmp(format,'eps',3) & ~strcmp(preview,'none')
  217. args = {args{:}, ['-' preview]};
  218. end
  219. hadError = 0;
  220. try
  221. % Process size parameters
  222. paperPos = get(H, 'PaperPosition');
  223. old = LocalPushOldData(old, H, 'PaperPosition', paperPos);
  224. figureUnits = get(H, 'Units');
  225. set(H, 'Units', get(H,'PaperUnits'));
  226. figurePos = get(H, 'Position');
  227. aspectRatio = figurePos(3)/figurePos(4);
  228. set(H, 'Units', figureUnits);
  229. if (width == -1) & (height == -1)
  230. width = paperPos(3);
  231. height = paperPos(4);
  232. elseif (width == -1)
  233. width = height * aspectRatio;
  234. elseif (height == -1)
  235. height = width / aspectRatio;
  236. end
  237. set(H, 'PaperPosition', [0 0 width height]);
  238. paperPosMode = get(H, 'PaperPositionMode');
  239. old = LocalPushOldData(old, H, 'PaperPositionMode', paperPosMode);
  240. set(H, 'PaperPositionMode', 'manual');
  241. % Process rendering parameters
  242. switch (color)
  243. case {'bw', 'gray'}
  244. if ~strcmp(color,'bw') & strncmp(format,'eps',3)
  245. format = [format 'c'];
  246. end
  247. args = {args{:}, ['-d' format]};
  248. %compute and set gray colormap
  249. oldcmap = get(H,'Colormap');
  250. newgrays = 0.30*oldcmap(:,1) + 0.59*oldcmap(:,2) + 0.11*oldcmap(:,3);
  251. newcmap = [newgrays newgrays newgrays];
  252. old = LocalPushOldData(old, H, 'Colormap', oldcmap);
  253. set(H, 'Colormap', newcmap);
  254. %compute and set ColorSpec and CData properties
  255. old = LocalUpdateColors(allColor, 'color', old);
  256. old = LocalUpdateColors(allAxes, 'xcolor', old);
  257. old = LocalUpdateColors(allAxes, 'ycolor', old);
  258. old = LocalUpdateColors(allAxes, 'zcolor', old);
  259. old = LocalUpdateColors(allMarker, 'MarkerEdgeColor', old);
  260. old = LocalUpdateColors(allMarker, 'MarkerFaceColor', old);
  261. old = LocalUpdateColors(allEdge, 'EdgeColor', old);
  262. old = LocalUpdateColors(allEdge, 'FaceColor', old);
  263. old = LocalUpdateColors(allCData, 'CData', old);
  264. case 'cmyk'
  265. if strncmp(format,'eps',3)
  266. format = [format 'c'];
  267. args = {args{:}, ['-d' format], '-cmyk'};
  268. else
  269. args = {args{:}, ['-d' format]};
  270. end
  271. otherwise
  272. error('Invalid Color parameter');
  273. end
  274. if (~isempty(renderer))
  275. args = {args{:}, ['-' renderer]};
  276. end
  277. if (~isempty(resolution)) | ~strncmp(format,'eps',3)
  278. if isempty(resolution)
  279. resolution = 0;
  280. end
  281. args = {args{:}, ['-r' int2str(resolution)]};
  282. end
  283. % Process font parameters
  284. if (~isempty(fontmode))
  285. oldfonts = LocalGetAsCell(allFont,'FontSize');
  286. switch (fontmode)
  287. case 'fixed'
  288. oldfontunits = LocalGetAsCell(allFont,'FontUnits');
  289. old = LocalPushOldData(old, allFont, {'FontUnits'}, oldfontunits);
  290. set(allFont,'FontUnits','points');
  291. if (fontsize == -1)
  292. set(allFont,'FontSize',7);
  293. else
  294. set(allFont,'FontSize',fontsize);
  295. end
  296. case 'scaled'
  297. if (fontsize == -1)
  298. wscale = width/figurePos(3);
  299. hscale = height/figurePos(4);
  300. scale = min(wscale, hscale);
  301. else
  302. scale = fontsize;
  303. end
  304. newfonts = LocalScale(oldfonts,scale,5);
  305. set(allFont,{'FontSize'},newfonts);
  306. otherwise
  307. error('Invalid FontMode parameter');
  308. end
  309. % make sure we push the size after the units
  310. old = LocalPushOldData(old, allFont, {'FontSize'}, oldfonts);
  311. end
  312. if strcmp(fontencoding,'adobe') & strncmp(format,'eps',3)
  313. args = {args{:}, '-adobecset'};
  314. end
  315. % Process linewidth parameters
  316. if (~isempty(linemode))
  317. oldlines = LocalGetAsCell(allMarker,'LineWidth');
  318. old = LocalPushOldData(old, allMarker, {'LineWidth'}, oldlines);
  319. switch (linemode)
  320. case 'fixed'
  321. if (linewidth == -1)
  322. set(allMarker,'LineWidth',1);
  323. else
  324. set(allMarker,'LineWidth',linewidth);
  325. end
  326. case 'scaled'
  327. if (linewidth == -1)
  328. wscale = width/figurePos(3);
  329. hscale = height/figurePos(4);
  330. scale = min(wscale, hscale);
  331. else
  332. scale = linewidth;
  333. end
  334. newlines = LocalScale(oldlines, scale, 0.5);
  335. set(allMarker,{'LineWidth'},newlines);
  336. otherwise
  337. error('Invalid LineMode parameter');
  338. end
  339. end
  340. % Export
  341. print(H, filename, args{:});
  342. catch
  343. hadError = 1;
  344. end
  345. % Restore figure settings
  346. for n=1:length(old.objs)
  347. set(old.objs{n}, old.prop{n}, old.values{n});
  348. end
  349. if hadError
  350. error(deblank(lasterr));
  351. end
  352. % Show preview if requested
  353. if showPreview
  354. X = imread(filename,'png');
  355. delete(filename);
  356. f = figure( 'Name', 'Preview', ...
  357. 'Menubar', 'none', ...
  358. 'NumberTitle', 'off', ...
  359. 'Visible', 'off');
  360. image(X);
  361. axis image;
  362. ax = findobj(f, 'type', 'axes');
  363. set(ax, 'Units', get(H,'PaperUnits'), ...
  364. 'Position', [0 0 width height], ...
  365. 'Visible', 'off');
  366. set(ax, 'Units', 'pixels');
  367. axesPos = get(ax,'Position');
  368. figPos = get(f,'Position');
  369. rootSize = get(0,'ScreenSize');
  370. figPos(3:4) = axesPos(3:4);
  371. if figPos(1) + figPos(3) > rootSize(3)
  372. figPos(1) = rootSize(3) - figPos(3) - 50;
  373. end
  374. if figPos(2) + figPos(4) > rootSize(4)
  375. figPos(2) = rootSize(4) - figPos(4) - 50;
  376. end
  377. set(f, 'Position',figPos, ...
  378. 'Visible', 'on');
  379. end
  380. %
  381. % Local Functions
  382. %
  383. function outData = LocalPushOldData(inData, objs, prop, values)
  384. outData.objs = {inData.objs{:}, objs};
  385. outData.prop = {inData.prop{:}, prop};
  386. outData.values = {inData.values{:}, values};
  387. function cellArray = LocalGetAsCell(fig,prop);
  388. cellArray = get(fig,prop);
  389. if (~isempty(cellArray)) & (~iscell(cellArray))
  390. cellArray = {cellArray};
  391. end
  392. function newArray = LocalScale(inArray, scale, minValue)
  393. n = length(inArray);
  394. newArray = cell(n,1);
  395. for k=1:n
  396. newArray{k} = max(minValue,scale*inArray{k}(1));
  397. end
  398. function newArray = LocalMapToGray(inArray);
  399. n = length(inArray);
  400. newArray = cell(n,1);
  401. for k=1:n
  402. color = inArray{k};
  403. if (~isempty(color))
  404. if ischar(color)
  405. switch color(1)
  406. case 'y'
  407. color = [1 1 0];
  408. case 'm'
  409. color = [1 0 1];
  410. case 'c'
  411. color = [0 1 1];
  412. case 'r'
  413. color = [1 0 0];
  414. case 'g'
  415. color = [0 1 0];
  416. case 'b'
  417. color = [0 0 1];
  418. case 'w'
  419. color = [1 1 1];
  420. case 'k'
  421. color = [0 0 0];
  422. otherwise
  423. newArray{k} = color;
  424. end
  425. end
  426. if ~ischar(color)
  427. color = 0.30*color(1) + 0.59*color(2) + 0.11*color(3);
  428. end
  429. end
  430. if isempty(color) | ischar(color)
  431. newArray{k} = color;
  432. else
  433. newArray{k} = [color color color];
  434. end
  435. end
  436. function newArray = LocalMapCData(inArray);
  437. n = length(inArray);
  438. newArray = cell(n,1);
  439. for k=1:n
  440. color = inArray{k};
  441. if (ndims(color) == 3) & isa(color,'double')
  442. gray = 0.30*color(:,:,1) + 0.59*color(:,:,2) + 0.11*color(:,:,3);
  443. color(:,:,1) = gray;
  444. color(:,:,2) = gray;
  445. color(:,:,3) = gray;
  446. end
  447. newArray{k} = color;
  448. end
  449. function outData = LocalUpdateColors(inArray, prop, inData)
  450. value = LocalGetAsCell(inArray,prop);
  451. outData.objs = {inData.objs{:}, inArray};
  452. outData.prop = {inData.prop{:}, {prop}};
  453. outData.values = {inData.values{:}, value};
  454. if (~isempty(value))
  455. if strcmp(prop,'CData')
  456. value = LocalMapCData(value);
  457. else
  458. value = LocalMapToGray(value);
  459. end
  460. set(inArray,{prop},value);
  461. end
  462. function bool = LocalIsPositiveScalar(value)
  463. bool = isnumeric(value) & ...
  464. prod(size(value)) == 1 & ...
  465. value > 0;
  466. function value = LocalToNum(value)
  467. if ischar(value)
  468. value = str2num(value);
  469. end