如何使用c#从图像中裁剪十字矩形?

use*_*953 5 c# crop image-processing image-rotation

我想得到图像的一些特定部分,所以我正在裁剪图像.但是,当我想得到一个与图像不平行的部分时,我会旋转图像然后裁剪.

我不想旋转图像并裁剪一个平行的矩形.我想要的是,在不旋转图像的情况下,从图像中裁剪出一个角度的矩形.

有没有办法做到这一点?

我想我不能很好地表达自己.这就是我想要做的:示例图片.

假设红色的东西是一个矩形:)我想从图像中裁剪出那个东西.裁剪后,它不需要是天使.所以mj可以躺下来.

Rot*_*tem 6

此方法应执行您要求的操作.

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;
}
Run Code Online (Sandbox Code Playgroud)

用法(使用你的MJ例子):

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