1 #include "stdafx.h"
2
3 #include "Image.hxx"
4
5 void eatComments(FILE *f)
6 {
7 int ch;
8
9 while((ch=getc(f))=='#') {
10 char str[1000];
11 fgets(str,1000,f);
12 }
13 ungetc(ch,f);
14 };
15
16 void eatWhitespace(FILE *f)
17 {
18 int ch=getc(f);
19
20 while(ch==' ' || ch=='\t' || ch=='\n' || ch=='\f' || ch=='\r')
21 ch=getc(f);
22
23 ungetc(ch,f);
24 };
25
26 void Image::ReadPPM(char *fileName)
27 {
28 std::cout << "reading PPM image " << fileName << std::endl;
29
30 FILE *f;
31 char ch;
32 int width, height, colres;
33
34 f = fopen(fileName,"r");
35 if (f == NULL) {
36 std::cerr << "could not open file " << fileName << std::endl;
37 exit(1);
38 }
39
40 char str[1000];
41
42 eatWhitespace(f);
43 eatComments(f);
44 eatWhitespace(f);
45 fscanf(f,"%s",str);
46
47 if (!strcmp(str,"P3")) {
48 eatWhitespace(f);
49 eatComments(f);
50 eatWhitespace(f);
51
52 fscanf(f,"%d %d",&width,&height);
53 if(width<=0 || height<=0) {
54 std::cerr << "width and height of the image are not greater than zero in file " << fileName << std::endl;
55 exit(1);
56 }
57
58 cout << "Image Res: " << width << " " << height << endl;
59
60 resX = width;
61 resY = height;
62
63 delete [] pixel;
64 pixel = new Vec3f[resX*resY];
65
66 eatWhitespace(f);
67 eatComments(f);
68 eatWhitespace(f);
69 fscanf(f,"%d",&colres);
70
71 ch=0;
72 while(ch!='\n')
73 fscanf(f,"%c",&ch);
74
75 for (int y=resY-1;y>=0;y--)
76 for (int x=0;x<resX;x++) {
77 int c[3];
78 fscanf(f,"%d %d %d",c+0,c+1,c+2);
79 (*this)[y][x] = Vec3f(c[0] / float(colres),
80 c[1] / float(colres),
81 c[2] / float(colres));
82 }
83
84 fclose(f);
85 } else {
86 std::cerr << "wrong format of file " << fileName<< std::endl;
87 exit(1);
88 }
89 };
90
91 void Image::WritePPM(char *fileName)
92 {
93 std::ofstream file(fileName);
94 file << "P3" << std::endl;
95 file << resX << " " << resY << " " << 255 << std::endl;
96 for (int y=resY-1;y>=0;y--) {
97 for (int x=0;x<resX;x++)
98 file
99 << (int)(255.99999999 * (*this)[y][x].x) << " "
100 << (int)(255.99999999 * (*this)[y][x].y) << " "
101 << (int)(255.99999999 * (*this)[y][x].z) << " "
102 << "\t";
103 file << std::endl;
104 file << std::flush;
105 };
106 };
syntax highlighted by Code2HTML, v. 0.9.1