Another process is using this file when saving a bitmap
Hi forum,
I wish to open a Image file, modify it, then save it.
To open the image, I simply use the following code
Code:
// BACKGROUND
Image buffer = new Bitmap(backgroundFilename);
background = (Image)buffer.Clone();
buffer.Dispose();
buffer = null;
Now if I want to save to this existing file, I do the following
Code:
Bitmap bmp = new Bitmap(1024, 512);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(background, 0, 0);
if (File.Exists(backgroundFilename))
{
File.Delete(backgroundFilename);
}
bmp.Save(backgroundFilename, System.Drawing.Imaging.ImageFormat.Png);
with the idea that if it already exists (which it does because I opened it), delete it then re-save it.
However, on the File.Delete line, C# crashes with a "This file is being used by another process"
Its obvious I am doing something wrong when opening the file, but not sure what.
Thanks
Re: Another process is using this file when saving a bitmap
I've never actually seen someone do it like that so my guess would be that cloning the Image will also copy the stream reference so disposing the original Image doesn't close the file. I would forget that Clone bit and just go straight to the DrawImage bit. Open the file and create an Image, create a Bitmap of the same size, draw the original onto the new and then dispose the original. You can now edit the copy, which contains just a copy of the pixel data and not the stream reference.
Re: Another process is using this file when saving a bitmap
Any chance you can give me an example olfrin above?
Re: Another process is using this file when saving a bitmap
Here is another suggestion that avoids the DrawImage bit
loading
Code:
var old = background;
using (var bmp = new Bitmap(backgroundFilename))
background = new Bitmap(bmp); //this seems to lose the stream reference (which i never knew existed)
//free up any resources used by the old background
if (old != null)
old.Dispose();
saving
Code:
//no need to delete to old file, it will be overwritten
background.Save(backgroundFilename, System.Drawing.Imaging.ImageFormat.Png);