我有一张OpenFileDialog
的表单,用于选择图片并在pictureBox
中显示。在表单打开之前,用户可以打开然后根据需要多次保存打开的图像。我想要做的是,在每次新的选择 - 保存之后,删除之前保存的图像(如果有的话)。问题是,当我实现代码时,我能够第一次删除图像,如果我继续使用当前打开的表单保存图像,我会收到资源正在使用的错误。我所做的是Dispose()
图像,但我想我不是在正确的地方做的。
这是我打开并加载图片的方式:
private void btnExplorer_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Title = "Select file";
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = fileNameFilter;
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.FileName = prefixFilter;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
pictureBox1.InitialImage = new Bitmap(openFileDialog1.FileName);
pictureBox1.ImageLocation = openFileDialog1.FileName;
selectedFile = pictureBox1.ImageLocation;
selectedFileName = openFileDialog1.SafeFileName;
pictureBox1.Load();
}
catch (Exception ex)
{
logger.Error(ex.ToString());
MessageBox.Show("Error loading image!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
在同一个班级,我有这个方法,如果我需要删除旧图像,我会调用它:
public void DeleteImage(AppConfig imagePath, string ImageName)
{
pictureBox1.InitialImage.Dispose();//Release the image before trying to delete it
string imgPath = imagePath.ConfigValue.ToString();
File.Delete(imgPath + "\\" + ImageName);
}
如你所见。 Dispose()
方法在这里,我会确保资源将在尝试删除之前处理,但正如我所说,这只能工作一次,然后我得到错误的次数与保存图像的尝试次数一样多。
P.S
我得到的确切错误是:
The process cannot access the file 'C:\Images\ME_083a210e1a7644198fe1ecaceb80af52.jpg' because it is being used by another process.
答案 0 :(得分:5)
有一种更好的方法。使用FileStream加载图像,然后将其指定给pictureBox
FileStream bmp = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
Image img = new Bitmap(bmp);
pictureBox1.Image = img;
bmp.Close();
如果你想清除图片框,只需
pictureBox1.Image = null;
答案 1 :(得分:1)
如果我理解正确,你想从它的图片框中删除一次“使用过的”图片:设置
picturebox.InitialImage=null;
(顺便说一句:你最好使用picturebox.Image ......)
“Dispose”是强制垃圾收集器从内存中删除未使用的对象。
您的错误与处理pictureBox-image无关,但与源文件的锁定无关。
如果你使用“使用”块来处理openFileDialog,也许它已经有所帮助。
答案 2 :(得分:0)
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Title = "Select file";
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "Jpeg Files(*.jpg)|*.jpg|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.InitialImage = new Bitmap(openFileDialog1.FileName);
pictureBox1.ImageLocation = openFileDialog1.FileName;
selectedFile = pictureBox1.ImageLocation;
selectedFileName = openFileDialog1.SafeFileName;
pictureBox1.Load();
}
}
public string selectedFileName { get; set; }
public string selectedFile { get; set; }
private void button2_Click(object sender, EventArgs e)
{
pictureBox1.ImageLocation = null;
}