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.
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.
Re: loading bitmap locks file until dispose?
Quote:
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.
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.
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);
}
}