问题
I want to get some specific parts of an image so I'm cropping the images. However, when I want to get a part that is not parallel to the image, I rotate the image and crop afterwards.
I don't want to rotate the image and crop a parallel rectangle. What I want is, without rotating the image, to crop a rectangle with an angle from the image.
Is there any way to do that?
I think I couldnt express myself well enough. This is what I want to do: example picture.
Assume the red thing is a rectangle :) I want to crop that thing out of image. After cropping it doesn't need to be angeled. So mj can lie down.
回答1:
This method should perform what you asked for.
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;
}
usage (using your MJ example):
Bitmap src = new Bitmap("C:\\mjexample.jpg");
Rectangle rect = new Rectangle(272, 5, 100, 350);
Bitmap cropped = cropRotatedRect(src, rect, -42.5f, true);
来源:https://stackoverflow.com/questions/8699103/how-to-crop-a-cross-rectangle-from-an-image-using-c