Overwriting an image file (bitmap)
Question
Hello I am trying to save a bitmap image in a basic image editor program.
Here's the code:
// then save it
ImageBoxInApp.Image.Save(filename);
[EDIT] And I am opening the image with this
openFileDialog1.Title = "Select an Image";
openFileDialog1.Filter = "All Files|*.*|Windows Bitmaps|*.bmp|JPEG Files|*.jpg";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
filename = openFileDialog1.FileName;
Image img = System.Drawing.Image.FromFile(filename);
So when I try this I receive a Generic GDI+ error
. So I found a solution to this and it looks like this:
// Delete existing file first
System.IO.File.Delete(filename);
// then save it
ImageBoxInApp.Image.Save(filename);
But when I try to do this I receive another error saying that the file I am deleting is currently open. This is because that is the file that I am trying to edit.
How do I "close" the file without actually closing the application? Or is there an alternative solution?
Thanks!
Solution
Its hard to say without seeing some context around how your loading the file, but here are a couple of suggestions:
- Before saving, copy the existing image into a new Image, close the original, perform the delete, and save the copy.
- Save the file to a random filename, delete the original, rename the randomly named file to the original name.
- Load the file into a memory stream and use the in memory copy to initialize the image.
I'd personally go with option #3 for most cases. Be sure to dispose of the image when you've finished using it - it is best if you can wrap it in a using ( ) block.