|
-
May 26th, 2006, 01:10 AM
#1
loading bitmap locks file until dispose?
I am loading a bitmap from a file and using it as the background image of my form.
Code:
string sBitmapFullPath = @"C:\picture.bmp";
Bitmap bm = new Bitmap(sBitmapFullPath);
Color col = bm.GetPixel(1, 1);
this.Width = bm.Width;
this.Height = bm.Height;
this.BackgroundImage = bm;
At some point later I try to modify the file C:\picture.bmp, but the file is locked. After I call Bitmap.Dispose, I can modify the file. Is there any way that I can modify the file while it is still locked? I tried to use Bitmap.Clone image, but that didn't work either. Any ideas?
Basically, I want to change the image used for my form background, but I want it to use the same file path.
-
May 26th, 2006, 01:37 AM
#2
Re: loading bitmap locks file until dispose?
If you load an image, it is still connected to its file and keeps it open. You need to detach it - you have to create a in memory copy of the image. Than you can close the stream.
- Make it run.
- Make it right.
- Make it fast.
Don't hesitate to rate my post. 
-
May 26th, 2006, 10:50 AM
#3
Re: loading bitmap locks file until dispose?
 Originally Posted by boudino
If you load an image, it is still connected to its file and keeps it open. You need to detach it - you have to create a in memory copy of the image. Than you can close the stream.
I'm not sure how to do this. I tried creating a new Bitmap class instance and then performing a Bitmap.Clone to copy the old bitmap to the new bitmap. But now I get the same error in reference to the new Bitmap instance.
-
May 26th, 2006, 11:15 AM
#4
Re: loading bitmap locks file until dispose?
Code:
Bitmap temp = Image.FromFile(...);
Bitmap bmp = new Bitmap(temp.Width, temp.Height);
using ( Graphics g = Graphics.FromImage(bmp) ) {
g.DrawImage(temp, ...);
}
temp.Dispose();
edit: though clone should work (I've done it quite a few times). make sure to dispose of the bmp from file before you try to access the image file itself.
Last edited by MadHatter; May 26th, 2006 at 11:18 AM.
-
May 26th, 2006, 11:32 AM
#5
Re: loading bitmap locks file until dispose?
I came up with another way. This also keeps the memory usage to a minimum
Code:
public void SetBitmap(string sBitmapFullPath)
{
try
{
if (m_bitmap != null)
{
//first dispose of the previous instance
m_bitmap.Dispose();
m_bitmap = null;
}
//create a temp bitmap
Bitmap bmTemp = new Bitmap(sBitmapFullPath);
//create the member variable from the temp
m_bitmap = new Bitmap(bmTemp);
//dispose the temp bitmap
bmTemp.Dispose();
bmTemp = null;
//set the background image to the member bitmap
this.BackgroundImage = m_bitmap;
}
catch (Exception e)
{
AddMasterString(e.Message,true);
}
}
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
|