How to rotate an image of picturebox with desired angle in C#?
Sometimes it is necessory to rotate an image using code.
Creating new bitmap and putting it back to picturebox is very easy.
This sample code is used for the same. I hope it will be useful for you all.
Introduction:
In windows form , put one picturebox and add some image into it.
Put one button and give the name as btnRotate to it. Put one textbox to get the desired angle from user.
After clicking on btnRotate, image which is present in picturebox1 should rotate with the desired angle given by user.
btnRotate_Click code is as follows:
private void btnRotate_Click(object sender, EventArgs e)
{
Bitmap resultPicture = MoveImageByDesiredAngle(pictureBox1.Image.Width, pictureBox1.Image.Height, Convert.ToInt32(textBox1.Text));
pictureBox1.Image = resultPicture;
}
Method MoveImageByDesiredAngle is used to rotate an image with desired angle. code is as follows:
private Bitmap MoveImageByDesiredAngle(int original_width , int original_height, int desiredAngle)
{
Bitmap resultPicture = new Bitmap(original_width, original_height);
Graphics g = Graphics.FromImage(resultPicture);
g.TranslateTransform((float)original_width / 2, (float)original_height / 2);
g.RotateTransform(desiredAngle);
g.TranslateTransform(-(float)original_width / 2, -(float)original_height / 2);
g.DrawImage(pictureBox1.Image , new Point(0, 0));
return resultPicture;
}