如何裁剪图像与旋转矩形? [英] How to crop an image with a rotated rectangle?

查看:144
本文介绍了如何裁剪图像与旋转矩形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 System.Drawing.Bitmap ,并在4个点(的形成矩形 Vector2 ■哪些被轻易地转化成的PointF S)。

I have an image in the form of a System.Drawing.Bitmap and a rectangle in the form of 4 points (Vector2s which are trivially converted to PointFs).

我想用这些点裁剪出的图像的部分。我发现这个答案是pretty的接近我想要的,但我不知道怎么弄的正确的矩阵出来。

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.

下面是我有这么远:

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?

推荐答案

想通了:

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

这篇关于如何裁剪图像与旋转矩形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆