I am trying to write a pgm file using this code..
myfile << "P5" << endl;
myfile << sizeColumn << " " << sizeRow << endl;
myfile << Q << endl;
myfile.write( reinterpret_cast<char *>(image), (sizeRow*sizeColumn)*sizeof(unsigned char));
If I try to write this to a .txt file, it has written the char representation.
How can I write my values to a pgm file so they display properly? Does anyone have any links as I cannot find much on it!
You might not want to use std::endl, because it flushes the output stream.
Additionaly, if you want compatibility to Windows (and probably any other OS from Microsoft), you have to open the file in binary mode. Microsoft opens files in text mode by default, which usually has an incompatibility-feature (ancient-DOS-backward-compatibility) no one wants anymore: It replaces every "\n" with "\r\n".
The PGM file format header is:
"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)
This is an example to output a pgm to file:
#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.