Search code examples
c++arraysimagerotationpng

Rotating a PNG Image in C++


I am quite new to C++.

I have a PNG image which I am trying to rotate by 180 degrees.

The image is to be saved as a new file.

I have wrote out a bit of code but hit a brick wall, any tips for how to continue would be appreciated. Code so far is below, thanks in advance.

#include <QCoreApplication>
#include <iostream>
#include "ImageHandle.h"

using namespace std;

void rotatedImage (unsigned PixelGrid[WIDTH][HEIGHT]);

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
const char LogoFile[] = "Airplane.png";

unsigned PixelGrid[WIDTH][HEIGHT];     // Image loaded from file

// If the file cannot be loaded ...
if (!loadImage(PixelGrid, LogoFile))
{
    // Display an error message
    cout << "Error loading file \"" << LogoFile << "\"" << endl;
}
else
{
    cout << "File \"" << LogoFile << "\" opened successfully" << endl;

    // Demo of use of saveImage - to create a copy as "Airplane.png"
    // This should be modified to save the new images as specified
    if (saveImage(PixelGrid, "AirplaneCopy.png"))
    {
        cout << "File \"AirplaneCopy.png\" saved successfully" << 
endl;
    }
    else
    {
        cout << "Could not save \"AirplaneCopy.png\"" << endl;
    }
}

rotatedImage(PixelGrid);

{
    if (saveImage(PixelGrid, "AirplaneRotated.png"))
    {
        cout << "\nFile\"AirplaneRotated.png\" saved successfully" << 
endl;
    }
    else
    {
        cout << "\nCould not save \"AirplaneRotated.png\"" << endl;
    }
}

return a.exec();
}

void rotatedImage (unsigned PixelGrid[WIDTH][HEIGHT])
{
int row;
int col;

for (row = 0; row < WIDTH; row++)
{
    for (col = 0; col < HEIGHT; col++)
    {
        PixelGrid[row][col] = 
    }
}
}

Thanks again.


Solution

  • If all you need it rotate a picture 180 degree, I guess you can use simple loop on half the picture and swap in each iteration the position on 1 pair of pixels.

    Let look at pixel at position (i,j) - where should it be after the rotation? because it is 180, it should be at (WIDTH - i, HEIGHT -j) so your rotatedImage should look like:

    void rotatedImage (unsigned PixelGrid[WIDTH][HEIGHT])
    {
        int row;
        int col;
    
        for (row = 0; row < WIDTH/2; row++)// because you only have to loop on half the image
        {
            for (col = 0; col < HEIGHT; col++) 
            {
                unsigned temp = PixelGrid[row][col];
                PixelGrid[row][col] = PixelGrid[WIDTH - row][HEIGHT - col];
                PixelGrid[WIDTH - row][HEIGHT - col] = temp;
            }
        }
    }
    

    I am not c++ expert so I hope I have none syntax error and I never check that so beware from array out of index I may missed