1

我想要做的基本上是从图像中裁剪出一个矩形。但是,它应该满足一些特殊情况:

  1. 我想在图像上裁剪一个有角度的矩形。
  2. 我不想旋转图像并裁剪一个矩形:)
  3. 如果裁剪超过图像大小,我不想裁剪空的背景颜色。

我想从起点的后面裁剪,当矩形大小完成时,它将在起点结束。我知道我无法很好地解释,所以如果我在视觉上展示我想要的东西:

在此处输入图像描述

蓝点是那里的起点,箭头表示裁剪方向。当裁剪超出图像边界时,它将回到起点的后面,当矩形宽度和高度完成时,矩形的末端将在起点处。

除此之外,这是我问的上一个问题:

在这个问题中,我无法预测图像尺寸会出现问题,所以我没有要求它。但是现在有案例3。除了案例3,这是完全相同的问题。我该怎么做,有什么建议吗?

4

1 回答 1

1

需要做的是为矩阵对齐添加偏移量。在这种情况下,我从每一边(总共 9 个矩形)取出一个额外长度的矩形,并且每次都偏移矩阵。

请注意,必须将偏移量0(原始裁剪)放在最后,否则会得到错误的结果。

另请注意,如果您指定一个大于旋转图片的矩形,您仍然会得到空白区域。

public static Bitmap CropRotatedRect(Bitmap source, Rectangle rect, float angle, bool HighQuality)
{
    int[] offsets = { -1, 1, 0 }; //place 0 last!
    Bitmap result = new Bitmap(rect.Width, rect.Height);
    using (Graphics g = Graphics.FromImage(result))
    {
        g.InterpolationMode = HighQuality ? InterpolationMode.HighQualityBicubic : InterpolationMode.Default;
        foreach (int x in offsets)
        {
            foreach (int y in offsets)
            {
                using (Matrix mat = new Matrix())
                {
                    //create the appropriate filler offset according to x,y
                    //resulting in offsets (-1,-1), (-1, 0), (-1,1) ... (0,0)
                    mat.Translate(-rect.Location.X - rect.Width * x, -rect.Location.Y - rect.Height * y);
                    mat.RotateAt(angle, rect.Location);
                    g.Transform = mat;
                    g.DrawImage(source, new Point(0, 0));
                }
            }
        }
    }
    return result;
}

要重新创建您的示例:

Bitmap source = new Bitmap("C:\\mjexample.jpg");
Bitmap dest = CropRotatedRect(source, new Rectangle(86, 182, 87, 228), -45, true);
于 2012-01-09T13:11:57.197 回答