My problems is that I can't overwrite the image I've opened recently.
So, let's imagine I'm opening the file with openfiledialog
:
OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
OpenFileDialog1.InitialDirectory = "c:\\";
OpenFileDialog1.Filter = "Images|*.GIF;*.TIF;*.JPG;*.BMP";
OpenFileDialog1.RestoreDirectory = true;
if (OpenFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((OpenFileDialog1.OpenFile()) != null)
{
if (string.IsNullOrEmpty(OpenFileDialog1.FileName))
return;
pictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName);
}
}
OpenFileDialog1.Dispose();
After I made some corrections on the picturebox (e.g. drawed something), I want to save the image (to the same file, from which I've opened the image) with savefiledialog
.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "BMP File|*.BMP";
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
}
It gives me an error (System.Runtime.InteropServices.ExternalException
) also known as GDI+ generic error. So, it's basically an error which denies me to overwrite the file I've opened recently.
The Image
loaded by Image.FromFile()
is keeping the file open.
You can Dispose()
the image to release the resources, but I don't think the PictureBox
would be too happy with that if it's still showing the old image.
Alternatively you could load the contents of the file in a MemoryStream
and use Image.FromStream()
.