When I try to delete image by using System.IO.File.Delete(....) then I get error exception.
IOException was unhandled by user code
The process cannot access the file
'xxx\image\6132_15658422-b0a1-45a9-b0f9-7e9af783ad53_Temp.jpg'
because
it is being used by another process.
Could anyone please give me suggestion ?
My main function that crop, resize and delete image by c#.
int X1 = 70, Y1 = 20, X2 = 201, Y2 = 236, w = 800, h = 600;
string filelocation = "image/6132_15658422-b0a1-45a9-b0f9-7e9af783ad53_Temp.jpg";
protected void Page_Load(object sender, EventArgs e)
{
try
{
using (System.Drawing.Image _Image = cropImage(
ResizeImage(
System.Drawing.Image.FromFile( Server.MapPath("~") +"/"+ filelocation), w, h),
(new System.Drawing.Rectangle(X1, Y1, X2, Y2))))
{
_Image.Save(Server.MapPath("~") + "/" + "image/output.jpg");
}
}
catch (Exception ex)
{
throw ex;
}
finally {
File.Delete(Server.MapPath("~") + "/" + filelocation);
}
}
For Crop Image Function,
public System.Drawing.Image cropImage(System.Drawing.Image image, Rectangle cropArea)
{
try
{
Bitmap bmpImage = new Bitmap(image);
Bitmap bmpCrop = bmpImage.Clone(cropArea,
bmpImage.PixelFormat);
return (System.Drawing.Image)(bmpCrop);
}
catch (Exception ex)
{
throw ex;
}
}
For Resize Image Function,
public System.Drawing.Image ResizeImage(System.Drawing.Image image, int maxWidth, int maxHeight)
{
try
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
catch (Exception ex)
{
throw ex;
}
}
[Updated]
Finally I correct my problem as @landenedge suggested,
using (var mainImage = System.Drawing.Image.FromFile(Server.MapPath("~") +"/"+ filelocation)){
using (System.Drawing.Image _Image = cropImage(
ResizeImage(mainImage, w, h),
(new System.Drawing.Rectangle(X1, Y1, X2, Y2))))
{
_Image.Save(Server.MapPath("~") + "/" + "image/output.jpg");
}
}
You need to dispose of the
Imageyou create withFromFile(). Try something like this:Also, don’t rethrow exceptions with
throw ex;– doing so resets the stack trace and can drop valuable debugging information. Instead, just usethrow;.