Bitmap.Save() is not working?

Optikal

Well-known member
Joined
Oct 8, 2002
Messages
67
Location
Canada
It seems that when I load a System.Drawing.Bitmap object
from a disk file using the constructor (the one that
accepts only one string [the filename]), then try to do
a .Save() on it passing in a string representing the
filename, it will produce an exception if the filename I
pass to Save() is the same one I used to load the bitmap.

The exception raised is:
System.Runtime.InteropServices.ExternalException
Additional information: A generic error occurred in GDI+.

If I pass in a different filename to Save() it works fine, or if I
create a new Bitmap by just specifying width and height
(not filename) then .Save() it, it works fine.

What is perhaps the strangest thing of all, is that if
right before I try my .Save(), if I do a .ShowDialog() on
a SaveFileDialog control, the Bitmap.Save() will always
work. Even though I do absolutely nothing with the
result from the dialog, and it doesnt matter what file I
select in the dialog (or even if I press cancel).

My theory is that the Bitmap is somehow holding onto the
file that it loads itself from. And that when I try to
save it, it raises that exception because the file is not
ready to be overwritten. Now my questions would be, how
do I make it so that I can successfully Save my bitmap,
and what the heck is the SaveFileDialog.ShowDialog()
doing that makes Bitmap.Save() work?
 
Thats a good question, and Im not exactly sure what the
ShowDialog is doing. I think it may be allowing more processing
time to other applications, in which case you can do the same
thing by calling Application.DoEvents() to allow other apps and the
OS to complete some commands. This may allow
Windows sufficient time to free up the bitmap so you can save to it.
 
Dont think thats the case. I load and save the bitmap in separate events (triggered by menu items). So the application is idle between the 2 events. But just to make sure, I tried it with Application.DoEvents() right before the save, but as I suspected, it made no difference.

It has been suggested that the Bitmap locks the file while the bitmap is loaded, and that if I want to save it to the same file I have to copy the bitmap to another in-memory Bitmap, then call Save on that one (havent tried it yet though)...still dont understand why the SaveFileDialog would make it work though.
 
The reason you have this problem is because the file you are trying to overwrite is "already in use".

If you find a way to make the file no longer in use, please let me know.

Nick
 
In fact, this snippet of code might be of some use for when you first open your image file...

strLocation = "Your File Location"
Dim objFileStream As New FileStream(strLocation, FileMode.Open)
mobjImage = Image.FromStream(objFileStream)
objFileStream.Close()
 
Back
Top