GDI+ Rotated sub-image
I have a rather large (30MB) image that I would like to take a small "slice" out of. The slice needs to represent a rotated portion of the original image.
The following works but the corners are empty and it appears that I am taking a rectangular area of the original image, then rotating that and drawing it on an unrotated surface resulting in the missing corners.
What I want is a rotated selection on the original image that is then drawn on an unrot开发者_如何学运维ated surface. I know I can first rotate the original image to accomplish this but this seems inefficient given its size.
Any suggestions? Thanks,
public Image SubImage(Image image, int x, int y, int width, int height, float angle)
{
var bitmap = new Bitmap(width, height);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.TranslateTransform(bitmap.Width / 2.0f, bitmap.Height / 2.0f);
graphics.RotateTransform(angle);
graphics.TranslateTransform(-bitmap.Width / 2.0f, -bitmap.Height / 2.0f);
graphics.DrawImage(image, new Rectangle(0, 0, width, height), x, y, width, height, GraphicsUnit.Pixel);
}
return bitmap;
}
You should performance test this before deciding on the best approach, but two options are
- As you suggest, rotate the image first and then extract the inner rectangle.
- Extract an inner rectangle that is larger than the required rotated portion, but smaller that then entire image. Rotate this new image and then extract the inner image from the rotated sub image.
Option 2 basically allows you to perform the rotation on a smaller image than the entire image.
Like I say I would do some decent performance testing to determine if going with option 2 over option 1 is really worth it.
精彩评论