Search code examples
c#asp.net-mvc-5cropjcrop

Crop image to certain ratio from virtual path c#


I would like to Crop an image to a ratio of 5/3.5 when I have the following:

  • Virtual path to image (~/Uploads/Images)
  • X Point for Top left corner of image
  • Y Point for Top left corner of image
  • Image width
  • Image Height

Here is an image showing what I mean:

cropping

The highlighted bits are what I have.

How can I achieve that with C# in my MVC Controller? I'd like to also store the image back to its original location, overwriting the old image if possible.


Solution

  • You can still use System.Drawing in asp.net even though its not recommended.

    from what i understod you need a function with the following signiture

    public static void CropAndOverwrite(string imgPath,int x1, int y1, int height, int width)
    

    The task is fairly simple

    public static void CropAndOverwrite(string imgPath, int x1, int y1, int height, int width)
        {
    
            //Create a rectanagle to represent the cropping area
            Rectangle rect = new Rectangle(x1, y1, width, height);
            //see if path if relative, if so set it to the full path
            if (imgPath.StartsWith("~"))
            {
                //Server.MapPath will return the full path
                imgPath = Server.MapPath(imgPath);
            }
            //Load the original image
            Bitmap bMap = new Bitmap(imgPath);
            //The format of the target image which we will use as a parameter to the Save method
            var format = bMap.RawFormat;
    
    
            //Draw the cropped part to a new Bitmap
            var croppedImage = bMap.Clone(rect, bMap.PixelFormat);
    
            //Dispose the original image since we don't need it any more
            bMap.Dispose();
    
            //Remove the original image because the Save function will throw an exception and won't Overwrite by default
            if (System.IO.File.Exists(imgPath))
                System.IO.File.Delete(imgPath);
    
            //Save the result in the format of the original image
            croppedImage.Save(imgPath,format);
            //Dispose the result since we saved it
            croppedImage.Dispose();
        }