Commit dec520d3 authored by Simone Liuzzo's avatar Simone Liuzzo

added folder for matlab extensions (exportfig in it)

parent a3d2dcc8
/*
* Based on code snippet from
* http://java.sun.com/developer/technicalArticles/releases/data/
*
* Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to license terms.
*/
import java.awt.image.BufferedImage;
import java.awt.datatransfer.*;
public class ImageSelection implements Transferable {
private static final DataFlavor flavors[] =
{DataFlavor.imageFlavor};
private BufferedImage image;
public ImageSelection(BufferedImage image) {
this.image = image;
}
// Transferable
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (flavor.equals(flavors[0]) == false) {
throw new UnsupportedFlavorException(flavor);
}
return image;
}
public DataFlavor[] getTransferDataFlavors() {
return flavors;
}
public boolean isDataFlavorSupported(DataFlavor
flavor) {
return flavor.equals(flavors[0]);
}
}
\ No newline at end of file
Copyright (c) 2014, Oliver J. Woodford, Yair M. Altman
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This diff is collapsed.
%APPEND_PDFS Appends/concatenates multiple PDF files
%
% Example:
% append_pdfs(output, input1, input2, ...)
% append_pdfs(output, input_list{:})
% append_pdfs test.pdf temp1.pdf temp2.pdf
%
% This function appends multiple PDF files to an existing PDF file, or
% concatenates them into a PDF file if the output file doesn't yet exist.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% IN:
% output - string of output file name (including the extension, .pdf).
% If it exists it is appended to; if not, it is created.
% input1 - string of an input file name (including the extension, .pdf).
% All input files are appended in order.
% input_list - cell array list of input file name strings. All input
% files are appended in order.
% Copyright: Oliver Woodford, 2011
% Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in
% one go is much faster than appending them one at a time.
% Thanks to Michael Teo for reporting the issue of a too long command line.
% Issue resolved on 5/5/2011, by passing gs a command file.
% Thanks to Martin Wittmann for pointing out the quality issue when
% appending multiple bitmaps.
% Issue resolved (to best of my ability) 1/6/2011, using the prepress
% setting
% 26/02/15: If temp dir is not writable, use the output folder for temp
% files when appending (Javier Paredes); sanity check of inputs
% 24/01/18: Fixed error in case of existing output file (append mode)
% 24/01/18: Fixed issue #213: non-ASCII characters in folder names on Windows
function append_pdfs(varargin)
if nargin < 2, return; end % sanity check
% Are we appending or creating a new file
append = exist(varargin{1}, 'file') == 2;
output = [tempname '.pdf'];
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(output,'w');
fwrite(fid,1);
fclose(fid);
delete(output);
isTempDirOk = true;
catch
% Temp dir is not writable, so use the output folder
[dummy,fname,fext] = fileparts(output); %#ok<ASGLU>
fpath = fileparts(varargin{1});
output = fullfile(fpath,[fname fext]);
isTempDirOk = false;
end
if ~append
output = varargin{1};
varargin = varargin(2:end);
end
% Create the command file
if isTempDirOk
cmdfile = [tempname '.txt'];
else
cmdfile = fullfile(fpath,[fname '.txt']);
end
prepareCmdFile(cmdfile, output, varargin{:});
% Call ghostscript
[status, errMsg] = ghostscript(['@"' cmdfile '"']);
% Check for ghostscript execution errors
if status && ~isempty(strfind(errMsg,'undefinedfile')) && ispc
% Fix issue #213: non-ASCII characters in folder names on Windows
for fileIdx = 2 : numel(varargin)
[fpath,fname,fext] = fileparts(varargin{fileIdx});
varargin{fileIdx} = fullfile(normalizePath(fpath),[fname fext]);
end
% Rerun ghostscript with the normalized folder names
prepareCmdFile(cmdfile, output, varargin{:});
[status, errMsg] = ghostscript(['@"' cmdfile '"']);
end
% Delete the command file
delete(cmdfile);
% Check for ghostscript execution errors
if status
error('YMA:export_fig:append_pdf',errMsg);
end
% Rename the file if needed
if append
movefile(output, varargin{1}, 'f');
end
end
% Prepare a text file with ghostscript directives
function prepareCmdFile(cmdfile, output, varargin)
fh = fopen(cmdfile, 'w');
fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output);
fprintf(fh, ' "%s"', varargin{:});
fclose(fh);
end
% Convert long/non-ASCII folder names into their short ASCII equivalents
function pathStr = normalizePath(pathStr)
[fpath,fname,fext] = fileparts(pathStr);
if isempty(fpath) || strcmpi(fpath,pathStr), return, end
dirOutput = evalc(['system(''dir /X /AD "' pathStr '*"'')']);
shortName = strtrim(regexprep(dirOutput,{'.*> *',[fname fext '.*']},''));
if isempty(shortName)
shortName = [fname fext];
end
fpath = normalizePath(fpath); %recursive until entire fpath is processed
pathStr = fullfile(fpath, shortName);
end
function fh = copyfig(fh)
%COPYFIG Create a copy of a figure, without changing the figure
%
% Examples:
% fh_new = copyfig(fh_old)
%
% This function will create a copy of a figure, but not change the figure,
% as copyobj sometimes does, e.g. by changing legends.
%
% IN:
% fh_old - The handle of the figure to be copied. Default: gcf.
%
% OUT:
% fh_new - The handle of the created figure.
% Copyright (C) Oliver Woodford 2012, Yair Altman 2015
% 26/02/15: If temp dir is not writable, use the dest folder for temp
% destination files (Javier Paredes)
% 15/04/15: Suppress warnings during copyobj (Dun Kirk comment on FEX page 2013-10-02)
% 09/09/18: Fix issue #252: Workaround for cases where copyobj() fails for any reason
% Set the default
if nargin == 0
fh = gcf;
end
% Is there a legend?
useCopyobj = isempty(findall(fh, 'Type', 'axes', 'Tag', 'legend'));
if useCopyobj
% Safe to copy using copyobj
oldWarn = warning('off'); %Suppress warnings during copyobj (Dun Kirk comment on FEX page 2013-10-02)
try
fh = copyobj(fh, 0);
catch
% Fix issue #252: Workaround for cases where copyobj() fails for any reason
useCopyobj = false; % if copyobj() croaks, use file save/load below
end
warning(oldWarn);
end
if ~useCopyobj
% copyobj will change the figure, so save and then load it instead
tmp_nam = [tempname '.fig'];
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam); % cleanup
catch
% Temp dir is not writable, so use the current folder
[dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
fpath = pwd;
tmp_nam = fullfile(fpath,[fname fext]);
end
hgsave(fh, tmp_nam);
fh = hgload(tmp_nam);
delete(tmp_nam);
end
end
function [A, vA, vB, bb_rel] = crop_borders(A, bcol, padding, crop_amounts)
%CROP_BORDERS Crop the borders of an image or stack of images
%
% [B, vA, vB, bb_rel] = crop_borders(A, bcol, [padding])
%
%IN:
% A - HxWxCxN stack of images.
% bcol - Cx1 background colour vector.
% padding - scalar indicating how much padding to have in relation to
% the cropped-image-size (0<=padding<=1). Default: 0
% crop_amounts - 4-element vector of crop amounts: [top,right,bottom,left]
% where NaN/Inf indicate auto-cropping, 0 means no cropping,
% and any other value mean cropping in pixel amounts.
%
%OUT:
% B - JxKxCxN cropped stack of images.
% vA - coordinates in A that contain the cropped image
% vB - coordinates in B where the cropped version of A is placed
% bb_rel - relative bounding box (used for eps-cropping)
%{
% 06/03/15: Improved image cropping thanks to Oscar Hartogensis
% 08/06/15: Fixed issue #76: case of transparent figure bgcolor
% 21/02/16: Enabled specifying non-automated crop amounts
% 04/04/16: Fix per Luiz Carvalho for old Matlab releases
% 23/10/16: Fixed issue #175: there used to be a 1px minimal padding in case of crop, now removed
%}
if nargin < 3
padding = 0;
end
if nargin < 4
crop_amounts = nan(1,4); % =auto-cropping
end
crop_amounts(end+1:4) = NaN; % fill missing values with NaN
[h, w, c, n] = size(A);
if isempty(bcol) % case of transparent bgcolor
bcol = A(ceil(end/2),1,:,1);
end
if isscalar(bcol)
bcol = bcol(ones(c, 1));
end
% Crop margin from left
if ~isfinite(crop_amounts(4))
bail = false;
for l = 1:w
for a = 1:c
if ~all(col(A(:,l,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
l = 1 + abs(crop_amounts(4));
end
% Crop margin from right
if ~isfinite(crop_amounts(2))
bcol = A(ceil(end/2),w,:,1);
bail = false;
for r = w:-1:l
for a = 1:c
if ~all(col(A(:,r,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
r = w - abs(crop_amounts(2));
end
% Crop margin from top
if ~isfinite(crop_amounts(1))
bcol = A(1,ceil(end/2),:,1);
bail = false;
for t = 1:h
for a = 1:c
if ~all(col(A(t,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
t = 1 + abs(crop_amounts(1));
end
% Crop margin from bottom
bcol = A(h,ceil(end/2),:,1);
if ~isfinite(crop_amounts(3))
bail = false;
for b = h:-1:t
for a = 1:c
if ~all(col(A(b,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
b = h - abs(crop_amounts(3));
end
if padding == 0 % no padding
% Issue #175: there used to be a 1px minimal padding in case of crop, now removed
%{
if ~isequal([t b l r], [1 h 1 w]) % Check if we're actually croppping
padding = 1; % Leave one boundary pixel to avoid bleeding on resize
bcol(:) = nan; % make the 1px padding transparent
end
%}
elseif abs(padding) < 1 % pad value is a relative fraction of image size
padding = sign(padding)*round(mean([b-t r-l])*abs(padding)); % ADJUST PADDING
else % pad value is in units of 1/72" points
padding = round(padding); % fix cases of non-integer pad value
end
if padding > 0 % extra padding
% Create an empty image, containing the background color, that has the
% cropped image size plus the padded border
B = repmat(bcol,[(b-t)+1+padding*2,(r-l)+1+padding*2,1,n]); % Fix per Luiz Carvalho
% vA - coordinates in A that contain the cropped image
vA = [t b l r];
% vB - coordinates in B where the cropped version of A will be placed
vB = [padding+1, (b-t)+1+padding, padding+1, (r-l)+1+padding];
% Place the original image in the empty image
B(vB(1):vB(2), vB(3):vB(4), :, :) = A(vA(1):vA(2), vA(3):vA(4), :, :);
A = B;
else % extra cropping
vA = [t-padding b+padding l-padding r+padding];
A = A(vA(1):vA(2), vA(3):vA(4), :, :);
vB = [NaN NaN NaN NaN];
end
% For EPS cropping, determine the relative BoundingBox - bb_rel
bb_rel = [l-1 h-b-1 r+1 h-t+1]./[w h w h];
end
function A = col(A)
A = A(:);
end
function eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%EPS2PDF Convert an eps file to pdf format using ghostscript
%
% Examples:
% eps2pdf source dest
% eps2pdf(source, dest, crop)
% eps2pdf(source, dest, crop, append)
% eps2pdf(source, dest, crop, append, gray)
% eps2pdf(source, dest, crop, append, gray, quality)
% eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%
% This function converts an eps file to pdf format. The output can be
% optionally cropped and also converted to grayscale. If the output pdf
% file already exists then the eps file can optionally be appended as a new
% page on the end of the eps file. The level of bitmap compression can also
% optionally be set.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% Inputs:
% source - filename of the source eps file to convert. The filename is
% assumed to already have the extension ".eps".
% dest - filename of the destination pdf file. The filename is assumed
% to already have the extension ".pdf".
% crop - boolean indicating whether to crop the borders off the pdf.
% Default: true.
% append - boolean indicating whether the eps should be appended to the
% end of the pdf as a new page (if the pdf exists already).
% Default: false.
% gray - boolean indicating whether the output pdf should be grayscale
% or not. Default: false.
% quality - scalar indicating the level of image bitmap quality to
% output. A larger value gives a higher quality. quality > 100
% gives lossless output. Default: ghostscript prepress default.
% gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
% multiple options are needed, enclose in call array: {'-a','-b'}
% Copyright (C) Oliver Woodford 2009-2014, Yair Altman 2015-
% Suggestion of appending pdf files provided by Matt C at:
% http://www.mathworks.com/matlabcentral/fileexchange/23629
% Thank you to Fabio Viola for pointing out compression artifacts, leading
% to the quality setting.
% Thank you to Scott for pointing out the subsampling of very small images,
% which was fixed for lossless compression settings.
% 09/12/11: Pass font path to ghostscript
% 26/02/15: If temp dir is not writable, use the dest folder for temp
% destination files (Javier Paredes)
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 01/03/15: Upon GS error, retry without the -sFONTPATH= option (this might solve
% some /findfont errors according to James Rankin, FEX Comment 23/01/15)
% 23/06/15: Added extra debug info in case of ghostscript error; code indentation
% 04/10/15: Suggest a workaround for issue #41 (missing font path; thanks Mariia Fedotenkova)
% 22/02/16: Bug fix from latest release of this file (workaround for issue #41)
% 20/03/17: Added informational message in case of GS croak (issue #186)
% 16/01/18: Improved appending of multiple EPS files into single PDF (issue #233; thanks @shartjen)
% Intialise the options string for ghostscript
options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"'];
% Set crop option
if nargin < 3 || crop
options = [options ' -dEPSCrop'];
end
% Set the font path
fp = font_path();
if ~isempty(fp)
options = [options ' -sFONTPATH="' fp '"'];
end
% Set the grayscale option
if nargin > 4 && gray
options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];
end
% Set the bitmap quality
if nargin > 5 && ~isempty(quality)
options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false'];
if quality > 100
options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
else
options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode'];
v = 1 + (quality < 80);
quality = 1 - quality / 100;
s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v);
options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s);
end
end
% Enable users to specify optional ghostscript options (issue #36)
if nargin > 6 && ~isempty(gs_options)
if iscell(gs_options)
gs_options = sprintf(' %s',gs_options{:});
elseif ~ischar(gs_options)
error('gs_options input argument must be a string or cell-array of strings');
else
gs_options = [' ' gs_options];
end
options = [options gs_options];
end
% Check if the output file exists
if nargin > 3 && append && exist(dest, 'file') == 2
% File exists - append current figure to the end
tmp_nam = [tempname '.pdf'];
[fpath,fname,fext] = fileparts(tmp_nam);
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam);
catch
% Temp dir is not writable, so use the dest folder
fpath = fileparts(dest);
tmp_nam = fullfile(fpath,[fname fext]);
end
% Copy the existing (dest) pdf file to temporary folder
copyfile(dest, tmp_nam);
% Produce an interim pdf of the source eps, rather than adding the eps directly (issue #233)
ghostscript([options ' -f "' source '"']);
[~,fname] = fileparts(tempname);
tmp_nam2 = fullfile(fpath,[fname fext]); % ensure using a writable folder (not necessarily tempdir)
copyfile(dest, tmp_nam2);
% Add the existing pdf and interim pdf as inputs to ghostscript
%options = [options ' -f "' tmp_nam '" "' source '"']; % append the source eps to dest pdf
options = [options ' -f "' tmp_nam '" "' tmp_nam2 '"']; % append the interim pdf to dest pdf
try
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
catch me
% Delete the intermediate files and rethrow the error
delete(tmp_nam);
delete(tmp_nam2);
rethrow(me);
end
% Delete the intermediate (temporary) files
delete(tmp_nam);
delete(tmp_nam2);
else
% File doesn't exist or should be over-written
% Add the source eps file as input to ghostscript
options = [options ' -f "' source '"'];
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
end
% Check for error
if status
% Retry without the -sFONTPATH= option (this might solve some GS
% /findfont errors according to James Rankin, FEX Comment 23/01/15)
orig_options = options;
if ~isempty(fp)
options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' ');
status = ghostscript(options);
if ~status, return; end % hurray! (no error)
end
% Report error
if isempty(message)
error('Unable to generate pdf. Check destination directory is writable.');
elseif ~isempty(strfind(message,'/typecheck in /findfont'))
% Suggest a workaround for issue #41 (missing font path)
font_name = strtrim(regexprep(message,'.*Operand stack:\s*(.*)\s*Execution.*','$1'));
fprintf(2, 'Ghostscript error: could not find the following font(s): %s\n', font_name);
fpath = fileparts(mfilename('fullpath'));
gs_fonts_file = fullfile(fpath, '.ignore', 'gs_font_path.txt');
fprintf(2, ' try to add the font''s folder to your %s file\n\n', gs_fonts_file);
error('export_fig error');
else
fprintf(2, '\nGhostscript error: perhaps %s is open by another application\n', dest);
if ~isempty(gs_options)
fprintf(2, ' or maybe the%s option(s) are not accepted by your GS version\n', gs_options);
end
fprintf(2, ' or maybe you have another gs executable in your system''s path\n');
fprintf(2, 'Ghostscript options: %s\n\n', orig_options);
error(message);
end
end
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
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'];
end
user_string('gs_font_path', fp);
end
This diff is collapsed.
%FIX_LINES Improves the line style of eps files generated by print
%
% Examples:
% fix_lines fname
% fix_lines fname fname2
% fstrm_out = fixlines(fstrm_in)
%
% This function improves the style of lines in eps files generated by
% MATLAB's print function, making them more similar to those seen on
% screen. Grid lines are also changed from a dashed style to a dotted
% style, for greater differentiation from dashed lines.
%
% The function also places embedded fonts after the postscript header, in
% versions of MATLAB which place the fonts first (R2006b and earlier), in
% order to allow programs such as Ghostscript to find the bounding box
% information.
%
%IN:
% fname - Name or path of source eps file.
% fname2 - Name or path of destination eps file. Default: same as fname.
% fstrm_in - File contents of a MATLAB-generated eps file.
%
%OUT:
% fstrm_out - Contents of the eps file with line styles fixed.
% Copyright: (C) Oliver Woodford, 2008-2014
% The idea of editing the EPS file to change line styles comes from Jiro
% Doke's FIXPSLINESTYLE (fex id: 17928)
% The idea of changing dash length with line width came from comments on
</