Question

I guess this one is rather simple for those who use GDI more frequently. I have an image that I want to rotate.

Sample image:

before rotation

After I apply my rotation, it looks like the following:

enter image description here

Here's the code used:

public Bitmap RotateBitmap(Bitmap bitmap, float angle)
{
    using (Graphics graphics = Graphics.FromImage(bitmap))
    {
        graphics.TranslateTransform((float)bitmap.Width / 2, (float)bitmap.Height / 2);
        graphics.RotateTransform(angle);
        graphics.TranslateTransform(-(float)bitmap.Width / 2, -(float)bitmap.Height / 2);
        graphics.DrawImage(bitmap, new Point(0, 0));
    }
    return bitmap;
}

What I want to get rid of is the part of the image that remains there from before the rotation. Any attempts to use DrawRectangle and Clear before calling DrawImage gave me white images, which makes some kind of sense.

Was it helpful?

Solution

Try the following:

public Bitmap RotateBitmap(Image bitmap, float angle) {
    Bitmap result = new Bitmap(bitmap.Width, bitmap.Height, bitmap.PixelFormat);
    using(Graphics graphics = Graphics.FromImage(result)) {
        graphics.TranslateTransform((float)bitmap.Width / 2f, (float)bitmap.Height / 2f);
        graphics.RotateTransform(angle);
        graphics.TranslateTransform(-(float)bitmap.Width / 2f, -(float)bitmap.Height / 2f);
        graphics.DrawImage(bitmap, Point.Empty);
    }
    return result;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top