Sunday, August 03, 2008

Saving a Bitmap

A friend of mine came through a problem while dealing with Bitmaps after writing some code that should open an image.. do some operations & finally save it in the same path. (overwrite the old copy)... the code looked as follows :
Bitmap
bmp = new Bitmap(@"C:\Pic.jpg");
..
//Do some Operations on bmp
..
btm.Save(@"C:\Pic.jpg");


An Exceptions is then fired on the bmp.Save(..) statement "A generic error occurred in GDI+"

At the first look, it seemed strange to see the exception esp the "Save" method should handle the overwriting process..
Yet, here was the mistake.. After creating the first bitmap from the image file, a lock has been done on the file in the memory, & then later, we are trying to save the bitmap in the same file (which is currently locked) & that's why we get that exception.
It will work in case you wanted to save in different paths, but not in case of overwriting..

so the suggested solutions was to create a copy from that bitmap, make the operations on that copy.. then dispose the bmp object (to release the lock) & later on save it (using the copy).. the new code should look as follows :

Bitmap bmp = new Bitmap(@"C:\Pic.jpg");
Bitmap copy = new Bitmap(bmp.Width, bmp.Height);
Graphics g = Graphics.FromImage(copy);
g.DrawImage(bmp, new Point(0, 0));
..
//Do some Operations on copy
..

//release the image file

bmp.Dispose();
bmp = copy;
bmp.Save(@"C:\Pic.jpg");

That's it..