talrnu
talrnu

Reputation: 213

Saving an unchanged Image to the file it was read from

I use System.Drawing.Image.FromFile(filePath) to read a .PNG image file into an Image variable for display in a pop-up dialog. The user might modify that image using controls in the dialog, and when they click the OK button to close the dialog, the image in its current state is written back to the file it was originally read from by calling Image.Save(filePath, format).

This works fine if they modify the image. For example, they might rotate the image, for which I call Image.RotateFlip().

However, this does not work if they do not modify the image, i.e. the first thing they do when the pop-up appears is click the OK button. This results in a "generic GDI+ error".

Google results lead me to believe that some sort of lock on the original file is being retained until the image data is modified. Calling Image.Save() before modifying the image conflicts with the lock, but calling it after a modification works because there is no longer a lock.

Unfortunately, I'm having trouble finding any other reports of my exact problem. So I wonder: why can't I save an Image to the file it was read from unless I modify it?

The most direct solution to this problem is to perform some undetectable modification on the Image (e.g. rotate it 360 degrees) immediately after loading it. But this is terribly hackish.

I'd check to see if the Image has been edited and simply not save it unless edits have been performed, but there doesn't seem to be a simple way to do that short of using a boolean flag and setting it in any code that modifies the image. But this is a bit fragile, as anyone adding image modification code in the future would need to know to set this flag in their code.

Ultimately, my question is: what's the best way to address this problem?

Upvotes: 0

Views: 33

Answers (1)

Hans Passant
Hans Passant

Reputation: 942020

Yes. Make a deep copy of the image with the Bitmap(Image) constructor and dispose the image so the lock on the file can never cause trouble. Like this:

public static Bitmap LoadImageNoLock(string filePath) {
    using (var img = Image.FromFile(filePath)) {
        var bmp = new Bitmap(img);
        bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution);
        return bmp;
    }
}

Upvotes: 2

Related Questions