|
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
{
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:
- 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.
- 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
| You must Sign In to use this message board. |
|
| | Msgs 1 to 25 of 39 (Total in Forum: 39) (Refresh) | FirstPrevNext |
|
|
 |
|
|
I noticed in your example and in the other examples from the comments that the top and left sides of the rotated imaged don't get anti-aliased like the right and bottom edges do. Anyone found a solution for that??
-Isaac Nicolay
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
I figured out a solution by talking to the author of the article, in your rotation function before you start the rotation, if you put a 1 pixel edge on the top and left sides of the image like:
Bitmap bit = new Bitmap(image.Width + 1, image.Height + 1); Graphics gr = Graphics.FromImage(bit); gr.Clear(Color.White); gr.DrawImage(image, new Point(1, 1)); image = (System.Drawing.Image)bit;
it will anti-alias correclty. I chose white because I am showing it on a white background on a webpage. I would guess you should be able to use Color.Transparent if you are using it in a windows form or if you are doing a gif file.
-Isaac Nicolay
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
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
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Public Sub Rotate(ByRef imgSrc As Image, ByVal Angle As Single, ByVal BackColor As Color) Dim dA As Double Dim iPointsX(3) As Integer Dim iPointsY(3) As Integer Dim dR As Double = 0.5 * Math.Sqrt(Math.Pow(imgSrc.Height, 2) + Math.Pow(imgSrc.Width, 2)) Dim dAngleRad As Double = Math.PI * Angle / 180 Dim iK As Integer = -1 For I As Integer = 1 To 4 dA = Math.PI * (I \ 3) + iK * Math.Atan(imgSrc.Height / imgSrc.Width) iPointsX(I - 1) = dR * Math.Cos(dAngleRad + dA) + imgSrc.Width * 0.5 iPointsY(I - 1) = dR * Math.Sin(dAngleRad + dA) + imgSrc.Height * 0.5 iK *= -1 Next Dim pts() As Point = {New Point(iPointsX(3), iPointsY(3)), New Point(iPointsX(0), iPointsY(0)), New Point(iPointsX(2), iPointsY(2))} Array.Sort(iPointsX) Array.Sort(iPointsY) Dim imgNew As Bitmap = New Bitmap(iPointsX(3) - iPointsX(0), iPointsY(3) - iPointsY(0)) Dim graSrc As Graphics = Graphics.FromImage(imgNew) graSrc.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic graSrc.Clear(BackColor) For I As Integer = 0 To 2 pts(I).X -= iPointsX(0) pts(I).Y -= iPointsY(0) Next graSrc.DrawImage(imgSrc, pts) graSrc.Dispose() imgSrc = imgNew End Sub
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Why not transform the points of the bounds of the image directly using the matrix? The resulting min/max values will form the new bounds... (ignore the generic function at the bottom, I just use it to get the min/max values out of a series of parameters).
private static Rectangle GetRotatedBounds(Bitmap bmp, Point rotationCenter, float angle) { // Create rotation matrix Matrix newMatrix = new Matrix(); newMatrix.RotateAt(angle, rotationCenter);
// Get bounds of the original unrotated image Rectangle bmpBounds = new Rectangle(new Point(0, 0), new Size(bmp.Width, bmp.Height));
// Construct rectangle with these bounds Point[] points = { new Point(bmpBounds.Left, bmpBounds.Top), new Point(bmpBounds.Right, bmpBounds.Top), new Point(bmpBounds.Right, bmpBounds.Bottom), new Point(bmpBounds.Left, bmpBounds.Bottom)};
// Rotate the points of the bounds newMatrix.TransformPoints(points);
// Get min/max values of the new bounds int maxX = BinaryReduce<int>(Math.Max, points[0].X, points[1].X, points[2].X, points[3].X); int minX = BinaryReduce<int>(Math.Min, points[0].X, points[1].X, points[2].X, points[3].X);
int maxY = BinaryReduce<int>(Math.Max, points[0].Y, points[1].Y, points[2].Y, points[3].Y); int minY = BinaryReduce<int>(Math.Min, points[0].Y, points[1].Y, points[2].Y, points[3].Y);
// Return resulting bounding rectangle return new Rectangle(new Point(minX, minY), new Size(maxX - minX, maxY - minY)); }
private delegate T BinaryFunction<T>(T a, T b);
private static T BinaryReduce<T>(BinaryFunction<T> function, params T[] values) { if (values.Length == 0) return default(T);
if(values.Length == 1) return values[0];
T result = values[0]; for(int i = 1; i < values.Length; i++) result = function(result, values[i]);
return result; }
This works well for me...
You can easily modify my code to get the boundaries of any rotated shape if you pass the points-array into the GetRotatedBounds as well instead of getting them from the image.
|
| Sign In·View Thread·PermaLink | 2.50/5 (2 votes) |
|
|
|
 |
|
|
I really liked this approach to rotating an image using DrawImage. However I think you might have overcomplicated it a bit. You in fact only need to take the starting 3 points, rotate them about the centre, then draw the image between the rotated points
private static Bitmap AlternativeRotateImage( Image image, double angle ) { /* From MSDN spec * The destPoints parameter specifies three points of a parallelogram. * The three PointF structures represent the upper-left, upper-right, * and lower-left corners of the parallelogram * */ Bitmap rotatedImage = new Bitmap( image.Width, image.Height ); PointF[] points = new PointF[3]; double radAngle = ( angle * Math.PI ) / 180; double sin = Math.Sin( radAngle ); double cos = Math.Cos( radAngle ); double halfWidth = image.Width / 2; double halfHeight = image.Height / 2; double cosWidth = cos * halfWidth; double cosHeight = cos * halfHeight; double sinWidth = sin * halfWidth; double sinHeight = sin * halfHeight; points[ 0 ] = new PointF ( (float)( halfWidth - cosWidth + sinHeight ), (float)( halfHeight - cosHeight - sinWidth ) ); points[ 1 ] = new PointF ( (float)( halfWidth + cosWidth + sinHeight ), (float)( halfHeight - cosHeight + sinWidth ) ); points[ 2 ] = new PointF ( (float)( halfWidth - cosWidth - sinHeight ), (float)( halfHeight + cosHeight - sinWidth ) ); Graphics rotatedImageGraphics = Graphics.FromImage( rotatedImage ); rotatedImageGraphics.DrawImage( image, points ); return rotatedImage; }
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Did you test your alternative code? Try to rotate an image by 30 degrees and see the image edges cropped off. Your code doesn't get the right image bounds.:->
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Im rotating pics for a game and the use magenta (255,0,255) for transparent but as the image gets antialised it shows up with magenta borders (as theyre not perfectly magenta)
I tried with g.SmoothingMode = SmoothingMode.None; but the result is the same
- thomasa88
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
I like your article and it lead me in the direction I needed. I reworked your code so that my weak trig skills don't slow me down. I also decided to flip the Bitmap onto an new one and keep a copy of the old one for future rotations. You may want to take a look at your Graphics device. I don't think you call dispose() after you are done with it.
Have you found a way to AntiAlias the sides during the redraw?
public static Bitmap RotateImage2(Bitmap bmp, float angle) { Bitmap retbmp = null;
//Get the current rectangle points Point[] pts = new Point[] { new Point(0, 0), new Point(bmp.Width, 0), new Point(bmp.Width, bmp.Height), new Point(0, bmp.Height) };
// put the center point at (0,0) for the rotation for (int i = 0; i < 4; i++) { pts[i].X -= bmp.Width / 2; pts[i].Y -= bmp.Height / 2; }
//rotate the Rectangle Matrix m = new Matrix(); m.Rotate(angle); m.TransformPoints(pts); m.Dispose();
//Locate the new rectangle int maxX = int.MinValue; int maxY = int.MinValue; int minX = int.MaxValue; int minY = int.MaxValue; for (int i = 0; i < 4; i++) { if (maxX < pts[i].X) maxX = pts[i].X; if (maxY < pts[i].Y) maxY = pts[i].Y;
if (minX > pts[i].X) minX = pts[i].X; if (minY > pts[i].Y) minY = pts[i].Y; }
//reset the points to a 0,0 base for (int i = 0; i < 4; i++) { pts[i].X -= minX; pts[i].Y -= minY; }
//Create the new bitmap retbmp = new Bitmap(maxX - minX, maxY - minY, PixelFormat.Format32bppArgb); //Rotate the image onto the new Bitmap Graphics g = Graphics.FromImage(retbmp); Point[] finalPts = new Point[] { pts[0], pts[1], pts[3] }; g.DrawImage(bmp, finalPts); g.Dispose();
return retbmp; }
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
He did dispose of the Graphics object, with the using(Graphics g = Graphics.FromImage(rotatedBmp)) code block, that automatically calls Dispose() on the object inside the using() brackets.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
Hi there...
Good work, but when I'm using it i'm having problem that after rotation i get a black edges, i mean like the empty space is filled with black, any solution to this problem urgently please...
Aws
Aws Al Attar
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
If you do g.Clear(Color.White); on the line right after Graphics g = Graphics.FromImage(retbmp); you can set the background to whatever color you want!
-Isaac Nicolay
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Thank You Very Much i am trying this one from so many days.Now it's looking so simple.Thank u again.
Kranthi
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi James, I was trying to create a label of Image size but not succeeded. I need a label where I can rotate the Image and after rotation Label should also change the size with respect to image points.
Thanks, Chandra Prakash
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
 |
|
|
 |
|
|
How can we handle this for windows CE or PPC? As you know there are lots of limitations for image and bitmap objects. I m trying to do this with a faster algorithm but i can not found any now.
Tayfun (Architect)
|
| Sign In·View Thread·PermaLink | 1.50/5 (2 votes) |
|
|
|
 |
|
|
Simply put, doing a simple imagine rotation should just be as simple as transposing the X,Y coords in the original image to Y,X in the rotated copy. I can't recall if that rotates right or left but the other direction is (MaxY - Y),(maxX - X).
Just loop over the scanlines in the original image and write into a new Bitmap in tranposed coordinates. This works for the 90deg rotations.
If you still want this degree rotation, then you will have to a calculation intensive pattern like this. There is little that can be done to speed up trig. 
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
below i have written a routine which rotates the given bitmap with a specified angle
public static Bitmap RotateImage(Bitmap image,double angle) { int ow = image.Width; int oh = image.Height; Point oldMiddle = new Point(ow/2,oh/2); int newSize = (int)Pythagoras(ow,oh); Point newMiddle = new Point(newSize/2,newSize/2); Bitmap newBitmap = new Bitmap(newSize,newSize); Graphics g = Graphics.FromImage(newBitmap); double nx,ny; double pixelDist; double bearing; for (int x = 0; x < ow; x++) { for (int y = 0; y < oh ; y++) { Color c = image.GetPixel(x,y); pixelDist = Pythagoras(oldMiddle.X-x,oldMiddle.Y-y); /* Pythagoras calculates the sqrt of sqr(param1)+sqr(param2) bearing = BearingBetween(oldMiddle,new Point(x,y)); /* BearingBetween calculates the angle of the line from Point1 to point2 bearing = bearing + angle; bearing = 360 - bearing + 90; /* I have done this for compass scaling nx = newMiddle.X + pixelDist*Math.Cos(DegToRad(bearing)); ny = newMiddle.Y - pixelDist*Math.Sin(DegToRad(bearing)); newBitmap.SetPixel((int)nx, (int)ny,c); } } return newBitmap; }
this is not an optimal solution. Image boundaries gets larger and the rotated image is distorted why i did not understand. Also it will be slow for large images. Is there anybody who can handle with image distortion?
Tayfun YAĞCI
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
For Smart Device Application C# does not have the following Graphics.DrawImage(image,points) Graphics.Transform Drawing2D.Matrix Graphics.Rotate ... etc. As far as i know we have only Bitmap.Set(Get)Pixel(x,y) Grahics.DrawImage(Image,....Some Parameters not relevant to rotation or transposing ...) " We can zoom it but is it important ? "
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Thank you so much for such a good example. I'm appreciated your good work. Hope you will have more excellent about GDI+ examples in the future.
|
| Sign In·View Thread·PermaLink | 5.00/5 (1 vote) |
|
|
|
 |
|
|
Your algoritm may work for rectangles, but I've seen the algorithms for any path and it gets increasingly complex. Fortunately, Microsoft packed a lot of functionality into System.Drawing.Drawing2D.GraphicsPath(). After you transform your Image with a matrix, you should get a series of points or other coordinates. Using these, you can construct a new GraphicsPath and call GraphicsPath.GetBounds() to find the bounding rectangle that encloses all points. There's a lot more it can do, too, and I've found it very handy in many situations.
"Well, I wouldn't say I've been missing it, Bob." - Peter Gibbons
|
| Sign In·View Thread·PermaLink | | | | | | |