我正在尝试显示各种文件类型的图像(包括动画.gif文件)在我的 Winforms 应用程序中。我也必须能够修改显示的文件。 (更改文件名,删除它们)。
问题是一个Picturebox 锁定图像文件,直到应用程序关闭 http://support.microsoft.com/kb/309482当使用正常方式时。
这意味着我不能这样做:
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 https://i.stack.imgur.com/50yeY.png.
我发现了一些关于它的其他主题(this https://stackoverflow.com/questions/2097152/creating-wpf-bitmapimage-from-memorystream-png-gif?lq=1 and this https://stackoverflow.com/questions/18167280/image-file-copy-is-being-used-by-another-process?rq=1)但它们都是关于 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 无法加载。