在 C++ 中旋转 PNG 图像

Rotating a PNG Image in C++

我对 C++ 很陌生。

我有一张 PNG 图片,我想将其旋转 180 度。

图像将另存为新文件。

我写了一些代码,但遇到了困难,如有任何关于如何继续的提示,我们将不胜感激。到目前为止的代码如下,在此先感谢。

#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] = 
    }
}
}

再次感谢。

如果你只需要将图片旋转 180 度,我想你可以在一半图片上使用简单的循环,并在每次迭代中交换 1 对像素上的位置。

让我们看看位置 (i,j) 的像素 - 旋转后它应该在哪里?因为它是 180,它应该在 (WIDTH - i, HEIGHT -j) 所以你的 rotatedImage 应该看起来像:

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;
        }
    }
}

我不是 c++ 专家所以我希望我有 none 语法错误并且我从不检查它所以当心数组超出索引我可能会错过

180度旋转很容易做到。

你需要像这样翻转数组。

Original           Flipped rows      and Finally Flipped cols

[0][0 , 1, 2]      [2][0, 1, 2]    [2][2, 1, 0]

[1][0 , 1, 2]      [1][0, 1, 2]    [1][2, 1, 0]

[2][0 , 1, 2]      [0][0, 1, 2]    [0][2, 1, 0]

您只需翻转数组中另一个方向的行和列。