How to crop an image using C# with the WebImage class?

886 views Asked by At

I have an application that is written using C# on the top on ASP.NET MVC 5 framework.

I am trying to use WebImage to crop an image that I have on disk. On the GUI, I am using Jcrop plugin to allow the user to mark the area they want to crop aka keep. As you can see the Jcrop plugin provides me the X1, X2, Y1, and Y2 which identify the location of the final image to keep. Jcrop also provides me with the final height and width of the final image even though they can also be calculated using the following formula W = X2 - X1; H = Y2 - Y1

enter image description here

Here is my method in which I am cropping a given image and overriding it.

/// <summary>
/// Crop the given image and overrides it with the cropped image
/// </summary>
/// <param name="filename">The full path of the image and the location of the new image</param>
/// <param name="top">Y or Y1</param>
/// <param name="left">X or X1</param>
/// <param name="bottom">Y2</param>
/// <param name="right">X2</param>
/// <returns></returns>
public WebImage CropAndSave(string sourcePath, int top, int left, int bottom, int right)
{
    byte[] imageBytes = File.ReadAllBytes(sourcePath);

    var image = new WebImage(imageBytes)
    {
        FileName = ExtractFileName(sourcePath)
    };

    WebImage croppedImage = image.Crop(top, left, bottom, right);
    croppedImage.Save(sourcePath, "jpg", true);

    return croppedImage;
}

However, the cropped image is not what I expect. It is a very small image, not the same one that the user wants to keep.

How can I use WebImage.Crop(...) to correctly crop the image?

1

There are 1 answers

0
Steve0 On

Reading the definition you provided Crop is expecting the following;

  • Number of pixels to remove from the top Y1
  • Number of pixels to remove from the left X1
  • Full Height of the original minus Y2
  • Full Width of the original minus X2

    image.Crop(Y1, X1, image.height - Y2, image.width - X2);