Replacing Bitmap In-Place

Illustration

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:

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:

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.