【发布时间】:2014-03-27 19:33:02
【问题描述】:
我正在尝试在我的 Winforms 应用程序中显示各种文件类型的图像(包括 动画 .gif 文件)。我还必须能够修改显示的文件。 (更改文件名,删除它们)。
问题是Picturebox locks the image file until the application is closed在使用正常方式时。
这意味着我不能这样做:
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pic = new PictureBox();
pic.Size = new Size(250, 250);
pic.Image = Image.FromFile("someImage.gif");
this.Controls.Add(pic);
//No use to call pic.Image = null or .Dispose of it
File.Delete("someImage.gif"); //throws exception
}
上面链接中的解决方法如下:
private void Form1_Load2(object sender, EventArgs e)
{
PictureBox pic = new PictureBox();
pic.Size = new Size(250, 250);
//using a FileStream
var fs = new System.IO.FileStream("someImage.gif", System.IO.FileMode.Open, System.IO.FileAccess.Read);
pic.Image = System.Drawing.Image.FromStream(fs);
fs.Close();
this.Controls.Add(pic);
pic.MouseClick += pic_MouseClick;
}
这适用于普通图像类型,但它不会加载动画 .gif,这对我很重要。尝试加载一个会使它看起来像this。
我发现了一些关于它的其他主题(this 和 this),但它们都是关于 WPF 并使用 BitmapImage。我已经搜索了如何在 Winforms 应用程序中使用 BitmapImage,但除了它应该以某种方式工作之外,没有发现任何其他东西。
我想继续使用 Winforms,因为我刚刚习惯了它,但这不是必需的。
总结一下:我需要一种方法来显示常见的图像类型(png、jpg、bmp 和动画 gif),同时仍然能够修改 HDD 上的文件。如果这意味着卸载->修改->重新加载文件,则可以。我更喜欢 Winforms,但其他框架也可以。
感谢您的帮助。
编辑:我尝试过的另一种方法
using (System.IO.FileStream fs = new System.IO.FileStream("E:\\Pics\\small.gif", System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
fs.CopyTo(ms);
pic.Image = Image.FromStream(ms);
}
但显示与第二个示例相同的问题。 gif 无法加载。
【问题讨论】:
-
将其作为内存流打开(从文件流中复制字节),然后将其加载到您可以提供给图片框的 gdi 对象中。这样就没有文件的链接了。
-
好吧,当在 MemoryStream 上使用 GIF 时,有一个技巧要做:stackoverflow.com/questions/8763630/…
-
@woutervs 我用另一个代码 sn-p 编辑了帖子。这是你的意思吗?如果没有,您能详细说明吗?
-
试试我的答案。在这种情况下,您甚至不需要 FileStream。
-
Hans Passant 的答案确实是将文件流复制到内存流的正确方法。 MrPaulch 的回答可能是 .net 4.5 的解决方案(我自己没有测试过。)
标签: c# .net winforms visual-studio-2010 window