Load a picture so it doesn't lock the picture file in C#

When you create a Bitmap from a file, C# locks the file for some reason (possibly so it can read the file again later if it needs to refresh the image).

To work around this problem, load the image into a Bitmap, create a new Bitmap and copy the image into it, and dispose of the original Bitmap. This example loads a Bitmap either the straightforward way or using this technique.

private Bitmap m_Bitmap;

// Load the file.
private void btnLoad_Click(object sender, EventArgs e)
{
// Get the file name.
string file_name = Application.StartupPath;
file_name = file_name.Substring(0, file_name.LastIndexOf("\\"));
file_name = file_name.Substring(0, file_name.LastIndexOf("\\"));
file_name += "\\vbgp.jpg";

if (radLocked.Checked)
{
LoadLocked(file_name);
}
else
{
LoadUnlocked(file_name);
}
}

// Load the image into a Bitmap and set the
// PictureBox's Image property to the Bitmap.
private void LoadLocked(string file_name)
{
if (m_Bitmap != null) m_Bitmap.Dispose();

m_Bitmap = new Bitmap(file_name);
picSample.Image = m_Bitmap;
}

// Load the image into a Bitmap, clone it, and
// set the PictureBox's Image property to the Bitmap.
private void LoadUnlocked(string file_name)
{
if (m_Bitmap != null) m_Bitmap.Dispose();

using (Bitmap bm = new Bitmap(file_name))
{
m_Bitmap = new Bitmap(bm.Width, bm.Height);
using (Graphics gr = Graphics.FromImage(m_Bitmap))
{
gr.DrawImage(bm, 0, 0);
}
picSample.Image = m_Bitmap;
}
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.