c++ - 写入 PGM 文件

标签 c++ pgm

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

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

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

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

最佳答案

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

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

PGM 文件格式 header 为:

"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.

关于c++ - 写入 PGM 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10323921/

相关文章:

c++ - 如何将 boost::assign 与扩展 STL 容器的自定义容器一起使用?

c++ - 从大学计算机换到家里,为什么我得到的 FreeImage.h 没有这样的文件或目录?

c++ - system()并继承lxc功能

javascript - 如何以 html 格式显示 pgm/ppm 文件?

python - 在 PGM 格式文件中实现膨胀过滤器

pgm - 简单的原始二进制图像文件格式

c++ - 在 Windows XP 中使用 C++ 获取主音量

java - 读取 .pgm 图像时在 Java 和 Matlab 之间具有不同的值

java - 帮助将插件添加到 Java ImageWriter

c++ - 显示1到9的数字在二维数组中出现的次数