Click here to Skip to main content
15,886,095 members
Articles / Programming Languages / C#
Article

Image Rotation in .NET

Rate me:
Please Sign up or sign in to vote.
4.73/5 (72 votes)
6 Dec 2002BSD5 min read 418.4K   17.3K   91   59
Rotates an image without having to worry about cropping the edges.

Introduction

A few days ago Tweety asked me how you would go about rotating an Image object.  The reply seemed simple enough, use the Transform property of your Graphics object with a Matrix object having the appropriate Rotate method called on it.  But I forgot about one aspect regarding the transforms, while it is easy to rotate the Image, you have to jump through hoops to get it to rotate correctly and still remain in somewhat the same location.

Since I was disgusted from looking at the same non-working code for the past two weeks this was a welcome vacation. 

My first attempt

I wanted to take what seemed the obvious way to do this, so I started messing around with the Rotate/RotateAt methods and trying to figure out what the equation to create the proper translation should be.  Unfortunately I could never figure out the proper formula.  Looking over my previous drawings something did occur to me, I could figure out the size of the smallest possible rectangle in which the rotated bitmap would fit, or the bounding box.

My second attempt or Ah ha!

Given an angle of rotation, theta, and knowing the width and height of the original bitmap I can figure out the size of the triangles of 'empty space'. 

Some basic trig identities are used to calculate the lengths of the sides of the triangles.  Assuming a right triangle, then:

cos(theta) = length(adjacent)/length(hypotenuse)
sin(theta) = length(opposite)/length(hypotenuse)

Solving for the unknown you get:

length(adjacent) = cos(theta) * length(hypotenuse)
length(opposite) = sin(theta) * length(hypotenuse)

Since we have a known theta and hypotenuse we can calculate the length of the other two sides of each triangle.  To make it clear, the length of the hypotenuse is either the width or the height of the original rectangle, r

Now looking at the diagram we can see that the width of the bounding box will be oh + aw and the height of the bounding box will be ah + ow.  I'll leave it as an exercise for the reader to come up with the proof that shows why there are only at most two different sized triangles for any rectangle r in the above diagram.

Also looking at the diagram it became obvious what the coordinates of each corner of the bitmap would be for the rotation, now if only I had a way to specify the coordinates of each corner when drawing an image...what do you know, I do!

C#
Graphics.DrawImage(Image image, Point[] destPoints);

destPoints is a 3 element array of Point objects, which defines a parallelogram. The three points you need to pass in define where the upper-left corner, the upper-right corner, and the lower-left corner of the original image should be drawn. With this one method you can perform scales and rotations easily. 

The last part to take into consideration is that the above portions only work when the angle of rotation is between 0 and 90 degrees, or 0 and PI/2 radians.  But handling rotations greater than that is easy, by using the absolute value of the values of cos(theta) and sin(theta) the first rotation of 90 degrees will cause the return to go from 0 to 1 and the next rotation causes it to go from 1 to 0, repeating forever which is the behavior we desire.  The only tricky part is that each time you rotate 90 degrees the height and width need to switch, else you'll be calculating values based on the wrong hypotenuse.

While the bitmap is rotating, the points used differ for each quadrant theta is in, so when calculating the points I had to break it up based on that condition.

In the code snippet before 7 values are used, nWidth and

nHeight
are the width and height, respectively, of the bounding box/new bitmap.  adjacentTop and oppositeTop are the lengths of the adjacent and opposite sides of the triangle labeled top in the diagram.  The same is true for adjacentBottom and
oppositeBottom
except it uses the other triangle; the last value is of course 0.  Because the trig functions expect everything to be done in radians (and I prefer radians anyway), theta has been converted from degrees to radians.

C#
const double pi2 = Math.PI / 2.0;

if( theta >= 0.0 && theta < pi2 )
{
    points = new Point[] { 
        new Point( (int) oppositeBottom, 0 ), 
        new Point( nWidth, (int) oppositeTop ),
        new Point( 0, (int) adjacentBottom )
    };
}
else if( theta >= pi2 && theta < Math.PI )
{
    points = new Point[] { 
        new Point( nWidth, (int) oppositeTop ),
        new Point( (int) adjacentTop, nHeight ),
        new Point( (int) oppositeBottom, 0 )						 
    };
}
else if( theta >= Math.PI && theta < (Math.PI + pi2) )
{
    points = new Point[] { 
        new Point( (int) adjacentTop, nHeight ), 
        new Point( 0, (int) adjacentBottom ),
        new Point( nWidth, (int) oppositeTop )
    };
}
else // theta >= (Math.PI + pi2)
{
    points = new Point[] { 
        new Point( 0, (int) adjacentBottom ), 
        new Point( (int) oppositeBottom, 0 ),
        new Point( (int) adjacentTop, nHeight )		
    };
}

Intended usage

Rather than use the same bitmap for the rotation, I always create a new bitmap to draw on.  This is done for a couple reasons:

  1. Consistent behavior - since the point of this was to rotate a bitmap and have it not get cut off, I would have to create a new bitmap if the one passed in wasn't large enough.
  2. Consistent quality - if the same bitmap is rotated over and over again, eventually all the extrapolating done would degrade the image quality.

So when you pass an Image in, you will get a new one out and it should be of comparable quality to the original image.

The demo program is extremely basic, the only interesting portion of it, is that I made the NumericUpDown control wrap around using the next bit of code.

C#
if( angle.Value > 359.9m )
{
    angle.Value = 0;
    return ;
}

if( angle.Value < 0.0m )
{
    angle.Value = 359.9m;
    return ;
}

pictureBox.Image = Utilities.RotateImage(img, 
    (float) angle.Value );

After setting the new value I return from the method so that it can run again because of the change I made.

Acknowledgments

  • Tweety for asking the question which got me into writing the code and the article
  • Shog9 and PJ Arends for offering suggestions and pointing me in the right direction while I was stuck with the code not working for non-square images.

History

  • December 7, 2002 - Initial posting

License

This article, along with any associated source code and files, is licensed under The BSD License


Written By
Software Developer (Senior) InfoPlanIT, LLC
United States United States
James has been programming in C/C++ since 1998, and grew fond of databases in 1999. His latest interest has been in C# and .NET where he has been having fun writing code starting when .NET v1.0 was in its first beta.

He is currently a senior developer and consultant for InfoPlanIT, a small international consulting company that focuses on custom solutions and business intelligence applications.

He was previously employed by ComponentOne where he was a Product Manager for the ActiveReports, Data Dynamics Reports, and ActiveAnalysis products.

Code contained in articles where he is the sole author is licensed via the new BSD license.

Comments and Discussions

 
General請問要如何把它轉換為mfc Pin
Member 118434541-Oct-15 22:03
Member 118434541-Oct-15 22:03 
Questionthanks Pin
2010sampel25-Nov-12 11:14
2010sampel25-Nov-12 11:14 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey20-Feb-12 0:27
professionalManoj Kumar Choubey20-Feb-12 0:27 
Generaltanx message Pin
Member 84568809-Dec-11 21:18
Member 84568809-Dec-11 21:18 
GeneralMy vote of 5 Pin
t1_t1_t117-Mar-11 4:51
t1_t1_t117-Mar-11 4:51 
GeneralNot fast... Pin
Demaker28-Jan-10 20:44
Demaker28-Jan-10 20:44 
AnswerRe: Not fast... Pin
Xmen Real 11-Aug-10 15:40
professional Xmen Real 11-Aug-10 15:40 
GeneralThis also works and is much faster :) Pin
DragonSimon24-May-09 11:14
DragonSimon24-May-09 11:14 
Generalquality suffering during rotation Pin
rikki2337527-May-09 21:58
rikki2337527-May-09 21:58 
GeneralRotateFlip Pin
tobias00426-Apr-09 7:12
tobias00426-Apr-09 7:12 
Generalsaving the new image Pin
Slylandro20-Oct-08 18:30
Slylandro20-Oct-08 18:30 
GeneralThanks! Pin
HughJampton4-Oct-08 23:14
HughJampton4-Oct-08 23:14 
QuestionHow to rotate 3 or more words in a text line with different angles? Pin
MaryamR22-Sep-08 1:40
MaryamR22-Sep-08 1:40 
Questionthe quality of image falls when it rotates? Pin
GIS_Developer2-Sep-08 3:39
GIS_Developer2-Sep-08 3:39 
AnswerUSE THIS VERSION!!! :P Pin
FocusedWolf14-Feb-09 8:40
FocusedWolf14-Feb-09 8:40 
I went in and tuned this persons code so now the image rotation is perfect from i can see. Their was some calls to Math.Cieling in original code, and uses of int when float was acceptable, etc that just messed up the image... so after i fixed all that, the code works really perfectly now :P

In my program, i let the user rotate a image by dragging on a progressbar... so i do low quality rotations and when user releases mouse button, it does one high quality... that's just some advice for people that need a performance boost :P

public static Bitmap RotateImage(Image image, double angle, bool highDetail)
        {
            if (image == null)
                throw new ArgumentNullException("image");

            const double pi2 = Math.PI / 2.0D;

            // Why can't C# allow these to be const, or at least readonly
            // *sigh*  I'm starting to talk like Christian Graus :omg:
            double oldWidth = (double)image.Width;
            double oldHeight = (double)image.Height;

            // Convert degrees to radians
            double theta = angle * Math.PI / 180.0D;
            double locked_theta = theta;

            // Ensure theta is now [0, 2pi)
            while (locked_theta < 0.0D)
                locked_theta += 2.0D * Math.PI;

            double newWidth, newHeight;
            int nWidth, nHeight; // The newWidth/newHeight expressed as ints

        #region Explaination of the calculations
            /*
			 * The trig involved in calculating the new width and height
			 * is fairly simple; the hard part was remembering that when 
			 * PI/2 <= theta <= PI and 3PI/2 <= theta < 2PI the width and 
			 * height are switched.
			 * 
			 * When you rotate a rectangle, r, the bounding box surrounding r
			 * contains for right-triangles of empty space.  Each of the 
			 * triangles hypotenuse's are a known length, either the width or
			 * the height of r.  Because we know the length of the hypotenuse
			 * and we have a known angle of rotation, we can use the trig
			 * function identities to find the length of the other two sides.
			 * 
			 * sine = opposite/hypotenuse
			 * cosine = adjacent/hypotenuse
			 * 
			 * solving for the unknown we get
			 * 
			 * opposite = sine * hypotenuse
			 * adjacent = cosine * hypotenuse
			 * 
			 * Another interesting point about these triangles is that there
			 * are only two different triangles. The proof for which is easy
			 * to see, but its been too long since I've written a proof that
			 * I can't explain it well enough to want to publish it.  
			 * 
			 * Just trust me when I say the triangles formed by the lengths 
			 * width are always the same (for a given theta) and the same 
			 * goes for the height of r.
			 * 
			 * Rather than associate the opposite/adjacent sides with the
			 * width and height of the original bitmap, I'll associate them
			 * based on their position.
			 * 
			 * adjacent/oppositeTop will refer to the triangles making up the 
			 * upper right and lower left corners
			 * 
			 * adjacent/oppositeBottom will refer to the triangles making up 
			 * the upper left and lower right corners
			 * 
			 * The names are based on the right side corners, because thats 
			 * where I did my work on paper (the right side).
			 * 
			 * Now if you draw this out, you will see that the width of the 
			 * bounding box is calculated by adding together adjacentTop and 
			 * oppositeBottom while the height is calculate by adding 
			 * together adjacentBottom and oppositeTop.
			 */
            #endregion

            double adjacentTop, oppositeTop;
            double adjacentBottom, oppositeBottom;

            // We need to calculate the sides of the triangles based
            // on how much rotation is being done to the bitmap.
            //   Refer to the first paragraph in the explaination above for 
            //   reasons why.
            if ((locked_theta >= 0.0D && locked_theta < pi2) ||
                (locked_theta >= Math.PI && locked_theta < (Math.PI + pi2)))
            {
                adjacentTop = Math.Abs(Math.Cos(locked_theta)) * oldWidth;
                oppositeTop = Math.Abs(Math.Sin(locked_theta)) * oldWidth;

                adjacentBottom = Math.Abs(Math.Cos(locked_theta)) * oldHeight;
                oppositeBottom = Math.Abs(Math.Sin(locked_theta)) * oldHeight;
            }
            else
            {
                adjacentTop = Math.Abs(Math.Sin(locked_theta)) * oldHeight;
                oppositeTop = Math.Abs(Math.Cos(locked_theta)) * oldHeight;

                adjacentBottom = Math.Abs(Math.Sin(locked_theta)) * oldWidth;
                oppositeBottom = Math.Abs(Math.Cos(locked_theta)) * oldWidth;
            }

            newWidth = adjacentTop + oppositeBottom;
            newHeight = adjacentBottom + oppositeTop;

            nWidth = (int)newWidth;
            nHeight = (int)newHeight;

            Bitmap rotatedBmp = new Bitmap(nWidth, nHeight);

            using (Graphics g = Graphics.FromImage(rotatedBmp))
            {
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                if (highDetail)
                {
                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                }

                else
                {
                    g.SmoothingMode = SmoothingMode.None;
                    g.InterpolationMode = InterpolationMode.Low;
                }

                // This array will be used to pass in the three points that 
                // make up the rotated image
                PointF[] points;

                /*
                 * The values of opposite/adjacentTop/Bottom are referring to 
                 * fixed locations instead of in relation to the
                 * rotating image so I need to change which values are used
                 * based on the how much the image is rotating.
                 * 
                 * For each point, one of the coordinates will always be 0, 
                 * nWidth, or nHeight.  This because the Bitmap we are drawing on
                 * is the bounding box for the rotated bitmap.  If both of the 
                 * corrdinates for any of the given points wasn't in the set above
                 * then the bitmap we are drawing on WOULDN'T be the bounding box
                 * as required.
                 */
                if (locked_theta >= 0.0D && locked_theta < pi2)
                {
                    points = new PointF[] { 
											 new PointF( (float)oppositeBottom, 0.0F ), 
											 new PointF( (float)newWidth, (float)oppositeTop ),
											 new PointF( 0.0F, (float) adjacentBottom )
										 };

                }
                else if (locked_theta >= pi2 && locked_theta < Math.PI)
                {
                    points = new PointF[] { 
											 new PointF( (float)newWidth, (float) oppositeTop ),
											 new PointF( (float) adjacentTop, (float)newHeight ),
											 new PointF( (float) oppositeBottom, 0.0F )						 
										 };
                }
                else if (locked_theta >= Math.PI && locked_theta < (Math.PI + pi2))
                {
                    points = new PointF[] { 
											 new PointF( (float) adjacentTop, (float)newHeight ), 
											 new PointF( 0.0F, (float) adjacentBottom ),
											 new PointF( (float)newWidth, (float)oppositeTop )
										 };
                }
                else
                {
                    points = new PointF[] { 
											 new PointF( 0.0F, (float) adjacentBottom ), 
											 new PointF( (float) oppositeBottom, 0.0F ),
											 new PointF( (float) adjacentTop, (float)newHeight )		
										 };
                }
                g.DrawImage(image, points);
            }
            return rotatedBmp;
        }

GeneralRe: USE THIS VERSION!!! :P Pin
Southmountain1-Jul-22 8:32
Southmountain1-Jul-22 8:32 
QuestionA version for compact framework? Pin
Oxcarz10-Aug-08 3:09
Oxcarz10-Aug-08 3:09 
GeneralTop and left side anti-aliasing Pin
wangforforyou5-Nov-07 12:51
wangforforyou5-Nov-07 12:51 
GeneralRe: Top and left side anti-aliasing Pin
wangforforyou6-Nov-07 8:44
wangforforyou6-Nov-07 8:44 
GeneralVB.NET version of the RotateImage function Pin
tigerwood200628-Feb-07 18:51
tigerwood200628-Feb-07 18:51 
GeneralRe: VB.NET version of the RotateImage function Pin
reso_od_ua30-May-08 12:50
reso_od_ua30-May-08 12:50 
GeneralRe: VB.NET version of the RotateImage function Pin
NarutoXD3-Sep-11 6:59
NarutoXD3-Sep-11 6:59 
GeneralEasy way to get the resulting bounds [modified] Pin
Quimbo21-Sep-06 4:17
Quimbo21-Sep-06 4:17 
GeneralAlternative Pin
timberly13-Jun-06 10:05
timberly13-Jun-06 10:05 
GeneralRe: Alternative Pin
T4Top16-Sep-06 23:45
T4Top16-Sep-06 23:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.