[英]PictureBox Not Releasing Resources
My application is used to store scanned images, with additional information, to an SQL Database.我的应用程序用于将扫描图像和附加信息存储到 SQL 数据库中。 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.FileName);
((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();
It's usually FromFile() that causes locking issues: (not the PictureBox itself)通常是FromFile()导致锁定问题:(不是 PictureBox 本身)
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.这应该制作图像的副本以供在 PictureBox 中使用,并解除文件本身的任何锁定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.