简体   繁体   English

如何裁剪带有旋转矩形的图像?

[英]How to crop an image with a rotated rectangle?

I have an image in the form of a System.Drawing.Bitmap and a rectangle in the form of 4 points ( Vector2 s which are trivially converted to PointF s). 我有一个System.Drawing.Bitmap形式的图像和一个4点形式的矩形(将Vector2转换为PointF )。

I want to use those points to crop out a section of the image. 我想使用这些点裁剪出图像的一部分。 I found this answer which is pretty close to what I want, but I'm not sure how to get the right matrix out of it. 我找到了这个答案该答案与我想要的非常接近,但是我不确定如何从中获得正确的矩阵。

Here's what I've got so far: 到目前为止,这是我得到的:

protected static Bitmap CropImage(Bitmap src, Vector2[] rect)
{
    var width = (rect[1] - rect[0]).Length;
    var height = (rect[3] - rect[0]).Length;
    var result = new Bitmap(M2.Round(width), M2.Round(height));
    using (Graphics g = Graphics.FromImage(result))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        using (Matrix mat = new Matrix())
        {
             // ????
        }
    }
    return result;
}

How can I get the proper transform matrix out of my rect? 如何从矩形中获取正确的变换矩阵?

It would be the same as in the linked answer, but instead of: 它与链接的答案相同,但不是:

mat.Translate(-rect.Location.X, -rect.Location.Y);
mat.RotateAt(angle, rect.Location);

You would use: 您将使用:

double angle = Math.Atan2(rect[1].Y - rect[0].Y, rect[1].X - rect[0].X);
mat.Translate(-rect[0].X, -rect[0].Y);
mat.RotateAt((float)angle, rect[0]);

(Or something along those lines. It may be -angle , or rect[0] instead of rect[1] and vice-versa in Atan2 . I can't check immediately…) (或者沿这些行的东西,也可以是-angle ,或rect[0]而不是rect[1]反之亦然在Atan2我不能立即检查...)

Figured it out: 弄清楚了:

protected static Bitmap CropImage(Bitmap src, Vector2[] rect)
{
    var width = (rect[1] - rect[0]).Length;
    var height = (rect[3] - rect[0]).Length;
    var result = new Bitmap(M2.Round(width), M2.Round(height));
    using (Graphics g = Graphics.FromImage(result))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        using (Matrix mat = new Matrix())
        {
            var rot = -Math.Atan2(rect[1].Y - rect[0].Y, rect[1].X - rect[0].X) * M2.RadToDeg;

            mat.Translate(-rect[0].X, -rect[0].Y);
            mat.RotateAt((float)rot, rect[0].ToPointF());

            g.Transform = mat;
            g.DrawImage(src, new Rectangle(0, 0, src.Width, src.Height));
        }
    }
    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM