rotate-me-fast/pnm.cpp
Fabien Freling 7e152c29fc Add support for PGM format.
The code has been split into different source files.

This breaks for now rotation for tiled images and PPM format. The focus
is now on the PGM format.
2014-07-21 06:57:08 +02:00

87 lines
1.4 KiB
C++

#include <fstream>
#include <string>
#include <iostream>
#include "pnm.h"
using namespace std;
namespace pnm
{
bool read_header(std::ifstream& istr, Format& type, unsigned int& width, unsigned int& height)
{
// check magic
if (istr.get() != 'P' )
{
return false;
}
char c_type = static_cast<char>(istr.get());
if (c_type == '6')
{
type = Format::PPM;
}
else if (c_type == '5')
{
type = Format::PGM;
}
else
{
cerr << "Invalid PNM format." << endl;
return false;
}
if (istr.get() != '\n')
{
return false;
}
// skip comments
while (istr.peek() == '#')
{
std::string line;
std::getline(istr, line);
}
// get size
istr >> width >> height;
if (width == 0 || height == 0)
{
return false;
}
// get maxvalue
if (istr.get() != '\n')
{
return false;
}
int max_value = -1;
istr >> max_value;
if (max_value > 255)
{
return false;
}
if (istr.get() != '\n')
{
return false;
}
return true;
}
bool write_header(std::ofstream& ostr, Format type, unsigned int width, unsigned int height)
{
if (type == Format::PGM)
ostr << "P5" << endl;
if (type == Format::PPM)
ostr << "P6" << endl;
ostr << width << " " << height << endl;
ostr << "255" << endl;
return true;
}
} // end of namespace pnm