How to crop a cross rectangle from an image using c#?

这一生的挚爱 提交于 2019-11-28 01:32:51

问题


I want to get some specific parts of an image so I'm cropping the images. However, when I want to get a part that is not parallel to the image, I rotate the image and crop afterwards.

I don't want to rotate the image and crop a parallel rectangle. What I want is, without rotating the image, to crop a rectangle with an angle from the image.

Is there any way to do that?

I think I couldnt express myself well enough. This is what I want to do: example picture.

Assume the red thing is a rectangle :) I want to crop that thing out of image. After cropping it doesn't need to be angeled. So mj can lie down.


回答1:


This method should perform what you asked for.

public static Bitmap CropRotatedRect(Bitmap source, Rectangle rect, float angle, bool HighQuality)
{
    Bitmap result = new Bitmap(rect.Width, rect.Height);
    using (Graphics g = Graphics.FromImage(result))
    {
        g.InterpolationMode = HighQuality ? InterpolationMode.HighQualityBicubic : InterpolationMode.Default;
        using (Matrix mat = new Matrix())
        {
            mat.Translate(-rect.Location.X, -rect.Location.Y);
            mat.RotateAt(angle, rect.Location);
            g.Transform = mat;
            g.DrawImage(source, new Point(0, 0));
        }
    }
    return result;
}

usage (using your MJ example):

Bitmap src = new Bitmap("C:\\mjexample.jpg");
Rectangle rect = new Rectangle(272, 5, 100, 350);
Bitmap cropped = cropRotatedRect(src, rect, -42.5f, true);


来源:https://stackoverflow.com/questions/8699103/how-to-crop-a-cross-rectangle-from-an-image-using-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!