首页 > 解决方案 > 在 C++ 中旋转 PNG 图像

问题描述

我对 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] = 
    }
}
}

再次感谢。

标签: c++arraysimagerotationpng

解决方案


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

让我们看看位置的像素(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++专家,所以我希望我没有语法错误,我从不检查,所以要小心数组超出索引,我可能会错过


推荐阅读