我目前正在研究一个需要输出生成图像的项目。我决定用灰度
netbpm format
因为它很简单。其中一张图片是一张高度图。我要导出的代码如下:
#include <array>
#include <fstream>
#include <iostream>
int main(){
constexpr unsigned LENGTH = 4;
std::array<double, LENGTH*LENGTH> m_data = {
0, 0, 0, 0,
0, 1, 1, 0,
0, 1, 1, 0,
0, 0, 0, 0
};
std::ofstream fout;
fout.exceptions(std::ios::badbit | std::ios::failbit);
fout.open("test.pgm", std::ios::binary);
fout << "P5 " << LENGTH << " " << LENGTH << "\n256\n";
for(unsigned i=0;i<LENGTH*LENGTH;++i){
unsigned char brightness = m_data[i]*255;
std::cout << m_data[i] << std::endl;
fout.write(reinterpret_cast<char*>(&brightness), sizeof(unsigned char));
}
return 0;
}
阅读后,这个代码对我来说是正确的
the specification for the netbpm format on Wikipedia
. 但是,当我尝试在gimp或clion中打开此图像时,会出现各种错误:
文件保存时使用
pgm
延伸。我的代码有什么问题?