Cropping a cross rectangle from an image using C #

What I want to do is basically crop the rectangle from the image. However, it must satisfy some special cases:

  • I want to crop the rectangle in the image.
  • I don’t want to rotate the image and crop the rectangle :)
  • If cropping exceeds the size of the image, I do not want to crop the empty background color.

I want to crop from the back of the starting point, which will end at the starting point when the size of the rectangle is complete. I know that I can’t explain, so if I show what I want visually:

enter image description here

The blue dot is the starting point, and the arrow shows the direction of cropping. When cropping exceeds the borders of the image, it will return to the back of the starting point, just as when the width and height of the rectangle are over, the end of the rectangle will be at the starting point.

Also, this is the previous question I asked:

In this matter, I could not predict that there might be a problem with the image size, so I did not ask about it. But now there is case 3. Except for case three, this is exactly the same question. How can I do this, any suggestions?

+1
source share
1 answer

What needs to be done is to add offsets to the alignment of the matrix. In this case, I take one additional length of the rectangle on each side (a total of 9 rectangles) and each time compensating for the matrix.

Note that you must put offset 0 (the original frame) last, otherwise you will get the wrong result.

Also note that if you specify a rectangle that is larger than the rotated image, you will still get empty areas.

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

To recreate your example:

 Bitmap source = new Bitmap("C:\\mjexample.jpg"); Bitmap dest = CropRotatedRect(source, new Rectangle(86, 182, 87, 228), -45, true); 
+1
source

All Articles