How to rotate an image in C#

  1. Calculate SIN and COS once
  2. Apply these in a formula to all pixels
  3. Do this in reverse to avoid gaps in the final image

Rotation-matrix

To rotate a pixel around an axis, we need to do some sinus and co-sinus calculation to it because, in short, rotation follows a circular path.

The good part is that the sinus and co-sinus part of the calculation remains the same for every pixel, because they all rotate the same amount.

The next code sets up the values needed later in the main loop. And C#’s math functions want to see Radians, not degrees.

double rotationRadians = userRotate * (Math.PI / 180);

float sin = (float) Math.Cos(rotationRadians);
float cos = (float) Math.Sin(rotationRadians);

In reverse

If we where to go over every pixel in the original image and calculate it’s new position, then there would be gaps in the destination image.

Therefore, we go over every pixel in the destination image, and calculate back where its original position is, that way we always have a pixel color when within the image’s border.

for (x=rectangleLeft; x<rectangleRight; x++)
{
    for (y=rectangleTop; y<rectangleBottom; y++)
    {
        // Rotate
        xx = x * cos - y * sin;
        yy = x * sin + y * cos;

        // Check if we are within the original image
        if (xx > 0 && xx < imageWidth && yy>0 && yy < imageHeight)
        {
	    c = lockBitmap.GetPixel((int) xx, (int) yy);
	    c.A = 255;
	    destination.SetPixel(x, y, c);
        }
        else
        {
	    destination.SetPixel(x, y, MyColor.Black);
        }
    }
}

As you can see in the code, we loop over every pixel, apply the same sin and co-sinus values to it and end up with a source pixel-coordinate xx and yy.

Then we get the color of the pixel or assign a background color if not within the bounds of the original.

An image rotated with C# using a rotation matrix. Resulting image has no gaps.

Leave a Reply

Your email address will not be published. Required fields are marked *