Home > data-vis > supporting_functions > export_fig > print2array.m

print2array

PURPOSE ^

PRINT2ARRAY Exports a figure to an image array

SYNOPSIS ^

function [A, bcol] = print2array(fig, res, renderer, gs_options)

DESCRIPTION ^

PRINT2ARRAY  Exports a figure to an image array

 Examples:
   A = print2array
   A = print2array(figure_handle)
   A = print2array(figure_handle, resolution)
   A = print2array(figure_handle, resolution, renderer)
   A = print2array(figure_handle, resolution, renderer, gs_options)
   [A bcol] = print2array(...)

 This function outputs a bitmap image of the given figure, at the desired
 resolution.

 If renderer is '-painters' then ghostcript needs to be installed. This
 can be downloaded from: http://www.ghostscript.com

 IN:
   figure_handle - The handle of the figure to be exported. Default: gcf.
   resolution - Resolution of the output, as a factor of screen
                resolution. Default: 1.
   renderer - string containing the renderer paramater to be passed to
              print. Default: '-opengl'.
   gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
                multiple options are needed, enclose in call array: {'-a','-b'}

 OUT:
   A - MxNx3 uint8 image of the figure.
   bcol - 1x3 uint8 vector of the background color

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SUBFUNCTIONS ^

SOURCE CODE ^

0001 function [A, bcol] = print2array(fig, res, renderer, gs_options)
0002 %PRINT2ARRAY  Exports a figure to an image array
0003 %
0004 % Examples:
0005 %   A = print2array
0006 %   A = print2array(figure_handle)
0007 %   A = print2array(figure_handle, resolution)
0008 %   A = print2array(figure_handle, resolution, renderer)
0009 %   A = print2array(figure_handle, resolution, renderer, gs_options)
0010 %   [A bcol] = print2array(...)
0011 %
0012 % This function outputs a bitmap image of the given figure, at the desired
0013 % resolution.
0014 %
0015 % If renderer is '-painters' then ghostcript needs to be installed. This
0016 % can be downloaded from: http://www.ghostscript.com
0017 %
0018 % IN:
0019 %   figure_handle - The handle of the figure to be exported. Default: gcf.
0020 %   resolution - Resolution of the output, as a factor of screen
0021 %                resolution. Default: 1.
0022 %   renderer - string containing the renderer paramater to be passed to
0023 %              print. Default: '-opengl'.
0024 %   gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
0025 %                multiple options are needed, enclose in call array: {'-a','-b'}
0026 %
0027 % OUT:
0028 %   A - MxNx3 uint8 image of the figure.
0029 %   bcol - 1x3 uint8 vector of the background color
0030 
0031 % Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-
0032 %{
0033 % 05/09/11: Set EraseModes to normal when using opengl or zbuffer
0034 %           renderers. Thanks to Pawel Kocieniewski for reporting the issue.
0035 % 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting it.
0036 % 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure size
0037 %           and erasemode settings. Makes it a bit slower, but more reliable.
0038 %           Thanks to Phil Trinh and Meelis Lootus for reporting the issues.
0039 % 09/12/11: Pass font path to ghostscript.
0040 % 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to
0041 %           Ken Campbell for reporting it.
0042 % 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting it.
0043 % 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for
0044 %           reporting the issue.
0045 % 26/02/15: If temp dir is not writable, use the current folder for temp
0046 %           EPS/TIF files (Javier Paredes)
0047 % 27/02/15: Display suggested workarounds to internal print() error (issue #16)
0048 % 28/02/15: Enable users to specify optional ghostscript options (issue #36)
0049 % 10/03/15: Fixed minor warning reported by Paul Soderlind; fixed code indentation
0050 % 28/05/15: Fixed issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() func)
0051 % 07/07/15: Fixed issue #83: use numeric handles in HG1
0052 %}
0053 
0054     % Generate default input arguments, if needed
0055     if nargin < 2
0056         res = 1;
0057         if nargin < 1
0058             fig = gcf;
0059         end
0060     end
0061     % Warn if output is large
0062     old_mode = get(fig, 'Units');
0063     set(fig, 'Units', 'pixels');
0064     px = get(fig, 'Position');
0065     set(fig, 'Units', old_mode);
0066     npx = prod(px(3:4)*res)/1e6;
0067     if npx > 30
0068         % 30M pixels or larger!
0069         warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx);
0070     end
0071     % Retrieve the background colour
0072     bcol = get(fig, 'Color');
0073     % Set the resolution parameter
0074     res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))];
0075     % Generate temporary file name
0076     tmp_nam = [tempname '.tif'];
0077     try
0078         % Ensure that the temp dir is writable (Javier Paredes 26/2/15)
0079         fid = fopen(tmp_nam,'w');
0080         fwrite(fid,1);
0081         fclose(fid);
0082         delete(tmp_nam);  % cleanup
0083         isTempDirOk = true;
0084     catch
0085         % Temp dir is not writable, so use the current folder
0086         [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
0087         fpath = pwd;
0088         tmp_nam = fullfile(fpath,[fname fext]);
0089         isTempDirOk = false;
0090     end
0091     % Enable users to specify optional ghostscript options (issue #36)
0092     if nargin > 3 && ~isempty(gs_options)
0093         if iscell(gs_options)
0094             gs_options = sprintf(' %s',gs_options{:});
0095         elseif ~ischar(gs_options)
0096             error('gs_options input argument must be a string or cell-array of strings');
0097         else
0098             gs_options = [' ' gs_options];
0099         end
0100     else
0101         gs_options = '';
0102     end
0103     if nargin > 2 && strcmp(renderer, '-painters')
0104         % Print to eps file
0105         if isTempDirOk
0106             tmp_eps = [tempname '.eps'];
0107         else
0108             tmp_eps = fullfile(fpath,[fname '.eps']);
0109         end
0110         print2eps(tmp_eps, fig, 0, renderer, '-loose');
0111         try
0112             % Initialize the command to export to tiff using ghostscript
0113             cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc'];
0114             % Set the font path
0115             fp = font_path();
0116             if ~isempty(fp)
0117                 cmd_str = [cmd_str ' -sFONTPATH="' fp '"'];
0118             end
0119             % Add the filenames
0120             cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"' gs_options];
0121             % Execute the ghostscript command
0122             ghostscript(cmd_str);
0123         catch me
0124             % Delete the intermediate file
0125             delete(tmp_eps);
0126             rethrow(me);
0127         end
0128         % Delete the intermediate file
0129         delete(tmp_eps);
0130         % Read in the generated bitmap
0131         A = imread(tmp_nam);
0132         % Delete the temporary bitmap file
0133         delete(tmp_nam);
0134         % Set border pixels to the correct colour
0135         if isequal(bcol, 'none')
0136             bcol = [];
0137         elseif isequal(bcol, [1 1 1])
0138             bcol = uint8([255 255 255]);
0139         else
0140             for l = 1:size(A, 2)
0141                 if ~all(reshape(A(:,l,:) == 255, [], 1))
0142                     break;
0143                 end
0144             end
0145             for r = size(A, 2):-1:l
0146                 if ~all(reshape(A(:,r,:) == 255, [], 1))
0147                     break;
0148                 end
0149             end
0150             for t = 1:size(A, 1)
0151                 if ~all(reshape(A(t,:,:) == 255, [], 1))
0152                     break;
0153                 end
0154             end
0155             for b = size(A, 1):-1:t
0156                 if ~all(reshape(A(b,:,:) == 255, [], 1))
0157                     break;
0158                 end
0159             end
0160             bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1));
0161             for c = 1:size(A, 3)
0162                 A(:,[1:l-1, r+1:end],c) = bcol(c);
0163                 A([1:t-1, b+1:end],:,c) = bcol(c);
0164             end
0165         end
0166     else
0167         if nargin < 3
0168             renderer = '-opengl';
0169         end
0170         err = false;
0171         % Set paper size
0172         old_pos_mode = get(fig, 'PaperPositionMode');
0173         old_orientation = get(fig, 'PaperOrientation');
0174         set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
0175         try
0176             % Workaround for issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() function)
0177             fp = [];  % in case we get an error below
0178             fp = findall(fig, 'Type','patch', 'LineWidth',0.75);
0179             set(fp, 'LineWidth',0.5);
0180             % Fix issue #83: use numeric handles in HG1
0181             if ~using_hg2(fig),  fig = double(fig);  end
0182             % Print to tiff file
0183             print(fig, renderer, res_str, '-dtiff', tmp_nam);
0184             % Read in the printed file
0185             A = imread(tmp_nam);
0186             % Delete the temporary file
0187             delete(tmp_nam);
0188         catch ex
0189             err = true;
0190         end
0191         set(fp, 'LineWidth',0.75);  % restore original figure appearance
0192         % Reset paper size
0193         set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation);
0194         % Throw any error that occurred
0195         if err
0196             % Display suggested workarounds to internal print() error (issue #16)
0197             fprintf(2, 'An error occured with Matlab''s builtin print function.\nTry setting the figure Renderer to ''painters'' or use opengl(''software'').\n\n');
0198             rethrow(ex);
0199         end
0200         % Set the background color
0201         if isequal(bcol, 'none')
0202             bcol = [];
0203         else
0204             bcol = bcol * 255;
0205             if isequal(bcol, round(bcol))
0206                 bcol = uint8(bcol);
0207             else
0208                 bcol = squeeze(A(1,1,:));
0209             end
0210         end
0211     end
0212     % Check the output size is correct
0213     if isequal(res, round(res))
0214         px = round([px([4 3])*res 3]);  % round() to avoid an indexing warning below
0215         if ~isequal(size(A), px)
0216             % Correct the output size
0217             A = A(1:min(end,px(1)),1:min(end,px(2)),:);
0218         end
0219     end
0220 end
0221 
0222 % Function to return (and create, where necessary) the font path
0223 function fp = font_path()
0224     fp = user_string('gs_font_path');
0225     if ~isempty(fp)
0226         return
0227     end
0228     % Create the path
0229     % Start with the default path
0230     fp = getenv('GS_FONTPATH');
0231     % Add on the typical directories for a given OS
0232     if ispc
0233         if ~isempty(fp)
0234             fp = [fp ';'];
0235         end
0236         fp = [fp getenv('WINDIR') filesep 'Fonts'];
0237     else
0238         if ~isempty(fp)
0239             fp = [fp ':'];
0240         end
0241         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'];
0242     end
0243     user_string('gs_font_path', fp);
0244 end

Generated on Tue 23-May-2017 20:00:55 by m2html © 2005