#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Image_pgm {
int w;
int h;
int *content;
public:
Image_pgm();
Image_pgm(int, int);
~Image_pgm();
int width() { return w; }
int height() { return h; }
int p_read(const char *);
int p_write(const char *);
int read_v(int y, int x, unsigned char *c) {
if (x >= 0 && x < w && y >= 0 && y < h) {
*c = content[y * this->w + x];
return 0;
} else
return 1;
}
int write_v(int y, int x, unsigned char c) {
if (x >= 0 && x < w && y >= 0 && y < h) {
content[y * this->w + x] = c;
return 0;
} else
return 1;
}
};
Image_pgm::Image_pgm() {
w = h = 0;
content = 0;
}
Image_pgm::Image_pgm(int w, int h) {
this->w = w;
this->h = h;
this->content = new int[w * h];
}
Image_pgm::~Image_pgm() {
delete [] content;
}
const int cbuffsize = 1024;
int Image_pgm::p_read(const char *path) {
ifstream f;
f.open(path);
if (!f) {
cerr << "cannot open the file: " << path << '.' << endl;
return -1;
}
char *p, *p1, *p2, cbuff[cbuffsize];
int count = 0, max = 255;
int y = 0;
f.getline(cbuff, cbuffsize);
if (strstr(cbuff, "P2") != cbuff) {
cerr << "cannot find pgm header." << endl;
return -1;
}
while (f.getline(cbuff, cbuffsize)) {
if (cbuff[0] == '#')
continue;
count++;
if (count == 1) {
if ((p1 = strtok(cbuff, " ,")) == 0) goto error_handler;
if ((p2 = strtok(cbuff, " ,")) == 0) goto error_handler;
this->w = atoi(p1);
this->h = atoi(p2);
this->content = new int[this->w * this->h];
} else if (count == 2) {
if ((p1 = strtok(cbuff, " ,")) == 0) goto error_handler;
max = atoi(p1);
} else {
for (int i = 0; i < this->w; i++) {
content[y * this->w + i] = (int)((double)atoi(strtok((i == 0) ? cbuff : 0, " ,")) / max * 255.0);
}
y++;
if (y > h) goto error_handler;
}
}
f.close();
return 0;
error_handler:
cerr << "bad format." << endl;
f.close();
return -1;
}
int Image_pgm::p_write(const char *path) {
ofstream f(path);
if (!f) {
cerr << "cannot open the file: " << path << endl;
return -1;
}
f << "P2" << endl;
f << w << " " << h << endl;
for (int y = 0; y < this->h; y++) {
for (int x = 0; x < this->w; x++) {
f << content[y * this->w + x];
f << " ";
}
f << endl;
}
return 0;
}
int main() {
Image_pgm sample1;
sample1.p_read("a.pgm");
int wid, hei;
wid = sample1.width();
hei = sample1.height();
Image_pgm sample2(wid, hei);
for(int i = 0; i < hei; i++) {
for(int j = 0; j < wid; j++) {
unsigned char value;
sample1.read_v(i, j, &value);
sample2.write_v(i, j, value);
}
}
sample2.p_write("b.pgm");
return 0;
}
/* end */