3

I am trying to rotate a picture with C#, and am using this code:

///create a new empty bitmap to hold rotated image
Bitmap returnBitmap = new Bitmap(newBMP.Width, newBMP.Height);
//make a graphics object from the empty bitmap
Graphics g = Graphics.FromImage(returnBitmap);
//move rotation point to center of image
g.TranslateTransform((float)newBMP.Width / 2, (float)newBMP.Height / 2);
//rotate
g.RotateTransform(-90);
//move image back
g.TranslateTransform(-(float)newBMP.Width / 2, -(float)newBMP.Height / 2);
//draw passed in image onto graphics object
g.DrawImage(newBMP, new Point(0, 0)); 

The newBMP is a bitmap that I getting from a form, and I am changing its size. Then I want to rotate it, but when I try this code above, it cuts the top and the floor of the picture. After all of this, I save the new pic on the server.

All works fine except the rotate...

Anyone see the problem?

solved i used this: C# rotate bitmap 90 degrees

Community
  • 1
  • 1
Jordan
  • 570
  • 1
  • 6
  • 24
  • 7
    Surely the width and height or the `returnBitmap` need to be swapped if you are rotating by 90°? – Tim Rogers Mar 13 '13 at 14:40
  • I agree with the previous comment. You can just change width and height for 90°, 180°. For any degrees see my solution here: [stackoverflow.com: C#, rotating Graphics?](https://stackoverflow.com/questions/5172906/c-rotating-graphics/48725273#48725273) – Pavel Samoylenko Feb 10 '18 at 20:38

3 Answers3

1

If the bitmap is wider than it is tall, you're going to get cropping when you rotate it 90 degrees. You need to take that into account when you call g.TranslateTranform.

Ed Schwehm
  • 2,163
  • 4
  • 32
  • 55
0

This answer was just answered (for any angle) for vb.net on stack overflow...

How to rotate JPEG using Graphics.RotateTransform without clipping

Should be easy to convert to C#

Community
  • 1
  • 1
Scott Savage
  • 373
  • 1
  • 4
  • 17
0
 public static Bitmap RotateImage(Bitmap image, float angle)
    {
        //create a new empty bitmap to hold rotated image

        double radius = Math.Sqrt(Math.Pow(image.Width, 2) + Math.Pow(image.Height, 2));

        Bitmap returnBitmap = new Bitmap((int)radius, (int)radius);

        //make a graphics object from the empty bitmap
        using (Graphics graphic = Graphics.FromImage(returnBitmap))
        {
            //move rotation point to center of image
            graphic.TranslateTransform((float)radius / 2, (float)radius / 2);
            //rotate
            graphic.RotateTransform(angle);
            //move image back
            graphic.TranslateTransform(-(float)image.Width / 2, -(float)image.Height / 2);
            //draw passed in image onto graphics object
            graphic.DrawImage(image, new Point(0, 0));
        }
        return returnBitmap;
    }
Steve
  • 21
  • 4