PictureBox和Dispose [英] PictureBox and Dispose

查看:96
本文介绍了PictureBox和Dispose的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PictureBox 显示图像文件时,如果图像文件已经存在(覆盖),我必须删除它.但是,如果我尝试删除该文件,它会被 PictureBox 阻止.因此,我编写了以下代码:

I must delete an image file if it already exists (overwriting it) while a PictureBox is showing the same. However If I try to delete the file it's blocked by PictureBox. So I write the following code:

if (File.Exists(file))
{
   Image _tmp = (Image)current_pic.Image.Clone();                 
   current_pic.Image.Dispose();
   current_pic.Dispose();
   File.Delete(path);
   current_pic.Image = _tmp;
   current_pic.Image.Save(file, ImageFormat.Jpeg);
}
else
   current_pic.Image.Save(file, ImageFormat.Jpeg); 

并且由于 pic.Dispose()而删除了文件系统上的映像,但是映像没有更多内容显示在 PictureBox 中.也许 Dispose()方法会使 PictureBox 无效?

and the Image on filesystem is deleted thanks to pic.Dispose() but the Image is not more showed inside the PictureBox. Maybe does Dispose() method invalidate PictureBox?

推荐答案

您可以将图片读取到图片框中,而无需如下所示锁定

You can read a image into the picture box without locking it as shown below

Image img;
string file = @"d:\a.jpg";
using (Bitmap bmp = new Bitmap(file))
{
   img = new Bitmap(bmp);
   current_pic.Image = img;
}
if (File.Exists(file))
{
    File.Delete(file);
    current_pic.Image.Save(file, ImageFormat.Jpeg);
}
else
    current_pic.Image.Save(file, ImageFormat.Jpeg);

我已经更新了代码以甚至支持保存操作.

I have updated the code to even support the save operation.

即使链接图像后,先前的代码也支持删除.该流已关闭,在保存时会导致GDI +错误.

While the previous code supported the delete even after linking the images. The stream was closed and this while saving resulted in a GDI+ error.

新更新的代码符合您的所有要求,如下所示

The newly updated code meets all your requirements as follows

  • 允许在链接图像时删除文件
  • 使用Picturebox控件中的Image属性保存图像

这篇关于PictureBox和Dispose的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆