Overwrite image picturebox in C#

This is a common issue.

The documentation says:

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

There are two options. One is to delete the file before writing it.

The other is to use a Stream to write it. I prefer the latter..:

string fn = "d:\\xyz.jpg";

// read image file
Image oldImg = Image.FromFile(fn);

// do something (optional ;-)
((Bitmap)oldImg).SetResolution(123, 234);

// save to a memorystream
MemoryStream ms = new MemoryStream();
oldImg.Save(ms, ImageFormat.Jpeg);

// dispose old image
oldImg.Dispose();

// save new image to same filename
Image newImage = Image.FromStream(ms);
newImage.Save(fn);

Note that saving jpeg files often achieves better quality if you take control of encoding options. Use this overload for this..

Also note that since we need to dispose of the image you need to make sure that it is not used anywhere, like in a PictureBox.Image! If it is, set it to null there before disposing : pictureBox1.Image = null; !

For a solution deleting the old file see here

Leave a Comment