Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to crop a cross rectangle from an image using c#?

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.

like image 723
user1125953 Avatar asked Jan 02 '12 09:01

user1125953


1 Answers

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);
like image 185
Rotem Avatar answered Sep 18 '22 02:09

Rotem