-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathsaveFigureOld.m
4157 lines (3990 loc) · 201 KB
/
saveFigureOld.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function fileList = saveFigure(varargin)
% saveFigure('filename.pdf', figh)
% fileList = saveFigure('filename', figh, 'ext', {'pdf', 'fig', 'png', 'eps'})
%
% Saves a figure to a variety of formats by first exporting to svg, using
% Jeurg Schwizer's excellent plot2svg utility, and then using ImageMagick
% and Inkscape to convert into PDF, PNG, JPG, etc. This approach has a few
% desirable features:
% * Images look identical across platforms (Mac OS, Linux)
% * Images look identical across different formats, since all conversion
% uses tools outside of Matlab
% * All fonts in figure can be replaced with any TrueType / OpenType font
% that is installed on your system and will render correctly
%
% You must install image-magick and inkscape before using, e.g.
% Ubuntu/Debian: sudo apt-get install imagemagick inkscape
% Mac via Homebrew: brew install imagemagick inkscape
% [I would download inkscape on Mac directly, building it takes a while!]
%
% Currently not supported for Windows, though adding this shouldn't be too
% difficult. Mostly just need to get the system() calls to work properly.
%
% Required
%
% name : name for figure(s), in one of the following forms:
% string :
% if name has an extension at the end, only that format will be saved
% if name has no extension at the end, extensions in exts will be
% added
% cellstr : each entry corresponds to one extension, names must have
% valid extension
% struct : field value .(ext) will be used for each extension ext
%
% Optional:
%
% figh : figure handle, [default=gcf]
%
% Param / Value pairs:
%
% fontName: string of font name to replace all fonts in figure with.
% default = 'Source Sans Pro'. Any font installed on your system may be
% used.
%
% ext : list of extensions to use when name does not have extension already,
% default={'pdf', 'png', 'svg'}.
% Options include: 'fig', 'png', 'hires.png', 'svg', 'eps', 'pdf'
%
% copy : copy the figure before saving to prevent modifications from
% affecting the original figure. [default = true]
%
% quiet : print status messages [default = false]
%
% Usage Examples:
% saveFigure('figureName.pdf');
% fileList = saveFigure('figureName', gcf, 'ext', {'pdf', 'fig', 'png'});
% saveFigure('figureName.png', gcf, 'fontName', 'Helvetica');
%
% Dan O'Shea dan@djoshea.com
% (c) 2014-2015
%
% This code internally relies heavily on:
% plot2svg : Juerg Schwizer [ http://www.zhinst.com/blogs/schwizer/ ]
% copyfig : Oliver Woodford
% GetFullPath: Jan Simon
%
extListFull = {'fig', 'png', 'hires.png', 'svg', 'eps', 'pdf'};
extListDefault = {'fig', 'pdf', 'png'};
p = inputParser;
p.addOptional('name', '', @(x) ischar(x) || iscellstr(x) || isstruct(x) || isa(x, 'function_handle'));
p.addOptional('figh', gcf, @ishandle);
p.addParamValue('fontName', '', @ischar);
p.addParamValue('ext', [], @(x) ischar(x) || iscellstr(x));
p.addParamValue('copy', verLessThan('matlab', '8.4'), @islogical); % copy only for older versions
p.addParamValue('quiet', true, @islogical);
p.addParamValue('notes', '', @ischar);
% p.KeepUnmatched = true;
p.parse(varargin{:});
hfig = p.Results.figh;
fontName = p.Results.fontName;
name = p.Results.name;
ext = p.Results.ext;
quiet = p.Results.quiet;
if isempty(name)
name = get(hfig, 'Name');
end
% build a map with .ext = file with ext
fileInfo = containers.Map('KeyType', 'char', 'ValueType', 'char');
if isstruct(name)
fields = fieldnames(name);
for iF = 1:fields
fileInfo(fields{iF}) = GetFullPath(name.(fields{iF}));
end
elseif iscell(name) % expect each argument to have extension already
assert(isempty(ext), 'Extension list invalid with cell name argument');
[extList] = cellfun(@getExtensionFromFile, name, 'UniformOutput', false);
for iF = 1:length(extList)
if ~ismember(extList{iF}, extList)
error('Could not extract valid extension from file name %s', name{iF});
end
fileInfo(extList{iF}) = GetFullPath(name{iF});
end
elseif ischar(name) % may or may not have extension
extFromName = getExtensionFromFile(name);
if ismember(extFromName, extListFull)
% single file name with extension
assert(isempty(ext), 'Extension list invalid when name argument already has extension');
fileInfo(extFromName) = GetFullPath(name);
else
% single file name with no extension, use extension list
% (default if not found)
if isempty(ext)
ext = extListDefault;
end
if ~iscell(ext)
ext = {ext};
end
for iE = 1:numel(ext)
fileInfo(ext{iE}) = GetFullPath(sprintf('%s.%s', name, ext{iE}));
end
end
else
error('Unknown format for argument name');
end
values = fileInfo.values;
[pathFinal, nameFinal] = fileparts(values{1});
% save figure notes
if ~isempty(p.Results.notes)
notes = p.Results.notes;
notesFile = fullfile(pathFinal, [nameFinal, '.notes.txt']);
[fid, msg] = fopen(notesFile, 'w');
if fid == -1
error('Error opening notes file %s : %s', notesFile, msg);
end
fprintf(fid, '%s', notes);
fprintf(fid, '\n\nSaved on %s\n\nFile list:\n', datestr(now));
for iKey = 1:fileInfo.Count
fprintf(fid, '%s\n', values{iKey});
end
fclose(fid);
end
% check extensions
extList = fileInfo.keys;
nonSupported = setdiff(extList, extListFull);
if ~isempty(nonSupported)
error('Non-supported extensions %', strjoin(nonSupported, ', '));
end
fileList = {};
tempList = {};
% Save fig format
if fileInfo.isKey('fig')
file = fileInfo('fig');
fileList{end+1} = file;
if ~quiet
printmsg('fig', file);
end
saveas(hfig, file, 'fig');
end
% copy the figure
if p.Results.copy
hfigCopy = copyfig(hfig);
set(hfigCopy, 'NumberTitle', 'off', 'Name', 'Figure Copy -- Temporary');
else
hfigCopy = hfig;
end
% make sure the size of the figure is WYSIWYG
set(hfigCopy, 'PaperUnits' ,'centimeters');
set(hfigCopy, 'Units', 'centimeters');
set(hfigCopy, 'PaperPositionMode', 'auto');
% start with svg format, convert to pdf, then to other formats
needSvg = any(ismember(setdiff(extListFull, 'fig'), extList));
needPdf = any(ismember(setdiff(extListFull, {'fig', 'svg'}), extList));
svgFile = '';
pdfFile = '';
if fileInfo.isKey('svg') || needSvg
if fileInfo.isKey('svg')
% use actual file name
file = fileInfo('svg');
fileList{end+1} = file;
if ~quiet
printmsg('svg', file);
end
else
% use a temp file name
file = [tempname '.svg'];
tempList{end+1} = file;
end
svgFile = file;
% set font to Myriad Pro
if ~isempty(fontName)
figSetFont(hfigCopy, 'FontName', fontName);
end
if verLessThan('matlab', '8.4')
plot2svg(file, hfigCopy);
else
% use Matlab's built in svg engine (from Batik Graphics2D for
% java)
set(hfigCopy,'Units','pixels'); % All data in the svg-file is saved in pixels
% we specify the resolution because complicated figures will
% save as an image
print('-dsvg', '-r600', file);
end
end
if fileInfo.isKey('pdf') || needPdf
if fileInfo.isKey('pdf')
% use actual file name
file = fileInfo('pdf');
fileList{end+1} = file;
if ~quiet
printmsg('pdf', file);
end
else
% use a temp file name
file = [tempname '.pdf'];
tempList{end+1} = file;
end
% convert to pdf using inkscape
convertSvgToPdf(svgFile, file);
pdfFile = file;
end
if fileInfo.isKey('png')
file = fileInfo('png');
fileList{end+1} = file;
if ~quiet
printmsg('png', file);
end
convertPdf(pdfFile, file, false);
end
if fileInfo.isKey('hires.png')
file = fileInfo('hires.png');
fileList{end+1} = file;
if ~quiet
printmsg('hires.png', file);
end
convertPdf(pdfFile, file, true);
end
if fileInfo.isKey('eps')
file = fileInfo('eps');
fileList{end+1} = file;
if ~quiet
printmsg('eps', file);
end
convertPdf(pdfFile, file);
end
if p.Results.copy
close(hfigCopy);
end
% delete temporary files
for tempFile = tempList
delete(tempFile{1});
end
fileList = makecol(fileList);
end
function convertSvgToPdf(svgFile, pdfFile)
% use Inkscape to convert pdf
% if ismac
% inkscapePath = '/usr/local/bin/inkscape';
% if ~exist(inkscapePath, 'file')
% error('Could not locate Inkscape at %s', inkscapePath);
% end
% else
inkscapePath = 'inkscape';
% end
% MATLAB has it's own older version of libtiff.so inside it, so we
% clear that path when calling imageMagick to avoid issues
cmd = sprintf('export LANG=en_US.UTF-8; export LD_LIBRARY_PATH=""; export DYLD_LIBRARY_PATH=""; %s --export-dpi=600 --export-pdf=%s %s', ...
inkscapePath, escapePathForShell(pdfFile), escapePathForShell(svgFile));
%cmd = sprintf('%s --export-pdf %s %s', inkscapePath, escapePathForShell(pdfFile), escapePathForShell(svgFile));
[status, result] = system(cmd);
if status
fprintf('Error converting svg file. Is Inkscape configured correctly?\n');
fprintf(result);
fprintf('\n');
end
end
function convertPdf(pdfFile, file, hires)
% call imageMagick convert on pdfFile --> file
if nargin < 3
hires = false;
end
% if ismac
% convertPath = '/usr/local/bin/convert';
% if ~exist(convertPath, 'file')
% error('Could not locate convert at %s', convertPath);
% end
% else
convertPath = 'convert';
% end
% MATLAB has it's own older version of libtiff.so inside it, so we
% clear that path when calling imageMagick to avoid issues
% cmd = sprintf('export LD_LIBRARY_PATH=""; export DYLD_LIBRARY_PATH=""; convert -verbose -quality 100 -density %d %s -resize %d%% %s', ...
% density, escapePathForShell(pdfFile), resize, escapePathForShell(file));
if hires
cmd = sprintf('export LD_LIBRARY_PATH=""; export DYLD_LIBRARY_PATH=""; %s -verbose -density 300 %s -resample 300 %s', ...
convertPath, escapePathForShell(pdfFile), escapePathForShell(file));
else
cmd = sprintf('export LD_LIBRARY_PATH=""; export DYLD_LIBRARY_PATH=""; %s -verbose -density 300 %s -resample 150 %s', ...
convertPath, escapePathForShell(pdfFile), escapePathForShell(file));
end
[status, result] = system(cmd);
if status
fprintf('Error converting pdf file. Are ImageMagick and Ghostscript installed?\n');
fprintf(result);
fprintf('\n');
end
end
function printmsg(ex, file)
fprintf('Saving %s as %s\n', ex, file);
end
function figSetFont(hfig, varargin)
% set all fonts in the figure
hfont = findobj(hfig, '-property', 'FontName');
set(hfont, varargin{:});
htext = findall(hfig, 'Type', 'Text');
set(htext, varargin{:});
drawnow;
end
function [ext, fileSansExt] = getExtensionFromFile(file)
[fPath, fName, dotext] = fileparts(file);
if ~isempty(dotext)
if strcmp(dotext, '.png')
[~, fName2, ext2] = fileparts(fName);
if strcmp(ext2, '.hires')
ext = 'hires.png';
fName = fName2;
else
ext = 'png';
end
else
ext = dotext(2:end);
end
else
ext = '';
end
fileSansExt = fullfile(fPath, fName);
end
function str = strjoin(strCell, join)
% str = strjoin(strCell, join)
% creates a string by concatenating the elements of strCell, separated by the string
% in join (default = ', ')
%
% e.g. strCell = {'a','b'}, join = ', ' [ default ] --> str = 'a, b'
if nargin < 2
join = ', ';
end
if isempty(strCell)
str = '';
else
if isnumeric(strCell) || islogical(strCell)
% convert numeric vectors to strings
strCell = arrayfun(@num2str, strCell, 'UniformOutput', false);
elseif iscell(strCell)
strCell = cellfun(@num2str, strCell, 'UniformOutput', false);
end
strCell = cellfun(@num2str, strCell, 'UniformOutput', false);
str = cellfun(@(str) [str join], strCell, ...
'UniformOutput', false);
str = [str{:}];
str = str(1:end-length(join));
end
end
%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
function fh = copyfig(fh)
% Set the default
if nargin == 0
fh = gcf;
end
hAxes = findobj(fh, 'Type', 'axes');
nAxes = numel(hAxes);
props = {'Visible', 'Position', 'Rotation', ...
'HorizontalAlign', 'VerticalAlign', 'Interpreter'};
items = {'XLabel', 'YLabel', 'ZLabel', 'Title'};
savedProps = cell(nAxes, numel(items), numel(props));
for iAx = 1:nAxes
axh = hAxes(iAx);
for iItem = 1:numel(items)
item = get(axh, items{iItem});
for iProp = 1:numel(props)
savedProps{iAx, iItem, iProp} = get(item, props{iProp});
end
end
end
% Is there a legend?
if isempty(findobj(fh, 'Type', 'axes', 'Tag', 'legend'))
% Safe to copy using copyobj
fh = copyobj(fh, 0);
else
% copyobj will change the figure, so save and then load it instead
tmp_nam = [tempname '.fig'];
hgsave(fh, tmp_nam);
fh = hgload(tmp_nam);
delete(tmp_nam);
end
hAxes = findobj(fh, 'Type', 'axes');
for iAx = 1:nAxes
axh = hAxes(iAx);
for iItem = 1:numel(items)
item = get(axh, items{iItem});
for iProp = 1:numel(props)
set(item, props{iProp}, savedProps{iAx, iItem, iProp});
end
end
end
end
function path = escapePathForShell(path)
% path = escapePathForShell(path)
% Escape a path to a file or directory for embedding within a shell command
% passed to cmd or unix.
path = strrep(path, ' ', '\ ');
end
function File = GetFullPath(File)
% GetFullPath - Get absolute path of a file or folder [MEX]
% FullName = GetFullPath(Name)
% INPUT:
% Name: String or cell string, file or folder name with or without relative
% or absolute path.
% Unicode characters and UNC paths are supported.
% Up to 8192 characters are allowed here, but some functions of the
% operating system may support 260 characters only.
%
% OUTPUT:
% FullName: String or cell string, file or folder name with absolute path.
% "\." and "\.." are processed such that FullName is fully qualified.
% For empty strings the current directory is replied.
% The created path need not exist.
%
% NOTE: The Mex function calls the Windows-API, therefore it does not run
% on MacOS and Linux.
% The magic initial key '\\?\' is inserted on demand to support names
% exceeding MAX_PATH characters as defined by the operating system.
%
% EXAMPLES:
% cd(tempdir); % Here assumed as C:\Temp
% GetFullPath('File.Ext') % ==> 'C:\Temp\File.Ext'
% GetFullPath('..\File.Ext') % ==> 'C:\File.Ext'
% GetFullPath('..\..\File.Ext') % ==> 'C:\File.Ext'
% GetFullPath('.\File.Ext') % ==> 'C:\Temp\File.Ext'
% GetFullPath('*.txt') % ==> 'C:\Temp\*.txt'
% GetFullPath('..') % ==> 'C:\'
% GetFullPath('Folder\') % ==> 'C:\Temp\Folder\'
% GetFullPath('D:\A\..\B') % ==> 'D:\B'
% GetFullPath('\\Server\Folder\Sub\..\File.ext')
% % ==> '\\Server\Folder\File.ext'
% GetFullPath({'..', 'new'}) % ==> {'C:\', 'C:\Temp\new'}
%
% COMPILE: See GetFullPath.c
% Run the unit-test uTest_GetFullPath after compiling.
%
% Tested: Matlab 6.5, 7.7, 7.8, 7.13, WinXP/32, Win7/64
% Compiler: LCC 2.4/3.8, OpenWatcom 1.8, BCC 5.5, MSVC 2008
% Author: Jan Simon, Heidelberg, (C) 2010-2011 matlab.THISYEAR(a)nMINUSsimon.de
%
% See also Rel2AbsPath, CD, FULLFILE, FILEPARTS.
% $JRev: R-x V:023 Sum:BNPK16hXCfpM Date:22-Oct-2011 00:51:51 $
% $License: BSD (use/copy/change/redistribute on own risk, mention the author) $
% $UnitTest: uTest_GetFullPath $
% $File: Tools\GLFile\GetFullPath.m $
% History:
% 001: 20-Apr-2010 22:28, Successor of Rel2AbsPath.
% 010: 27-Jul-2008 21:59, Consider leading separator in M-version also.
% 011: 24-Jan-2011 12:11, Cell strings, '~File' under linux.
% Check of input types in the M-version.
% 015: 31-Mar-2011 10:48, BUGFIX: Accept [] as input as in the Mex version.
% Thanks to Jiro Doke, who found this bug by running the test function for
% the M-version.
% 020: 18-Oct-2011 00:57, BUGFIX: Linux version created bad results.
% Thanks to Daniel.
% Initialize: ==================================================================
% Do the work: =================================================================
% #############################################
% ### USE THE MUCH FASTER MEX ON WINDOWS!!! ###
% #############################################
% Difference between M- and Mex-version:
% - Mex-version cares about the limit MAX_PATH.
% - Mex does not work under MacOS/Unix.
% - M is remarkably slower.
% - Mex calls Windows system function GetFullPath and is therefore much more
% stable.
% - Mex is much faster.
% Disable this warning for the current Matlab session:
% warning off JSimon:GetFullPath:NoMex
% If you use this function e.g. under MacOS and Linux, remove this warning
% completely, because it slows down the function by 40%!
%warning('JSimon:GetFullPath:NoMex', ...
% 'GetFullPath: Using slow M instead of fast Mex.');
% To warn once per session enable this and remove the warning above:
%persistent warned
%if isempty(warned)
% warning('JSimon:GetFullPath:NoMex', ...
% 'GetFullPath: Using slow M instead of fast Mex.');
% warned = true;
% end
% Handle cell strings:
% NOTE: It is faster to create a function @cell\GetFullPath.m under Linux,
% but under Windows this would shadow the fast C-Mex.
if isa(File, 'cell')
for iC = 1:numel(File)
File{iC} = GetFullPath(File{iC});
end
return;
end
isWIN = strncmpi(computer, 'PC', 2);
% DATAREAD is deprecated in 2011b, but available:
hasDataRead = ([100, 1] * sscanf(version, '%d.%d.', 2) <= 713);
if isempty(File) % Accept empty matrix as input
if ischar(File) || isnumeric(File)
File = cd;
return;
else
error(['JSimon:', mfilename, ':BadInputType'], ...
['*** ', mfilename, ': Input must be a string or cell string']);
end
end
if ischar(File) == 0 % Non-empty inputs must be strings
error(['JSimon:', mfilename, ':BadInputType'], ...
['*** ', mfilename, ': Input must be a string or cell string']);
end
if isWIN % Windows: --------------------------------------------------------
FSep = '\';
File = strrep(File, '/', FSep);
isUNC = strncmp(File, '\\', 2);
FileLen = length(File);
if isUNC == 0 % File is not a UNC path
% Leading file separator means relative to current drive or base folder:
ThePath = cd;
if File(1) == FSep
if strncmp(ThePath, '\\', 2) % Current directory is a UNC path
sepInd = strfind(ThePath, '\');
ThePath = ThePath(1:sepInd(4));
else
ThePath = ThePath(1:3); % Drive letter only
end
end
if FileLen < 2 || File(2) ~= ':' % Does not start with drive letter
if ThePath(length(ThePath)) ~= FSep
if File(1) ~= FSep
File = [ThePath, FSep, File];
else % File starts with separator:
File = [ThePath, File];
end
else % Current path ends with separator, e.g. "C:\":
if File(1) ~= FSep
File = [ThePath, File];
else % File starts with separator:
ThePath(length(ThePath)) = [];
File = [ThePath, File];
end
end
elseif isWIN && FileLen == 2 && File(2) == ':' % "C:" => "C:\"
% "C:" is the current directory, if "C" is the current disk. But "C:" is
% converted to "C:\", if "C" is not the current disk:
if strncmpi(ThePath, File, 2)
File = ThePath;
else
File = [File, FSep];
end
end
end
else % Linux, MacOS: ---------------------------------------------------
FSep = '/';
File = strrep(File, '\', FSep);
if strcmp(File, '~') || strncmp(File, '~/', 2) % Home directory:
HomeDir = getenv('HOME');
if ~isempty(HomeDir)
File(1) = [];
File = [HomeDir, File];
end
elseif strncmpi(File, FSep, 1) == 0
% Append relative path to current folder:
ThePath = cd;
if ThePath(length(ThePath)) == FSep
File = [ThePath, File];
else
File = [ThePath, FSep, File];
end
end
end
% Care for "\." and "\.." - no efficient algorithm, but the fast Mex is
% recommended at all!
if ~isempty(strfind(File, [FSep, '.']))
if isWIN
if strncmp(File, '\\', 2) % UNC path
index = strfind(File, '\');
if length(index) < 4 % UNC path without separator after the folder:
return;
end
Drive = File(1:index(4));
File(1:index(4)) = [];
else
Drive = File(1:3);
File(1:3) = [];
end
else % Unix, MacOS:
isUNC = false;
Drive = FSep;
File(1) = [];
end
hasTrailFSep = (File(length(File)) == FSep);
if hasTrailFSep
File(length(File)) = [];
end
if hasDataRead
if isWIN % Need "\\" as separator:
C = dataread('string', File, '%s', 'delimiter', '\\'); %#ok<REMFF1>
else
C = dataread('string', File, '%s', 'delimiter', FSep); %#ok<REMFF1>
end
else % Use the slower REGEXP in Matlab > 2011b:
C = regexp(File, FSep, 'split');
end
% Remove '\.\' directly without side effects:
C(strcmp(C, '.')) = [];
% Remove '\..' with the parent recursively:
R = 1:length(C);
for dd = reshape(find(strcmp(C, '..')), 1, [])
index = find(R == dd);
R(index) = [];
if index > 1
R(index - 1) = [];
end
end
if isempty(R)
File = Drive;
if isUNC && ~hasTrailFSep
File(length(File)) = [];
end
elseif isWIN
% If you have CStr2String, use the faster:
% File = CStr2String(C(R), FSep, hasTrailFSep);
File = sprintf('%s\\', C{R});
if hasTrailFSep
File = [Drive, File];
else
File = [Drive, File(1:length(File) - 1)];
end
else % Unix:
File = [Drive, sprintf('%s/', C{R})];
if ~hasTrailFSep
File(length(File)) = [];
end
end
end
end
%% Plot2SVG
function varargout = plot2svg(param1,id,pixelfiletype)
% Matlab to SVG converter
% Prelinary version supporting 3D plots as well
%
% Usage: plot2svg(filename,graphic handle,pixelfiletype)
% optional optional optional
% or
%
% plot2svg(figuresize,graphic handle,pixelfiletype)
% optional optional optional
%
% pixelfiletype = 'png' (default), 'jpg'
%
% Juerg Schwizer 23-Oct-2005
% See http://www.zhinst.com/blogs/schwizer/ to get more informations
%
% 07.06.2005 - Bugfix axxindex (Index exceeds matrix dimensions)
% 19.09.2005 - Added possibility to select output format of pixel graphics
% 23.10.2005 - Bugfix cell array strings (added by Bill)
% Handling of 'hggroups' and improved grouping of objects
% Improved handling of pixel images (indexed and true color pictures)
% 23.10.2005 - Switched default pixelfromat to 'png'
% 07.11.2005 - Added handling of hidden axes for annotations (added by Bill)
% 03.12.2005 - Bugfix of viewBox to make Firefox 1.5 working
% 04.12.2005 - Improved handling of exponent values for log-plots
% Improved markers
% 09.12.2005 - Bugfix '<' '>' '?' '"'
% 22.12.2005 - Implementation of preliminary 3D version
% Clipping
% Minor tick marks
% 22.01.2005 - Removed unused 'end'
% 29.10.2006 - Bugfix '°','±','µ','²','³','¼''½','¾','©''®'
% 17-04-2007 - Bugfix 'projection' in hggroup and hgtransform
% 27-01-2008 - Added Octave functionality (thanks to Jakob Malm)
% Bugfixe cdatamapping (thanks to Tom)
% Bugfix image data writing (thanks to Tom)
% Patches includes now markers as well (needed for 'scatter'
% plots (thanks to Phil)
% 04-02-2008 - Bugfix markers for Octave (thanks to Jakob Malm)
% 30-12-2008 - Bugfix image scaling and orientation
% Bugfix correct backslash (thanks to Jason Merril)
% 20-06-2009 - Improvment of image handling (still some remaining issues)
% Fix for -. line style (thanks to Ritesh Sood)
% 28-06-2009 - Improved depth sorting for patches and surface
% - Bugfix patches
% - Bugfix 3D axis handling
% 11-07-2009 - Support of FontWeight and FontAngle properties
% - Improved markers (polygon instead of polyline for closed markers)
% - Added character encoding entry to be fully SVG 1.1 conform
% 13-07-2009 - Support of rectangle for 2D
% - Added preliminary support for SVG filters
% - Added preliminary support for clipping with pathes
% - Added preliminary support for turning axis tickmarks
% 18-07-2009 - Line style scaling with line width (will not match with png
% output)
% - Small optimizations for the text base line
% - Bugfix text rotation versus shift
% - Added more SVG filters
% - Added checks for filter strings
% 21-07-2009 - Improved bounding box calculation for filters
% - Bugfixes for text size / line distance
% - Support of background box for text
% - Correct bounding box for text objects
% 31-07-2009 - Improved support of filters
% - Experimental support of animations
% 16-08-2009 - Argument checks for filters
% - Rework of latex string handling
% - 'sub' and 'super' workaround for Firefox and Inkscape
% 31-10-2009 - Bugfix for log axes (missing minor grid for some special
% cases)
% 24-01-2010 - Bugfix nomy line #1102 (thanks to Pooya Jannaty)
% 17-02-2010 - Bugfix minor tickmarks for log axis scaling (thanks to
% Harke Pera)
% - Added more lex symbols
% 06-03-2010 - Automatic correction of illegal axis scalings by the user
% (thanks to Juergen)
% - Renamed plot2svg_beta to plot2svg
% 12-04-2010 - Improved Octave compatibility
% 05-05-2010 - Bugfix for ticklabels outside of the axis limits (thanks to
% Ben Scandella)
% 30-10-2010 - Improved handling of empty cells for labels (thanks to
% Constantine)
% - Improved HTML character coding (thanks to David Mack)
% - Bugfix for last ')' (thanks to Jonathon Harding and Benjamin)
% - Enabled scatter plots using hggroups
% - Closing patches if they do not contain NaNs
% 10-11-2010 - Support of the 'Layer' keyword to but the grid on top of
% of the other axis content using 'top' (Many thanks to Justin
% Ashmall)
% - Tiny optimization of the grid display at axis borders
% 25-08-2011 - Fix for degree character (thanks to Manes Recheis)
% - Fix for problems with dash-arrays in Inkscape (thanks to
% Rüdiger Stirnberg)
% - Modified shape of driangles (thanks to Rüdiger Stirnberg)
% 22-10-2011 - Removed versn as return value of function fileparts (thanks
% to Andrew Scott)
% - Fix for images (thanks to Roeland)
% 20-05-2012 - Added some security checks for empty data
% - Fixed rotation for multiline text
% 25-08-2012 - Special handling of 1xn char arrays for tick labels
% (thanks to David Plavcan)
% - Fix for 'Index exceeds matrix dimensions' of axis labels
% (thanks to Aslak Grinsted)
% - Fix for another axis label problem (thanks to Ben Mitch)
% 15-09-2012 - Fix for linestyle none of rectangles (thanks to Andrew)
% - Enabled scatter plot functionality
global PLOT2SVG_globals
global colorname
% progversion='15-Sep-2012';
PLOT2SVG_globals.runningIdNumber = 0;
PLOT2SVG_globals.octave = false;
PLOT2SVG_globals.checkUserData = true;
PLOT2SVG_globals.ScreenPixelsPerInch = 90; % Default 90ppi
try
PLOT2SVG_globals.ScreenPixelsPerInch = get(0, 'ScreenPixelsPerInch');
catch
% Keep the default 90ppi
end
if nargout==1
varargout={0};
end
%disp([' Matlab/Octave to SVG converter version ' progversion ', Juerg Schwizer (converter@bluewin.ch).'])
matversion=version;
if exist('OCTAVE_VERSION','builtin')
PLOT2SVG_globals.octave = true;
disp(' Info: PLOT2SVG runs in Octave mode.')
else
if str2double(matversion(1))<6 % Check for matlab version and print warning if matlab version lower than version 6.0 (R.12)
disp(' Warning: Future versions may not support versions older than MATLAB R12.')
end
end
if nargout > 1
error('Function returns only one return value.')
end
if nargin<2 % Check if handle was included into function call, otherwise take current figure
id=gcf;
end
if nargin==0
if PLOT2SVG_globals.octave
error('PLOT2SVG in Octave mode does not yet support a file menu. File name is needed during function call.')
else
[filename, pathname] = uiputfile( {'*.svg', 'SVG File (*.svg)'},'Save Figure as SVG File');
if ~( isequal( filename, 0) || isequal( pathname, 0))
% yes. add backslash to path (if not already there)
pathname = addBackSlash( pathname);
% check, if extension is allrigth
if ( ~strcmpi( getFileExtension( filename), '.svg'))
filename = [ filename, '.svg'];
end
finalname=[pathname filename];
else
disp(' Cancel button was pressed.')
return
end
end
else
if isnumeric(param1)
if PLOT2SVG_globals.octave
error('PLOT2SVG in Octave mode does not yet support a file menu. File name is needed during function call.')
else
[filename, pathname] = uiputfile( {'*.svg', 'SVG File (*.svg)'},'Save Figure as SVG File');
if ~( isequal( filename, 0) || isequal( pathname, 0))
% yes. add backslash to path (if not already there)
pathname = addBackSlash( pathname);
% check, if ectension is allrigth
if ( ~strcmpi( getFileExtension( filename), '.svg'))
filename = [ filename, '.svg'];
end
finalname=[pathname filename];
else
disp(' Cancel button was pressed.')
return
end
end
else
finalname=param1;
end
end
% needed to see annotation axes
originalShowHiddenHandles = get(0, 'ShowHiddenHandles');
set(0, 'ShowHiddenHandles', 'on');
originalFigureUnits=get(id,'Units');
set(id,'Units','pixels'); % All data in the svg-file is saved in pixels
paperpos=get(id,'Position');
if ( nargin > 0)
if isnumeric(param1)
paperpos(3)=param1(1);
paperpos(4)=param1(2);
end
end
paperpos = paperpos * 90 / PLOT2SVG_globals.ScreenPixelsPerInch;
if (nargin < 3)
PLOT2SVG_globals.pixelfiletype = 'png';
else
PLOT2SVG_globals.pixelfiletype = pixelfiletype;
end
cmap=get(id,'Colormap');
colorname='';
for i=1:size(cmap,1)
colorname(i,:)=sprintf('%02x%02x%02x',fix(cmap(i,1)*255),fix(cmap(i,2)*255),fix(cmap(i,3)*255));
end
% Open SVG-file
[pathstr,name] = fileparts(finalname);
%PLOT2SVG_globals.basefilename = fullfile(pathstr,name);
PLOT2SVG_globals.basefilepath = pathstr;
PLOT2SVG_globals.basefilename = name;
PLOT2SVG_globals.figurenumber = 1;
fid=fopen(finalname,'wt'); % Create a new text file
fprintf(fid,'<?xml version="1.0" encoding="utf-8" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n'); % Insert file header
fprintf(fid,'<svg preserveAspectRatio="xMinYMin meet" width="100%%" height="100%%" viewBox="0 0 %0.3f %0.3f" ',paperpos(3),paperpos(4));
fprintf(fid,' version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"');
%fprintf(fid,' onload="Init(evt)"');
fprintf(fid,'>\n');
fprintf(fid,' <desc>Matlab Figure Converted by PLOT2SVG written by Juerg Schwizer, exported by SAVEFIGURE by Dan O''Shea</desc>\n');
%fprintf(fid,' <script type="text/ecmascript" xlink:href="puzzle_script.js" />\n');
fprintf(fid,' <g id="topgroup">\n');
group=1;
groups=[];
% Frame of figure
figcolor = searchcolor(id,get(id, 'Color'));
if (~ strcmp(figcolor, 'none'))
% Draw rectangle in the background of the graphic frame to cover all
% other graphic elements
try % Octave does not have support for InvertHardcopy yet -- Jakob Malm
if strcmp(get(id,'InvertHardcopy'),'on')
fprintf(fid,' <rect x="0" y="0" width="%0.3f" height="%0.3f" fill="#ffffff" stroke="none" />\n',paperpos(3),paperpos(4));
else
fprintf(fid,' <rect x="0" y="0" width="%0.3f" height="%0.3f" fill="%s" stroke="none" />\n',paperpos(3),paperpos(4),figcolor);
end
catch
fprintf(fid,' <rect x="0" y="0" width="%0.3f" height="%0.3f" fill="%s" stroke="none" />\n',paperpos(3),paperpos(4),figcolor);
end
end
% Search all axes
ax=get(id,'Children');
for j=length(ax):-1:1
currenttype = get(ax(j),'Type');
if strcmp(currenttype,'axes')
group=group+1;
groups=[groups group]; %#ok<*AGROW>
group=axes2svg(fid,id,ax(j),group,paperpos);
elseif strcmp(currenttype, 'legend')
group=group+1;
groups=[groups group];
group=legend2svg(fid,id,ax(j),group,paperpos);
elseif strcmp(currenttype,'uicontrol')
if strcmp(get(ax(j),'Visible'),'on')
control2svg(fid,id,ax(j),group,paperpos);