Home > eidors > graphics > matlab > print_convert.m

print_convert

PURPOSE ^

PRINT_CONVERT: print figures with anti-aliasing and trim them

SYNOPSIS ^

function print_convert(filename, varargin)

DESCRIPTION ^

PRINT_CONVERT: print figures with anti-aliasing and trim them
  PRINT_CONVERT(FILENAME,OPT) prints current figure to FILENAME, which 
  must include extenstion.

  OPT is either a string specifying dpi in the format '-r150' or a struct
  with (some of) these fields:
   opt.resolution   = 150;              % 150 dpi (default: 125)
   opt.pagesize     = [width, height];  % whatever matlab's current units
   opt.jpeg_quality = 85;               % jpeg quality (default: 85)
   opt.imwrite_opts = {'BitDepth',8};   % options to IMWRITE (default: '')
   opt.horz_cut     = 50;               % remove horizontal gaps larger
                                        % than 50 pixels (default: 0)
   opt.horz_space   = 10;               % replace the removed horizontal
                                        % gaps with 10 px of background
   opt.vert_cut     = 50;               % remove vertical gaps larger
                                        % than 50 pixels (default: 0)
   opt.vert_space   = 10;               % replace the removed vertical
                                        % gaps with 10 px of background
   opt.supersampling_factor = 2;        % anti-aliasing (default: 1 for
                                        % images, 2 for graphs). Higher is
                                        % smoother.
   opt.crop_slack   = [top,bot,left,right] %don't crop right to boundary

  Note that opt.imwrite_opts takes precedence over opt.jpeq_quality.

  print_convert has pre-version 3.7 options, which are deprecated

  Examples
   print_convert('outname.png')         % uses default options
   print_convert outname.png
   print_convert outname.png -r150       % set dpi=150
   print_convert('outname.png',opts);   % use options

 See also IMWRITE

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SUBFUNCTIONS ^

SOURCE CODE ^

0001 function print_convert(filename, varargin)
0002 %PRINT_CONVERT: print figures with anti-aliasing and trim them
0003 %  PRINT_CONVERT(FILENAME,OPT) prints current figure to FILENAME, which
0004 %  must include extenstion.
0005 %
0006 %  OPT is either a string specifying dpi in the format '-r150' or a struct
0007 %  with (some of) these fields:
0008 %   opt.resolution   = 150;              % 150 dpi (default: 125)
0009 %   opt.pagesize     = [width, height];  % whatever matlab's current units
0010 %   opt.jpeg_quality = 85;               % jpeg quality (default: 85)
0011 %   opt.imwrite_opts = {'BitDepth',8};   % options to IMWRITE (default: '')
0012 %   opt.horz_cut     = 50;               % remove horizontal gaps larger
0013 %                                        % than 50 pixels (default: 0)
0014 %   opt.horz_space   = 10;               % replace the removed horizontal
0015 %                                        % gaps with 10 px of background
0016 %   opt.vert_cut     = 50;               % remove vertical gaps larger
0017 %                                        % than 50 pixels (default: 0)
0018 %   opt.vert_space   = 10;               % replace the removed vertical
0019 %                                        % gaps with 10 px of background
0020 %   opt.supersampling_factor = 2;        % anti-aliasing (default: 1 for
0021 %                                        % images, 2 for graphs). Higher is
0022 %                                        % smoother.
0023 %   opt.crop_slack   = [top,bot,left,right] %don't crop right to boundary
0024 %
0025 %  Note that opt.imwrite_opts takes precedence over opt.jpeq_quality.
0026 %
0027 %  print_convert has pre-version 3.7 options, which are deprecated
0028 %
0029 %  Examples
0030 %   print_convert('outname.png')         % uses default options
0031 %   print_convert outname.png
0032 %   print_convert outname.png -r150       % set dpi=150
0033 %   print_convert('outname.png',opts);   % use options
0034 %
0035 % See also IMWRITE
0036  
0037 % (C) Andy Adler and Bartlomiej Grychtol 2010-2013. License: GPL v2 or v3.
0038 % $Id: print_convert.m 5505 2017-06-05 14:25:08Z aadler $
0039 %
0040 %  Compatibility with pre-3.7 features:
0041 %  ------------------------------------
0042 %  PRINT_CONVERT(FILENAME, OPTIONS, PAGEHWR)
0043 %
0044 %  FILENAME : filename to print to file type is the extension
0045 %  OPTIONS  : specify dpi as '-density N'
0046 %  PAGEHWR  : set page hight/width to control shape of figures
0047 %
0048 %   print_convert('outname.png','-density 150') % resolution to 150 dpi
0049 %   print_convert('outname.png','-density 150', 0.5)
0050  
0051 if ischar(filename) && strcmp(filename,'UNIT_TEST'); do_unit_test; return; end
0052 
0053 pp = parse_options(filename, varargin{:});
0054 
0055 tmpnam = [tempname,'.png'];
0056 
0057 old_ihc = get(gcf, 'InvertHardcopy');
0058 old_col = get(gcf, 'Color');
0059 set(gcf,'InvertHardCopy','off'); 
0060 set(gcf,'Color','w');
0061 
0062 set(gcf,'PaperPosition',pp.posn); % I wish matlab had unwind protect - like octave does!
0063 %%% The -dpng driver is broken in R2014a on linux (and maybe others);
0064 print('-dpng',pp.resolution,tmpnam);
0065 set(gcf,'PaperPosition',pp.page);
0066  
0067 set(gcf,'InvertHardCopy',old_ihc); %
0068 set(gcf,'Color',old_col);
0069  
0070 im = imread(tmpnam,'png');
0071 delete(tmpnam);
0072 
0073 im = bitmap_downsize(im, pp.factor);
0074 im = crop_image(im,pp);
0075 try
0076    imwrite(im,filename,pp.imwrite_opts{:});
0077 catch e
0078    eidors_msg(['Call to IMWRITE failed.'...
0079                'Probably opt.imwrite_opts is incorrect for %s files.'],...
0080                upper(pp.fmt), 1);
0081    disp('opt.imwrite_opts:');
0082    disp(pp.imwrite_opts);
0083    rethrow(e);
0084 end
0085 
0086 function im = crop_image(im,pp)
0087    tu = pp.crop_slack(1);
0088    bu = pp.crop_slack(2) + 1; %remove starting one more
0089    lu = pp.crop_slack(3);
0090    ru = pp.crop_slack(4) + 1;
0091 
0092    szim = size(im);
0093    bdr = squeeze(mean(double(im(1,:,:)),2));
0094  
0095    isbdr = true(szim(1),szim(2));
0096    for i=1:szim(3);
0097      isbdr = isbdr & (im(:,:,i) == bdr(i));
0098    end
0099  
0100    horz = [true,all(isbdr,1),true];
0101    horzpt = find(diff(horz)) - 1; % first 'true'
0102    if isempty(horzpt)
0103       eidors_msg('Image is blank. Cropping aborted.',1);
0104       return
0105    end
0106    im(:,horzpt(end)+ru:end,:)= []; % remove higher first
0107    if pp.horz_cut >0;
0108       horz_e_pt = find(diff(horz)==-1) -1; horz_e_pt(1) = [];
0109       horz_s_pt = find(diff(horz)==+1)   ; horz_s_pt(end) = [];
0110       idx = find(horz_e_pt - horz_s_pt > pp.horz_cut);
0111       for i=fliplr(idx) % remove higher first
0112         im(:,horz_s_pt(i)+pp.horz_space:horz_e_pt(i),:)= [];
0113       end
0114    end
0115    im(:,1:horzpt(1)-lu ,:)= [];
0116  
0117    vert = [true,all(isbdr,2)',true];
0118    vertpt = find(diff(vert)) - 1; % first 'true'
0119    im(vertpt(end)+bu:end,:,:)= [];
0120    if pp.vert_cut >0;
0121       vert_e_pt = find(diff(vert)==-1) -1; vert_e_pt(1) = [];
0122       vert_s_pt = find(diff(vert)==+1)   ; vert_s_pt(end) = [];
0123       idx = find(vert_e_pt - vert_s_pt > pp.vert_cut);
0124       for i=fliplr(idx) % remove higher first
0125         im(vert_s_pt(i)+pp.vert_space:vert_e_pt(i),:,:)= [];
0126       end
0127    end
0128    im(1:vertpt(1)-tu ,:,:)= [];
0129  
0130     
0131 % factor = 1 if all plots only contain images, 2 otherwise
0132 function f = default_factor
0133    f = 1; % default for images
0134    sp = get(gcf,'Children'); % subplots
0135    for i = 1:length(sp)
0136       obj = get(sp(i),'Children');
0137       tp  = get(obj,'Type');
0138       if ~all(strcmp(tp,'image'))
0139          f = 2;
0140          return;
0141       end
0142    end 
0143    
0144 function fmt = parse_format(filename)   
0145     ext = lower(regexp(filename,'(?<=\.).+$','match'));
0146     if isempty(ext); error('no filename extension detected (%s)',filename); end
0147     switch ext{1}
0148        case {'jpg', 'jpeg'}
0149           fmt = 'jpg';
0150        case {'j2c', 'j2k', 'jp2'}
0151           fmt = 'jp2';
0152        case {'tif','tiff'}
0153           fmt = 'tif';
0154        otherwise
0155           fmt = ext{1};
0156     end
0157        
0158 function pp = parse_options(filename,varargin)
0159    
0160    pp.fmt = parse_format(filename);
0161 
0162    pp.page = get(gcf,'PaperPosition');
0163    pp.posn = pp.page;
0164    pp.jpeg_quality = 85; % default jpeg quality
0165    pp.imwrite_opts = {}; % initial
0166    pp.horz_cut = 50;
0167    pp.horz_space = 10;
0168    pp.vert_cut = 50;
0169    pp.vert_space = 10;
0170    pp.factor = default_factor;
0171    pp.resolution = sprintf('-r%d',125 * pp.factor);
0172    pp.crop_slack = [0,0,0,0];
0173    
0174    
0175  
0176 % Old options
0177    if nargin< 2;   
0178       return; 
0179    end
0180    if nargin>=3
0181       pp.posn(4) = pp.posn(3)*varargin{2};  
0182    end
0183  
0184    opt = varargin{1};
0185    if ischar(opt)
0186       val =regexp(opt,'-density (\d+)','tokens');
0187       if ~isempty(val);
0188          pp.resolution = sprintf('-r%d', str2double(val{1}{1}) * pp.factor);
0189       end
0190       val =regexp(opt,'-r(\d+)','tokens');
0191       if ~isempty(val);
0192          pp.resolution = sprintf('-r%d', str2double(val{1}{1}) * pp.factor);
0193       end
0194    elseif isstruct(opt)
0195      if isfield(opt,'supersampling_factor')
0196         pp.factor = opt.supersampling_factor;
0197      end
0198      if isfield(opt,'resolution');
0199          pp.resolution = sprintf('-r%d', opt.resolution * pp.factor);
0200      else
0201          pp.resolution = sprintf('-r%d',125 * pp.factor);
0202      end
0203      if isfield(opt,'pagesize');
0204          pp.posn(3:4) = opt.pagesize;
0205      end
0206      % TODO, this code can copy from opt to pp
0207      if isfield(opt,'jpeg_quality')
0208         pp.jpeg_quality = opt.jpeg_quality;
0209      end
0210      if strcmp(pp.fmt,'jpg')
0211         pp.imwrite_opts = {'quality',pp.jpeg_quality}; 
0212      end
0213      if isfield(opt,'imwrite_opts');
0214         pp.imwrite_opts = opt.imwrite_opts;
0215         if strcmp(pp.fmt,'jpg') && ~any(strcmpi(pp.imwrite_opts,'quality'))
0216            pp.imwrite_opts(end+1:end+2) = {'quality',pp.jpeg_quality};
0217         end
0218      end
0219     
0220      if isfield(opt,'horz_cut');
0221          pp.horz_cut = opt.horz_cut;
0222      end
0223      if isfield(opt,'vert_cut');
0224          pp.vert_cut = opt.vert_cut;
0225      end
0226      if isfield(opt,'vert_space');
0227         if opt.vert_space >= pp.vert_cut;
0228            warrning('Option vert_space must be smaller than vert_cut. Ingoring');
0229         else
0230            pp.vert_space = opt.vert_space;
0231         end
0232      end
0233      if isfield(opt,'horz_space');
0234         if opt.horz_space >= pp.horz_cut;
0235            warrning('Option vert_space must be smaller than vert_cut. Ingoring');
0236         else
0237            pp.horz_space = opt.horz_space;
0238         end
0239      end
0240      if isfield(opt,'crop_slack');
0241         pp.crop_slack = opt.crop_slack;
0242      end
0243    else
0244       error('Can''t parse options');
0245    end
0246  
0247  
0248 function do_unit_test
0249    fprintf('does unit test \n');
0250    fid = fopen('print_convert_test.html','w');
0251    fprintf(fid,'<HTML><BODY>\n');
0252    for i=1:26;
0253      switch i;
0254        case {9,10}; typ = 'jpg';
0255        otherwise; typ = 'png';
0256      end
0257      fprintf(fid,...
0258      '<H1>%02d</H1><table border=1><tr><td><img src="pc%02d.%s"></table>\n',i,i,typ);
0259    end
0260    fprintf(fid,'</BODY></HTML>\n');
0261    fclose(fid);
0262    eidors_msg('TO VIEW OUTPUT, OPEN FILE print_convert_test.html',1);
0263  
0264    im = mk_image( ng_mk_cyl_models(1,[16,.5],.05),1);
0265    clf; show_fem(im);
0266    print_convert pc01.png
0267  
0268    im = mk_image( mk_common_model('b2c2',8), 1:256);
0269    clf; show_fem(im);
0270    print_convert pc02.png
0271  
0272  
0273    clf; subplot(221); show_fem(im); 
0274         subplot(224); show_slices(im); 
0275    print_convert pc03.png
0276  
0277    print_convert pc04.png '-density 50'
0278    print_convert pc05.png '-r100'
0279  
0280    print_convert('pc06.png', '-r100' , 1/8)
0281  
0282    print_convert('pc06.png', '-r100' , 3/1)
0283  
0284    opt.resolution = 100;
0285    print_convert('pc07.png', opt);
0286    opt.pagesize = [8,2];
0287    print_convert('pc08.png', opt);
0288  
0289    print_convert('pc09a.jpg');
0290    
0291    opt.pagesize = [8,6];
0292    print_convert('pc09.jpg', opt);
0293   
0294    
0295    opt.imwrite_opts = {'Quality',20};
0296    print_convert('pc10.jpg', opt);
0297    
0298    opt.imwrite_opts = {'Quality',100};
0299    print_convert('pc10b.jpg', opt);
0300  
0301    opt.imwrite_opts = {};
0302    opt.horz_cut = 50;
0303    print_convert('pc11.png', opt);
0304  
0305    opt.vert_cut = 50;
0306    print_convert('pc12.png', opt);
0307  
0308    clf; subplot(331); show_fem(im); 
0309         subplot(335); show_slices(im); 
0310         subplot(339); show_slices(im); 
0311    opt.vert_cut = 30;
0312    print_convert('pc13.png', opt);
0313    
0314    im = mk_image( ng_mk_cyl_models(1,[16,.5],.05),1);
0315    clf; show_fem(im);
0316    clear opt; opt.supersampling_factor = 1;
0317    print_convert('pc14.png', opt);
0318  
0319    clear opt; opt.supersampling_factor = 2;
0320    print_convert('pc15.png', opt);
0321  
0322    clear opt; opt.supersampling_factor = 3;
0323    print_convert('pc16.png', opt);
0324    
0325    clear opt; opt.supersampling_factor = 4;
0326    print_convert('pc17.png', opt);
0327    
0328    clear opt; opt.supersampling_factor = 8;
0329    print_convert('pc18.png', opt);
0330  
0331

Generated on Fri 01-Jun-2018 15:59:55 by m2html © 2005