views:

551

answers:

2

Consider this code for loading, modifying and saving a Bitmap image:

    using (Bitmap bmp = new Bitmap("C:\\test.jpg"))
    {
        bmp.RotateFlip(RotateFlipType.Rotate180FlipNone);
        bmp.Save("C:\\test.jpg");
    }

it runs without any exception. But consider this one:

    using (Bitmap bmp = new Bitmap("C:\\test.jpg"))
    {
        using (Bitmap bmpClone = (Bitmap)bmp.Clone())
        {
            //You can replace "bmpClone" in the following lines with "bmp",
            //exception occurs anyway                    
            bmpClone.RotateFlip(RotateFlipType.Rotate180FlipNone);
            bmpClone.Save("C:\\test.jpg");
        }
    }

It ends in an ExternalException with this message: "A generic error occurred in GDI+". What's wrong here? Any kind of lock on opened file? If so, why the first block works? What is the proper code for cloning a System.Drawing.Bitmap while we may need to edit main object or its clone in the memory and still have them both loaded in memory?

+5  A: 

Yes, the file is locked when the first bitmap object is loaded and thus bmpClone.Save() to the same file fails because you have a logical deadlock.

When opening Bitmaps by filename, the file is locked throughout the life of the Bitmap. If you use a stream, the stream must remain open.

Update:

If you wish to have two bitmaps in memory for use outside of the scope of the method you are in, then you won't be using a using block.

Create the first image from file, and then clone it. Utilize them as needed throughout your UI lifecycle but make sure you clean them up using Dispose() when they are no longer needed so that underlying resources are released.

Also, from MSDN:

Saving the image to the same file it was constructed from is not allowed and throws an exception

That's pretty awkward. If the object created using clone() keeps information on the image source (e.g. a handle on the original file) or you can't otherwise unlock the file while using the Bitmap instances, then you'll probably have to either save to a new file, or open from a temporary copy of the original.

Try this instead:

// ... make a copy of test.jpg called test_temp.jpg

Bitmap bmpOriginal = new Bitmap("C:\\test_temp.jpg"))
Bitmap bmpClone = (Bitmap)bmp.Clone();

// ... do stuff          
bmpClone.RotateFlip(RotateFlipType.Rotate180FlipNone);

bmpClone.Save("C:\\test.jpg");

// ... cleanup
bmpOriginal.Dispose();
bmpClone.Dispose();
jscharf
OK! But what if we really do need to have two copies of this Bitmap in memory (Two picture boxes one showing an "original" image, and one showing "modified" one, whenever -anytime- our user might click on Save button)?
hamid reza
Create two clones then and keep one unmodified.
dtb
@dtb:Problem occurs on Save method, in the second block, "bmp" is still unmodified.One solution is: creating a new Bitmap with same width+height+PixelFormat of source and drawing the source on it (implement cloning yourself), but is this solution wise? What is the efficient, fast and standard solution? How cloning of a Bitmap can be useful when it might result in such an exception?
hamid reza
`new Bitmap(Bitmap)` does exactly that: creating a new Bitmap with same width+height+PixelFormat of source and drawing the source on it
dtb
@dtb: It cannot be , because drawing on a Bitmap canvas is not always an option for creating a copy of a Bitmap. For example when the source bitmap is an 8 bit indexed one which Graphic.FromImage is not allowed for it, drawing is not possible, while new Bitmap(Bitmap) is working and possible.
hamid reza
+3  A: 

You could also load the bitmap without file locking using the simple workaround:

using (Stream s = File.OpenRead(@"\My Documents\My Pictures\Waterfall.jpg"))
Bitmap _backImage = (Bitmap)Bitmap.FromStream(s);
ptnik