1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
|
#include <iostream>
#include <cassert>
#include <cstdlib>
#include <fstream>
using namespace std;
const int MAXWIDTH = 512;
const int MAXHEIGHT = 512;
// reads a PGM file.
// Notice that: width and height are passed by reference!
void readImage(int image[][MAXHEIGHT], int &width, int &height) {
char c;
int x;
ifstream instr;
instr.open("city.pgm");
cout << "This is running " << endl;
// read the header P2
instr >> c; assert(c == 'P');
instr >> c; assert(c == '2');
// skip the comments (if any)
while ((instr>>ws).peek() == '#') { instr.ignore(4096, '\n'); }
instr >> width;
instr >> height;
assert(width <= MAXWIDTH);
assert(height <= MAXHEIGHT);
int max;
instr >> max;
assert(max == 255);
for (int row = 0; row < height; row++)
for (int col = 0; col < width; col++)
instr >> image[col][row];
instr.close();
return;
}
// Writes a PGM file
void writeImage(int image[][MAXHEIGHT], int width, int height) {
ofstream ostr;
ostr.open("outImage.pgm");
if (ostr.fail()) {
cout << "Unable to write file\n";
exit(1);
};
// print the header
ostr << "P2" << endl;
// width, height
ostr << width << ' ';
ostr << height << endl;
ostr << 255 << endl;
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
assert(image[col][row] < 256);
assert(image[col][row] >= 0);
ostr << image[col][row] << ' ';
// lines should be no longer than 70 characters
if ((col+1)%16 == 0) ostr << endl;
}
ostr << endl;
}
ostr.close();
return;
}
int main ()
{
int image[MAXWIDTH][MAXHEIGHT], width, height, t1, t2;
readImage (image, width, height);
writeImage (image, width, height);
return 0;
}
|