|
-
Mar 6th, 2012, 04:42 PM
#1
Thread Starter
Fanatic Member
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
-
Mar 7th, 2012, 12:09 AM
#2
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.
-
Mar 7th, 2012, 07:50 AM
#3
Lively Member
Re: Another process is using this file when saving a bitmap
Any chance you can give me an example olfrin above?
-
Mar 9th, 2012, 03:17 PM
#4
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);
Last edited by Milk; Mar 9th, 2012 at 04:19 PM.
Reason: grandma and spellige
W o t . S i g
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|