80 lines
2.8 KiB
Matlab
80 lines
2.8 KiB
Matlab
function fig_export(filename, format, folder, dpi, fig)
|
|
% EXPORT_CHART Save the current MATLAB figure or a specified figure in the selected image format.
|
|
%
|
|
% Parameters:
|
|
% - filename (string, optional): The output file name. If it has no extension, one will be
|
|
% added based on the format. If missing or empty, a default
|
|
% name 'exported_plot' is used.
|
|
% - format (string): The desired file format for the export. Default is 'pdf'.
|
|
% Accepted formats are 'png', 'jpg', 'tiff', 'svg', 'pdf', 'esp'.
|
|
% - folder (string): The directory where the image file will be saved. Default is the current directory.
|
|
% - dpi (int): Resolution in dots per inch. Default is 96.
|
|
% - fig (figure handle, optional): The MATLAB Figure object to export. If empty, the current active figure is used.
|
|
%
|
|
% Notes:
|
|
% - The function creates the folder if it doesn't exist.
|
|
% - Ensures compatibility with supported MATLAB formats.
|
|
|
|
if nargin < 1 || isempty(filename)
|
|
timestamp = char(datetime('now', 'Format','yyyyMMdd_HHmmSS'));
|
|
filename = ['exported_plot_' timestamp];
|
|
end
|
|
if nargin < 2 || isempty(format)
|
|
format = 'pdf';
|
|
end
|
|
if nargin < 3 || isempty(folder)
|
|
folder = '.';
|
|
end
|
|
if nargin < 4 || isempty(dpi)
|
|
dpi = 96;
|
|
end
|
|
if nargin < 5 || isempty(fig)
|
|
fig = gcf;
|
|
end
|
|
|
|
% Add extension if missing
|
|
[~, ~, ext] = fileparts(filename);
|
|
if isempty(ext)
|
|
filename = [filename '.' format];
|
|
else
|
|
format = ext(2:end); % Use extension for format
|
|
end
|
|
|
|
% Validate folder and create if necessary
|
|
if ~exist(folder, 'dir')
|
|
mkdir(folder);
|
|
end
|
|
|
|
% Construct full file path
|
|
filepath = fullfile(folder, filename);
|
|
|
|
% Format to '-d' option mapping
|
|
supportedFormats = struct( ...
|
|
'png', '-dpng', ...
|
|
'jpg', '-djpeg', ...
|
|
'tiff', '-dtiff', ...
|
|
'svg', '-dsvg', ...
|
|
'pdf', '-dpdf', ...
|
|
'eps', '-depsc' ...
|
|
);
|
|
if ~isfield(supportedFormats, lower(format))
|
|
error('Unsupported format "%s". Supported formats are: %s.', ...
|
|
format, strjoin(fieldnames(supportedFormats), ', '));
|
|
end
|
|
|
|
% Get the corresponding '-d' option
|
|
dOption = supportedFormats.(lower(format));
|
|
|
|
% Attempt to save the figure
|
|
try
|
|
% Include resolution for raster formats
|
|
if ismember(lower(format), {'png', 'jpg', 'tiff'})
|
|
print(fig, filepath, dOption, ['-r' num2str(dpi)]);
|
|
else
|
|
print(fig, filepath, dOption);
|
|
end
|
|
fprintf('Exported image to: "%s" as %s\n', filepath, format);
|
|
catch ME
|
|
fprintf('Failed to export the figure: %s\n', ME.message);
|
|
end
|
|
end |