Replacing Bitmap In-Place

Sometime even the simplest application can cause the exception. For example let's just open an image, edit it, and save it afterward. Something like this:

Code
var image = new Bitmap("test.jpg");
// do something with image
image.Save("test.jpg");

This code will throw the really helpful "A generic error occurred in GDI+." exception.

Fortunately, there is more than one way to skin this cat. Rather similar (and equivalent) code will work:

Code
Bitmap image;
using (var stream = new FileStream("test.jpg", FileMode.Open)) {
image = (Bitmap)Bitmap.FromStream(stream);
}
// do something with image
image.Save("test.jpg");

A slightly different embodiment of the same idea.

Leave a Reply

Your email address will not be published. Required fields are marked *