Reader Level:
Articles

Rotate and Flip Images in Windows Forms

By Shubham Saxena on October 04, 2012
This is the step-by-step process of how to use builtin functions for rotating and flipping an image.
  • 0
  • 0
  • 13109

One of my friends asked me how to rotate an image to a particular angle, so I just thought of writing an article about it. The following is the step-by-step process of how to use builtin functions for rotating and flipping an image.

Step 1

Create a blank Windows Forms application, as in:

Windows-forms-application.jpg

Step 2

Add a pictureBox from the toolbox and add a source image to it.

Now comes the real part, using Image.RotateFlip we can rotate the image by standard angles (90, 180 or 270 degrees) or flip the image horizontally or vertically.

The parameter of RotateFlip is System.Drawing.RotateFlipType, which specifies the type of rotation and flip to apply to the image.

e.g. : pictureBox1.Image.RotateFlip(RotateFlipType.Rotate180FlipNone);

The preceding code will rotate the image in a pictureBox1 by an angle of 180 degrees.

Step 3

Now back to our code, add the namespaces to use as:

using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

Step 4

We will make a function RotateImg with two arguments one is the Bitmap Image and the other is the float angle. The code snippet is as follows :

public static Bitmap RotateImg(Bitmap bmp, float angle)

{

int w = bmp.Width;

int h = bmp.Height;

Bitmap tempImg = new Bitmap(w, h);

Graphics g = Graphics.FromImage(tempImg);

g.DrawImageUnscaled(bmp, 1, 1);

g.Dispose();

GraphicsPath path = new GraphicsPath();

path.AddRectangle(new RectangleF(0f, 0f, w, h));

Matrix mtrx = new Matrix();

mtrx.Rotate(angle);

RectangleF rct = path.GetBounds(mtrx);

Bitmap newImg = new Bitmap(Convert.ToInt32(rct.Width), Convert.ToInt32(rct.Height));

g = Graphics.FromImage(newImg);

g.TranslateTransform(-rct.X, -rct.Y);

g.RotateTransform(angle);

g.InterpolationMode = InterpolationMode.HighQualityBilinear;

g.DrawImageUnscaled(tempImg, 0, 0);

g.Dispose();

tempImg.Dispose();

return newImg;

}

Step 5

Now we have a function which will rotate an image to an arbitrary angle, I'm adding my code now to the form_load event so that as soon as the form loads my code is executed.

Bitmap bitmap = (Bitmap)pictureBox1.Image;
pictureBox1.Image = (Image)(RotateImg(bitmap, 30.0f));

The preceding two lines of code will first convert the image in pictureBox1 to a Bitmap image and then it will call our function RotateImg to rotate the image 30 degrees (for example).

Here is the snapshot of the output window:

output-Windows-forms-application.jpg

Shubham Saxena

I'm Shubham Saxena MVP (Oct'12 to Oct'13) at Mindcracker, Ex - Microsoft Student Partner, Software Engg at Accenture. I am here to write some interesting blogs and hope it helps you.

COMMENT USING

Trending up