PictureBox and Dispose

I have to delete the image file if it already exists (overwrites it) while the PictureBox shows the same. However, if I try to delete the locked PictureBox file. Therefore, I am writing 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); 

and the image on the file system is deleted thanks to pic.Dispose() , but the image is no longer shown inside the PictureBox . Maybe the Dispose() method is not valid PictureBox ?

+4
source share
1 answer

You can read the image in the image window without blocking 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 updated the code to support the save operation.

While the previous code supported deletion even after linking to images. The stream was closed, and this, when saved, led to a GDI + error.

Updated code meets all your requirements as follows

  • Permission to delete a file when connecting images
  • Saving an Image Using the Image Property in a Picturebox Control
+4
source

All Articles