首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正在写入PGM文件

正在写入PGM文件
EN

Stack Overflow用户
提问于 2012-04-26 05:15:37
回答 2查看 9.2K关注 0票数 1

我正在尝试用下面的代码写一个pgm文件。

代码语言:javascript
复制
myfile << "P5" << endl;
 myfile << sizeColumn << " " << sizeRow << endl;
 myfile << Q << endl;
 myfile.write( reinterpret_cast<char *>(image), (sizeRow*sizeColumn)*sizeof(unsigned char));

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

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-26 07:30:50

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

另外,如果你想兼容Windows (可能还有微软的任何其他操作系统),你必须以二进制模式打开文件。默认情况下,Microsoft以文本模式打开文件,这通常具有一个不兼容的功能(古老的DOS向后兼容),没有人再需要它:它将每个"\n“替换为"\r\n”。

PGM文件格式标题为:

代码语言:javascript
复制
"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输出到文件的示例:

代码语言:javascript
复制
#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.
票数 4
EN

Stack Overflow用户

发布于 2012-04-26 05:27:06

确保使用ios::binary标志以二进制模式打开文件。如果你使用的是Windows,你可能想用"\r\n"替换你的endl%s。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10323921

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档