Why won't GDI let me delete large images?
My ASP.NET application has cropping and resizing features. This requires deleting the downloaded temporary image. Everything works fine, but when I try to delete an image larger than 80px by 80px, I get the message "The file is locked by another process ..." even though I freed up all resources.
Here's a snippet:
System.Drawing.Image tempimg = System.Drawing.Image.FromFile(temppath);
System.Drawing.Image img = (System.Drawing.Image) tempimg.Clone(); //advice from another forum
tempimg.Dispose();
img = resizeImage(img, 200, 200); //delete only works if it 80, 80
img.Save(newpath);
img.Dispose();
File.Delete(temppath);
+2
source to share
2 answers
I think you are not deleting the first instance of the image assigned to the img variable.
Consider this instead:
System.Drawing.Image tempimg = System.Drawing.Image.FromFile(temppath);
System.Drawing.Image img = (System.Drawing.Image) tempimg.Clone();
tempimg.Dispose();
System.Drawing.Image img2 = resizeImage(img, 200, 200);
img2.Save(newpath);
img2.Dispose();
img.Dispose();
File.Delete(temppath);
+1
source to share
If you create an image this way, it will not be blocked:
using (FileStream fs = new FileStream(info.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
byte[] data = new byte[fs.Length];
int read = fs.Read(data, 0, (int)fs.Length);
MemoryStream ms = new MemoryStream(data, false);
return Image.FromStream(ms, false, false); // prevent GDI from holding image file open
}
+1
source to share