2

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??

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Jibin Balachandran
  • 3,381
  • 1
  • 24
  • 38
  • 1
    The old image is still blocked by your code. You can pick another name or read one of many post how to unblock.. Search for 'c# Save jpeg IOException' – TaW Apr 27 '16 at 06:06
  • @TaW, Even when I give a new path, I was getting a blank image with the given width and height – Jibin Balachandran Apr 27 '16 at 06:15
  • It shouldn't be empty, unless you dispose of it. Watch the order of the Rectangles though! See [here](https://msdn.microsoft.com/en-us/library/ms142040%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) – TaW Apr 27 '16 at 06:19
  • @TaW I tried `using` so that save IOEcxeption won't come, its still not working.. Order of Rectangle is proper – Jibin Balachandran Apr 27 '16 at 06:24

1 Answers1

8
public void CropImage(int x, int y, int width, int height)
{
    string imagePath = @"C:\Users\Admin\Desktop\test.jpg";
    Bitmap croppedImage;

    // Here we capture the resource - image file.
    using (var originalImage = new Bitmap(imagePath))
    {
        Rectangle crop = new Rectangle(x, y, width, height);

        // Here we capture another resource.
        croppedImage = originalImage.Clone(crop, originalImage.PixelFormat);

    } // Here we release the original resource - bitmap in memory and file on disk.

    // At this point the file on disk already free - you can record to the same path.
    croppedImage.Save(imagePath, ImageFormat.Jpeg);

    // It is desirable release this resource too.
    croppedImage.Dispose();
}
Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49