5

我想获取图像的某些特定部分,所以我正在裁剪图像。但是,当我想要获得与图像不平行的部分时,我会旋转图像并随后进行裁剪。

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

有没有办法做到这一点?

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

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

4

1 回答 1

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;
}

用法(使用您的 MJ 示例):

Bitmap src = new Bitmap("C:\\mjexample.jpg");
Rectangle rect = new Rectangle(272, 5, 100, 350);
Bitmap cropped = CropRotatedRect(src, rect, -42.5f, true);
于 2012-01-02T11:41:11.527 回答