加载多个 .fig 文件并将其保存为 .png 文件
Load and save multiple .fig files as .png files
我在一个文件夹中有几个 MATLAB .fig 文件(例如 folder/file1.fig
、folder/file2.fig
、...等)。
我想将它们全部导出到单独的 .png 文件。我知道我可以在 MATLAB 中打开每个 .fig 文件,然后它们只需手动将它们一个一个地导出,但这非常耗时,我正在寻找更优雅的东西,例如遍历 MATLAB 中的所有文件并使用 MATLAB 函数导出它们。
在 MATLAB 中可以实现这样的功能吗?我该怎么办?
像这样?
files = dir('.....');
for i = 1:length(files)
currentfile = files(i).name;
f = openfig(currentfile);
print(f,'-dpng',[currentfile(1:end-3),'png']);
close(f);
end
您可以使用文件交换中的 openfig
which will automatically open the figure and return the handle to the figure. You can then use saveas
(or export_fig
从目录中加载 .fig 文件,以将图形另存为 PNG。
folder = '/my/folder';
% Get all .fig files in the folder
files = dir(fullfile(folder, '*.fig'));
files = fullfile(folder, {files.name});
for k = 1:numel(files)
% Get the filename
[~, fname] = fileparts(files{k});
% Open and display the .fig file
hfig = openfig(files{k});
% Save as a PNG file with the same name as the .fig file
saveas(hfig, fullfile(folder, [fname, '.png']))
% Close the figure again
close(hfig)
end
如果您不希望图形在打开时不断弹出,您可以将 visibility input 指定为 openfig
,这将允许您加载和保存图形而无需渲染到屏幕上。
hfig = openfig(files{k}, 'invisible');
我在一个文件夹中有几个 MATLAB .fig 文件(例如 folder/file1.fig
、folder/file2.fig
、...等)。
我想将它们全部导出到单独的 .png 文件。我知道我可以在 MATLAB 中打开每个 .fig 文件,然后它们只需手动将它们一个一个地导出,但这非常耗时,我正在寻找更优雅的东西,例如遍历 MATLAB 中的所有文件并使用 MATLAB 函数导出它们。
在 MATLAB 中可以实现这样的功能吗?我该怎么办?
像这样?
files = dir('.....');
for i = 1:length(files)
currentfile = files(i).name;
f = openfig(currentfile);
print(f,'-dpng',[currentfile(1:end-3),'png']);
close(f);
end
您可以使用文件交换中的 openfig
which will automatically open the figure and return the handle to the figure. You can then use saveas
(or export_fig
从目录中加载 .fig 文件,以将图形另存为 PNG。
folder = '/my/folder';
% Get all .fig files in the folder
files = dir(fullfile(folder, '*.fig'));
files = fullfile(folder, {files.name});
for k = 1:numel(files)
% Get the filename
[~, fname] = fileparts(files{k});
% Open and display the .fig file
hfig = openfig(files{k});
% Save as a PNG file with the same name as the .fig file
saveas(hfig, fullfile(folder, [fname, '.png']))
% Close the figure again
close(hfig)
end
如果您不希望图形在打开时不断弹出,您可以将 visibility input 指定为 openfig
,这将允许您加载和保存图形而无需渲染到屏幕上。
hfig = openfig(files{k}, 'invisible');