I'm trying to crop a jpeg file using the (x,y) coordinates,width and height and save the output in the same location(i.e replace). I tried the below code but its not working.
public void CropImage(int x, int y, int width, int height)
{
string image_path = @"C:\Users\Admin\Desktop\test.jpg";
var img = Image.FromFile(image_path);
Rectangle crop = new Rectangle(x, y, width, height);
Bitmap bmp = new Bitmap(crop.Width, crop.Height);
using (var gr = Graphics.FromImage(bmp))
{
gr.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), crop, GraphicsUnit.Pixel);
}
if (System.IO.File.Exists(image_path))
{
System.IO.File.Delete(image_path);
}
bmp.Save(image_path, ImageFormat.Jpeg);
}
This gives an error like:
An exception of type 'System.IO.IOException' occurred in mscorlib.dll but was not handled in user code
Additional information: The process cannot access the file 'C:\Users\Admin\Desktop\test.jpg' because it is being used by another process.
When I add img.Dispose()
I don't get the above error and I'm able to save it.But it saves the blank image with the given width and height.
Can anyone help me out with this??