Search code examples
c#imagepicturebox

PictureBox Not Releasing Resources


My application is used to store scanned images, with additional information, to an SQL Database. Because I use a picturebox to accomplish this there is an issue I've become aware of with the picturebox holding open resources. This is preventing me from doing anything with the original file until I close my form. I have tried various ways to dispose of the picturebox with no success. Need help with the following code to release the resources held by the picturebox.

       using (OpenFileDialog GetPhoto = new OpenFileDialog())
        {
            GetPhoto.Filter = "images | *.jpg";
            if (GetPhoto.ShowDialog() == DialogResult.OK)
            {
                pbPhoto.Image = Image.FromFile(GetPhoto.FileName);
                txtPath.Text = GetPhoto.FileName;
                txtTitle.Text = System.IO.Path.GetFileNameWithoutExtension(GetPhoto.Fi‌​leName);
                ((MainPage)MdiParent).tsStatus.Text = txtPath.Text;
                //GetPhoto.Dispose();  Tried this
                //GetPhoto.Reset();  Tried this
                //GC.Collect(): Tried this
            }
        }

Saving the image to my database uses the following:

            MemoryStream stream = new MemoryStream();
            pbPhoto.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] pic = stream.ToArray();

Solution

  • It's usually FromFile() that causes locking issues: (not the PictureBox itself)

    The file remains locked until the Image is disposed.

    Change:

    pbPhoto.Image = Image.FromFile(GetPhoto.FileName);
    

    To:

    using (FileStream fs = new FileStream(GetPhoto.FileName, FileMode.Open))
    {
        if (pbPhoto.Image != null)
        {
            Image tmp = pbPhoto.Image;
            pbPhoto.Image = null;
            tmp.Dispose();
        }
        using (Image img = Image.FromStream(fs))
        {
            Bitmap bmp = new Bitmap(img);
            pbPhoto.Image = bmp;
        }
    }
    

    This should make a copy of the image for use in the PictureBox and release the file itself from any locks.