I am using saveas function of Matlab to save figures but sometimes it gives me "Error using print (line 82) PNG library failed: Could not open file.."

85 views (last 30 days)
I am using saveas function of Matlab to save figures but sometimes my loop breaks gives me the above error, so I restart the loop and it starts working again, which makes me wanna think if there is any bug in the saveas function, because my code seems to be running when started again.
for m = 1:305
mkdir (Names{m});
folder = Names{m};
k = 1;
Limit = size(samples{m},2)
if(GenderList(m) == 1)
Temp = 'male';
else
Temp = 'female';
end
for i = 1:Limit
[coeffs,delta] = mfcc(samples{m}(:,i),fs);
f = figure('visible', 'off');
baseFileName = strcat(Names{m},'_',Temp,'_coeffs_', num2str(i,'%02d'),'.png');
fullFileName = fullfile(folder, baseFileName);
imagesc(coeffs);
saveas(f, fullFileName, 'png');
baseFileName2 = strcat(Names{m},'_',Temp,'_delta_', num2str(i,'%02d'),'.png');
fullFileName2 = fullfile(folder, baseFileName2);
imagesc(delta);
saveas(f, fullFileName2, 'png');
k = k+1;
clear coeffs;
clear delta;
i
end
clear k;
clear Temp;
end
  1 Comment
Jan
Jan on 16 Aug 2018
This can happen if the file is existing, but opened already. Can you exclude this?
By the way, omit the useless clear commands. They waste time only here.

Sign in to comment.

Answers (1)

Ann
Ann on 21 Jul 2021
Edited: Ann on 22 Jul 2021
I recently experience this error too, when using
print(figurehandle, '-dpng', [path])
It seems to occur randomly; my function which repeatedly creates figures and saves them to a folder using above code will work a few times, then crash. Troubleshooting by putting 'keyboard' in the line before the crashing one, and running the print(...) command by Evaluate Selection, then often does NOT reproduce the error.
I now think that this has to do with the folder to which my function tries to print; this is a local directory that gets automatically synced by Dropbox. During syncing the permission may change briefly.
  1 Comment
Florian
Florian on 28 Jul 2023
Edited: Florian on 28 Jul 2023
This was exactly my problem, too. If there are many figures to be plotted into a Dropbox folder, Dropbox starts uploading the first few and the later few produce the error
Error using print
PNG library failed: Could not open file..
If I pause Dropbox syncronization and execute the same file: no problems.
edited to add: If the figures already exist and are synced with Dropbox, merely overwriting them does NOT create the same error even if Dropbox is not paused.

Sign in to comment.

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!