【问题标题】:Writing to PGM file写入 PGM 文件
【发布时间】:2012-05-06 15:00:05
【问题描述】:

我正在尝试使用此代码编写一个 pgm 文件..

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

如果我尝试将其写入 .txt 文件,它已经写入了字符表示。

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

【问题讨论】:

标签: c++ pgm


【解决方案1】:

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

此外,如果您希望与 Windows(以及可能来自 Microsoft 的任何其他操作系统)兼容,您必须以二进制模式打开文件。微软默认以文本模式打开文件,这通常有一个没人想要的不兼容特性(ancient-DOS-backward-compatibility):它将每个“\n”替换为“\r\n”。

PGM文件格式头是:

"P5"                           + at least one whitespace (\n, \r, \t, space)
width (ascii decimal)          + at least one whitespace (\n, \r, \t, space) 
height (ascii decimal)         + at least one whitespace (\n, \r, \t, space) 
max gray value (ascii decimal) + EXACTLY ONE whitespace (\n, \r, \t, space) 

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

#include <fstream>
const unsigned char* bitmap[MAXHEIGHT] = …;// pointers to each pixel row
{
    std::ofstream f("test.pgm",std::ios_base::out
                              |std::ios_base::binary
                              |std::ios_base::trunc
                   );

    int maxColorValue = 255;
    f << "P5\n" << width << " " << height << "\n" << maxColorValue << "\n";
    // std::endl == "\n" + std::flush
    // we do not want std::flush here.

    for(int i=0;i<height;++i)
        f.write( reinterpret_cast<const char*>(bitmap[i]), width );

    if(wannaFlush)
        f << std::flush;
} // block scope closes file, which flushes anyway.

【讨论】:

    【解决方案2】:

    确保使用ios::binary 标志以二进制模式打开文件。如果您使用的是 Windows,则可能需要将您的 endls 替换为 "\r\n"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多