在PictureBox中锁定图像文件

时间:2015-05-05 12:24:17

标签: c# winforms picturebox

我将图片加载到图片框中:

myPictureBox.Image = Image.FromFile(strImageFile);

并且运行正常,但图像文件已被锁定,我无法管理,直到我的应用程序关闭..

我需要从程序的另一个窗口保存一个新图像,以便在关闭此子窗口时重新加载..

4 个答案:

答案 0 :(得分:3)

Image.FromFile将保持文件打开,这会阻止访问图像文件,直到图像被释放。如果要释放锁定,则需要将Image文件保留在内存中。

myPictureBox.Image = Image.FromStream(new MemoryStream(File.ReadAllBytes(strImageFile)));

答案 1 :(得分:1)

一种简单的方法是将文件从文件复制到新的Bitmap,然后在文件中处理该实例。最好使用正确的使用构造:

using(var fromFile = Image.FromFile(strImageFile))
{
    myPictureBox.Image = new Bitmap(fromFile);
}

答案 2 :(得分:1)

由于documented从文件加载图像并将克隆的实例分配给图片框。

  

如果要在多个PictureBox控件中使用相同的图像,请为每个PictureBox创建图像的克隆。从多个控件访问同一图像会导致发生异常。

要保持文件解锁,只需将其用于克隆时间:

using ( var img = Image.FromFile( fileName ) )
{
    pictureBox2.Image = (Image) img.Clone();
}

答案 3 :(得分:0)

好吧,您可以使用Image.FromStream代替Image.FromFile并将您正在阅读的流包装到using中,以确保在您阅读完毕后将其发布。

using (var stream = File.Open(strImageFile, FileMode.Open))
{
     myPictureBox.Image = Image.FromStream(stream);
}
相关问题