Click here to Skip to main content
Licence BSD
First Posted 6 Dec 2002
Views 237,468
Downloads 9,132
Bookmarked 86 times

Image Rotation in .NET

By | 6 Dec 2002 | Article
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!

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.

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.

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

About the Author

James T. Johnson

Product Manager
GrapeCity, inc.
United States United States

Member

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 v1.0 was in beta 1.
 
He is currently employed by GrapeCity-Data Dynamics as a Product Manager for Data Dynamics Reports and Data Dynamics Analysis.
 
Code contained in articles where he is the sole author is licensed via the new BSD license.
 
Learn more about the products James works with at the CodeProject Catalog
ActiveReports | Data Dynamics Analysis | Data Dynamics Reports

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 Pinmembermanoj kumar choubey0:27 20 Feb '12  
Generaltanx message PinmemberMember 845688021:18 9 Dec '11  
GeneralMy vote of 5 Pinmembert1_t1_t14:51 17 Mar '11  
GeneralNot fast... PinmemberDemaker20:44 28 Jan '10  
AnswerRe: Not fast... PinmemberXmen W.K.15:40 11 Aug '10  
GeneralThis also works and is much faster :) PinmemberDragonSimon11:14 24 May '09  
Generalquality suffering during rotation Pinmemberrikki23375221:58 7 May '09  
GeneralRotateFlip Pinmembertobias0047:12 26 Apr '09  
Generalsaving the new image PinmemberSlylandro18:30 20 Oct '08  
GeneralThanks! PinmemberHughJampton23:14 4 Oct '08  
QuestionHow to rotate 3 or more words in a text line with different angles? PinmemberMaryamR1:40 22 Sep '08  
Questionthe quality of image falls when it rotates? PinmemberGIS_Developer3:39 2 Sep '08  
AnswerUSE THIS VERSION!!! :P PinmemberFocusedWolf8:40 14 Feb '09  
QuestionA version for compact framework? PinmemberOxcarz3:09 10 Aug '08  
GeneralTop and left side anti-aliasing Pinmemberwangforforyou12:51 5 Nov '07  
GeneralRe: Top and left side anti-aliasing Pinmemberwangforforyou8:44 6 Nov '07  
GeneralVB.NET version of the RotateImage function Pinmembertigerwood200618:51 28 Feb '07  
I found this piece of Code very helpful too. Here is the VB.NET version of the main Function: RotateImage. Note that i inserted a line: g.Clear(Color.White) to solve the problem of extra black regions outside the image area (i think this will not be the problem for some situations).
 

 
Public Function RotateImage(ByVal image As Image, ByVal angle As Single) As Drawing.Bitmap
            If image Is Nothing Then
                  Throw New ArgumentNullException("image")
            End If
 
            Dim pi2 As Single = Math.PI / 2.0
            Dim oldWidth As Single = image.Width
            Dim oldHeight As Single = image.Height
 
            'Convert degrees to radians
            Dim theta As Single = angle * Math.PI / 180.0
            Dim locked_theta As Single = theta
 

            ' Ensure theta is now [0, 2pi)
            If locked_theta < 0.0 Then locked_theta += 2 * Math.PI
 
            Dim newWidth, newHeight As Single
            Dim nWidth, nHeight As Integer
 
            Dim adjacentTop, oppositeTop As Single
            Dim adjacentBottom, oppositeBottom As Single
 
            If (locked_theta >= 0.0 And locked_theta < pi2) Or _
            (locked_theta >= Math.PI And locked_theta < (Math.PI + pi2)) Then
                  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
            End If
 

 
            newWidth = adjacentTop + oppositeBottom
            newHeight = adjacentBottom + oppositeTop
 
            nWidth = Int(Math.Ceiling(newWidth))
            nHeight = Int(Math.Ceiling(newHeight))
 
            Dim rotatedBmp As New Drawing.Bitmap(nWidth, nHeight)
 
            Dim g As Graphics = Graphics.FromImage(rotatedBmp)
 
            g.Clear(Color.White)
 
            '// This array will be used to pass in the three points that
            '// make up the rotated image
            Dim points(2) As Point
 
            If (locked_theta >= 0.0 And locked_theta < pi2) Then
 
                  points(0) = New Point(Int(oppositeBottom), 0)
                  points(1) = New Point(nWidth, Int(oppositeTop))
                  points(2) = New Point(0, Int(adjacentBottom))
 
            ElseIf locked_theta >= pi2 And locked_theta < Math.PI Then
 
                  points(0) = New Point(nWidth, Int(oppositeTop))
                  points(1) = New Point(Int(adjacentTop), nHeight)
                  points(2) = New Point(Int(oppositeBottom), 0)
 
            ElseIf locked_theta >= Math.PI And locked_theta < (Math.PI + pi2) Then
 
                  points(0) = New Point(Int(adjacentTop), nHeight)
                  points(1) = New Point(0, Int(adjacentBottom))
                  points(2) = New Point(nWidth, Int(oppositeTop))
 
            Else
 
                  points(0) = New Point(0, Int(adjacentBottom))
                  points(1) = New Point(Int(oppositeBottom), 0)
                  points(2) = New Point(Int(adjacentTop), nHeight)
            End If
 
            g.DrawImage(image, points)
 
            g.Dispose()
            image.Dispose()
 
            Return rotatedBmp
 
      End Function

GeneralRe: VB.NET version of the RotateImage function Pinmemberreso_od_ua12:50 30 May '08  
GeneralRe: VB.NET version of the RotateImage function PinmemberNarutoXD6:59 3 Sep '11  
GeneralEasy way to get the resulting bounds [modified] PinmemberQuimbo4:17 21 Sep '06  
GeneralAlternative Pinmembertimberly10:05 13 Jun '06  
GeneralRe: Alternative PinmemberT4Top23:45 16 Sep '06  
QuestionWithout antialiasing? Pinmemberthomasa8810:28 25 Feb '06  
GeneralLetting the Framework handle the Trig PinmemberMichael Potter11:17 21 Nov '05  
GeneralRe: Letting the Framework handle the Trig PinmemberCardinal45:20 26 May '07  

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

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120529.1 | Last Updated 7 Dec 2002
Article Copyright 2002 by James T. Johnson
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid