Search code examples
c++rotationpixel

Rotate pixel array 90 degrees in C++


I've written the next function to rotate an unsigned char pixel array which holds a RGB image by 90 degrees. The problem I'm facing is that the rotated output is all completely garbled.

void rotate90(unsigned char *buffer, const unsigned int width, const unsigned int height)
{
    const unsigned int sizeBuffer = width * height * 3; 
    unsigned char *tempBuffer = new unsigned char[sizeBuffer];

    for (int y = 0, destinationColumn = height - 1; y < height; ++y, --destinationColumn)
    {
        int offset = y * width;

        for (int x = 0; x < width; x++)
        {
            tempBuffer[(x * height) + destinationColumn] = buffer[offset + x];
        }
    }

    // Copy rotated pixels

    memcpy(buffer, tempBuffer, sizeBuffer);
    delete[] tempBuffer;
}

Solution

  • Replace the line in the inner-most loop with:

    for (int i = 0; i < 3; i++)
        tempBuffer[(x * height + destinationColumn) * 3 + i] = buffer[(offset + x) * 3 + i];