尝试用C++编写一个简单的PPM图像文件,代码如下:
#include <iostream>
const int image_height = 256, image_width = 256;
int main()
{
std::cout << "P3\n" << image_width << ' ' << image_height << "\n255\n";
for (int i = image_height - 1; 0 <= i; --i) {
for (int j = 0; j < image_width; ++j) {
int red = j; int green = i; int blue = 63;
std::cout << red << ' ' << green << ' ' << blue << '\n';
}
}
return 0;
}
我编译了它,然后将输出重定向到名为“image.ppm”的文件。我尝试用 GIMP 打开它,但失败了。它说这是一个无效文件。我的GIMP是最新版本,我检查过PPM文件格式;我写的看起来确实符合一般格式。那我做错了什么?
显然问题出在重定向上。我应该直接写入该文件,而不是将输出重定向到该文件。我想这与编码的魔力有关。