Click here to Skip to main content
Click here to Skip to main content

C# Image/PictureBox Rotations

By , 16 Feb 2010
 

Introduction

I was working on an Etch A Sketch like program and made a knob image and wanted to simply rotate it as the user hit the arrow keys. I found many sources online, but none that got it done just how I wanted (see links below in References section). I then decided since I figured it out and got it all working why not make a simple demo with source that others could use.

Background

  • Loading an image from a dialogue prompt
  • Creating bitmaps, image/draw updates, and Graphic manipulation

Using the Code

There is a class called Utilities in the Utilities.cs file that contains the functions for rotating an image from the center or given an offset to rotate from.

Here is the main rotation function RotateImage:

/// <summary>
/// Creates a new Image containing the same image only rotated
/// </summary>
/// <param name=""image"">The <see cref=""System.Drawing.Image"/"> to rotate
/// <param name=""offset"">The position to rotate from.
/// <param name=""angle"">The amount to rotate the image, clockwise, in degrees
/// <returns>A new <see cref=""System.Drawing.Bitmap"/"> of the same size rotated.</see>
/// <exception cref=""System.ArgumentNullException"">Thrown if <see cref=""image"/"> 
/// is null.</see>
public static Bitmap RotateImage(Image image, PointF offset, float angle)
{
    if (image == null)
        throw new ArgumentNullException("image");
        
    //create a new empty bitmap to hold rotated image
    Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
    rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);
    
    //make a graphics object from the empty bitmap
    Graphics g = Graphics.FromImage(rotatedBmp);
    
    //Put the rotation point in the center of the image
    g.TranslateTransform(offset.X, offset.Y);
    
    //rotate the image
    g.RotateTransform(angle);
    
    //move the image back
    g.TranslateTransform(-offset.X, -offset.Y);
    
    //draw passed in image onto graphics object
    g.DrawImage(image, new PointF(0, 0));
    
    return rotatedBmp;
}

And here is how it is used:

//Load an image in from a file
Image image = new Bitmap("Picture.png");
//Set our picture box to that image
pictureBox.Image = (Bitmap)image.Clone();

//Store our old image so we can delete it
Image oldImage = pictureBox.Image;
//Pass in our original image and return a new image rotated 35 degrees right
pictureBox.Image = Utilities.RotateImage(image, 35);
if (oldImage != null)
{
    oldImage.Dispose();
} 

Points of Interest

Graphics are very powerful and allow you to do image manipulation really easily. For instance, this code could easily be modified to scale instead. I may added to this with more utilities like that.

References

History

  • 16th February, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

MusicMonkey5555
United States United States
Member
No Biography provided

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.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralthanksmemberLe Ngoc12 May '13 - 1:03 
thanks for your share
QuestionthanksmemberMember 788837319 Mar '13 - 0:18 
thanks
GeneralMy vote of 4memberMember 32777606 May '12 - 21:04 
code example not complete. implementation for method RotateImage(Image image, float angle) not given in explanation though source code is available.
QuestionThanks - but for 90/180 degrees rotations...membercopa01721 Feb '12 - 11:49 
...its much easier to use built in funtion of Image.RotateFlip(RotateFlipType.Rotate180FlipNone)
AnswerRe: Thanks - but for 90/180 degrees rotations...memberMusicMonkey555519 Mar '13 - 7:21 
This is true. I specifically wrote this though because I didn't want to just flip it. I suppose I could have done a check for the rotation value given and done that in those cases.
QuestionHere's a slightly more flexible version for rotating an image (with and without clipping), angle -180 to +180 degrees [modified]membervictorbos28 Oct '11 - 8:11 
public static Bitmap RotateImage(Image image, float angle)
{
    // center of the image
    float rotateAtX = image.Width / 2;
    float rotateAtY = image.Height / 2;
    bool bNoClip = false;
    return RotateImage(image, rotateAtX, rotateAtY, angle, bNoClip);
}
 
public static Bitmap RotateImage(Image image, float angle, bool bNoClip)
{
    // center of the image
    float rotateAtX = image.Width / 2;
    float rotateAtY = image.Height / 2;
    return RotateImage(image, rotateAtX, rotateAtY, angle, bNoClip);
}
 
public static Bitmap RotateImage(Image image, float rotateAtX, float rotateAtY, float angle, bool bNoClip)
{
    int W, H, X, Y;
    if (bNoClip)
    {
        double dW = (double)image.Width;
        double dH = (double)image.Height;
 
        double degrees = Math.Abs(angle);
        if (degrees <= 90)
        {
            double radians = 0.0174532925 * degrees;
            double dSin = Math.Sin(radians);
            double dCos = Math.Cos(radians);
            W = (int)(dH * dSin + dW * dCos);
            H = (int)(dW * dSin + dH * dCos);
            X = (W - image.Width) / 2;
            Y = (H - image.Height) / 2;
        }
        else
        {
            degrees -= 90;
            double radians = 0.0174532925 * degrees;
            double dSin = Math.Sin(radians);
            double dCos = Math.Cos(radians);
            W = (int)(dW * dSin + dH * dCos);
            H = (int)(dH * dSin + dW * dCos);
            X = (W - image.Width) / 2;
            Y = (H - image.Height) / 2;
        }
    }
    else
    {
        W = image.Width;
        H = image.Height;
        X = 0;
        Y = 0;
    }
 
    //create a new empty bitmap to hold rotated image
    Bitmap bmpRet = new Bitmap(W, H);
    bmpRet.SetResolution(image.HorizontalResolution, image.VerticalResolution);
 
    //make a graphics object from the empty bitmap
    Graphics g = Graphics.FromImage(bmpRet);
 
    //Put the rotation point in the "center" of the image
    g.TranslateTransform(rotateAtX+X, rotateAtY+Y);
 
    //rotate the image
    g.RotateTransform(angle);
 
    //move the image back
    g.TranslateTransform(-rotateAtX - X, -rotateAtY - Y);
 
    //draw passed in image onto graphics object
    g.DrawImage(image, new PointF(0+X, 0+Y));
 
    return bmpRet;
}


modified 28 Oct '11 - 14:22.

AnswerRe: Here's a slightly more flexible version for rotating an image (with and without clipping), angle -180 to +180 degreesmemberMember 190497013 Feb '12 - 3:12 
Very nice improvement.
GeneralThanxmemberraananv29 May '11 - 21:12 
Love it ! Smile | :)
GeneralMy vote of 5memberatix-group15 Feb '11 - 3:59 
awesome!
Generalthanks!memberpeejay0224 Aug '10 - 0:01 
nice code.

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 16 Feb 2010
Article Copyright 2010 by MusicMonkey5555
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid