Cropping picture, getting Rectangle from X,Y? [clo

2019-09-21 17:02发布

问题:

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 = //???
}

回答1:

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.