Reputation: 3521
protected void btnCropIt_Click(object s, EventArgs e)
{
System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("../upload/" + u.Avatar));
var m = cropImage(img, new Rectangle(0, 0, 50, 50));
System.IO.File.Delete(Server.MapPath("../upload/" + u.Avatar));
m.Save(Server.MapPath("../upload/" + u.Avatar));
}
private static System.Drawing.Image cropImage(System.Drawing.Image img, Rectangle cropArea)
{
Bitmap bmpImage = new Bitmap(img);
Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
return (System.Drawing.Image)(bmpCrop);
}
System.IO.File.Delete(Server.MapPath("../upload/" + u.Avatar));
This line of code throws exception that it can't delete image, it's used by another process. Any Idea? How to overwrite it?
Upvotes: 0
Views: 521
Reputation: 7666
Your code is still using it. FromFile()
keeps it locked until the image is disposed. It's kind of an obscure semantic, but the MSDN documentation does mention it.
You might try img.Finalize()
right after cropImage()
as a simple fix. If that doesn't work, pull it in with a FileStream, use the System.Drawing.Bitmap Stream constructor overload, then close the FileStream immediately.
Upvotes: 1