PictureBox不释放资源

问题描述

我的应用程序用于将扫描的图像以及其他信息存储到sql数据库中。因为我使用图片框来完成此操作,所以我发现一个图片框拥有开放资源的问题。这将阻止我在关闭表单之前对原始文件执行任何操作。我尝试了各种方法来处理图片框,但均未成功。需要以下代码的帮助,以释放图片框所拥有的资源。

       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
            }
        }

将图像保存到数据库中使用以下方法

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

解决方法

通常是FromFile()会导致锁定问题:(而不是PictureBox本身)

该文件将保持锁定状态,直到处理完图像为止。

更改:

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

收件人:

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;
    }
}

这应该复制图像以在PictureBox中使用,并从任何锁中释放文件本身。