Search code examples
c#coordinatespoints

Cropping picture, getting Rectangle from X,Y?


I'm trying to crop a picture in C# from integer x, y coordinates.. I just can't figure out how to get it?

public void doCroppedImage(int pointX, int pointY)
{
    Rectangle cropRect = //???
}

Solution

  • You can use this code. It returns the cropped image.

    public static Bitmap CropImage(Image source, int x,int y,int width,int height)
    {
        Rectangle crop = new Rectangle(x, y, width, height);
    
        var bmp = new Bitmap(crop.Width, crop.Height);
        using (var gr = Graphics.FromImage(bmp))
        {
            gr.DrawImage(source, new Rectangle(0, 0, bmp.Width, bmp.Height), crop, GraphicsUnit.Pixel);
        }
        return bmp;
    } 
    

    But one comment, to crop an image you have to know not only the x and y coordinates of cropping point but also the width and height of the cropped image.