代码之家  ›  专栏  ›  技术社区  ›  john01dav

我写netbpm映像的代码有什么问题?

  •  0
  • john01dav  · 技术社区  · 5 年前

    我目前正在研究一个需要输出生成图像的项目。我决定用灰度 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中打开此图像时,会出现各种错误:

    Non-specific error from Clion "Premature end of file" error from Gimp.

    文件保存时使用 pgm 延伸。我的代码有什么问题?

    1 回复  |  直到 5 年前
        1
  •  2
  •   Mark Setchell    5 年前

    尝试这样编写netpbm头:

    fout << "P5\n" << LENGTH << " " << LENGTH << "\n255\n";
    

    原因是大多数图像阅读器都会检查MaxVal,如果它小于等于255,则假定每像素8位。如果maxval超过255,则假定每个像素16位,因此它们会抱怨文件太短(因为它不提供每个像素2个字节)。