写入 PGM 文件

Jam*_*ton 2 c++ pgm

我正在尝试使用此代码编写 pgm 文件。

myfile << "P5" << endl;
 myfile << sizeColumn << " " << sizeRow << endl;
 myfile << Q << endl;
 myfile.write( reinterpret_cast<char *>(image), (sizeRow*sizeColumn)*sizeof(unsigned char));
Run Code Online (Sandbox Code Playgroud)

如果我尝试将其写入 .txt 文件,它会写入字符表示形式。

如何将我的值写入 pgm 文件以便它们正确显示?有谁有任何链接,因为我找不到太多!

com*_*nad 5

您可能不想使用std::endl,因为它会刷新输出流。

\n\n

此外,如果您想要与 Windows(可能还包括 Microsoft 的任何其他操作系统)兼容,则必须以二进制模式打开该文件。微软默认以文本模式打开文件,这通常具有不兼容功能(古老的 DOS 向后兼容性),没有人想要了:它将每个“\\n”替换为“\\r\\n”。

\n\n

PGM 文件格式标头为:

\n\n
"P5"                           + at least one whitespace (\\n, \\r, \\t, space)\nwidth (ascii decimal)          + at least one whitespace (\\n, \\r, \\t, space) \nheight (ascii decimal)         + at least one whitespace (\\n, \\r, \\t, space) \nmax gray value (ascii decimal) + EXACTLY ONE whitespace (\\n, \\r, \\t, space) \n
Run Code Online (Sandbox Code Playgroud)\n\n

这是将 pgm 输出到文件的示例:

\n\n
#include <fstream>\nconst unsigned char* bitmap[MAXHEIGHT] = \xe2\x80\xa6;// pointers to each pixel row\n{\n    std::ofstream f("test.pgm",std::ios_base::out\n                              |std::ios_base::binary\n                              |std::ios_base::trunc\n                   );\n\n    int maxColorValue = 255;\n    f << "P5\\n" << width << " " << height << "\\n" << maxColorValue << "\\n";\n    // std::endl == "\\n" + std::flush\n    // we do not want std::flush here.\n\n    for(int i=0;i<height;++i)\n        f.write( reinterpret_cast<const char*>(bitmap[i]), width );\n\n    if(wannaFlush)\n        f << std::flush;\n} // block scope closes file, which flushes anyway.\n
Run Code Online (Sandbox Code Playgroud)\n