-
Notifications
You must be signed in to change notification settings - Fork 1
/
image.cpp
executable file
·93 lines (83 loc) · 2.55 KB
/
image.cpp
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
84
85
86
87
88
89
90
91
92
#include <cstring>
#include "image.h"
// ====================================================================================
bool Image::Save(const std::string &filename) const {
int len = filename.length();
if (!(len > 4 && filename.substr(len-4) == std::string(".ppm"))) {
std::cerr << "ERROR: This is not a PPM filename: " << filename << std::endl;
return false;
}
FILE *file = fopen(filename.c_str(), "wb");
if (file == NULL) {
std::cerr << "Unable to open " << filename << " for writing\n";
return false;
}
// misc header information
fprintf (file, "P6\n");
fprintf (file, "%d %d\n", width,height);
fprintf (file, "255\n");
// the data
// flip y so that (0,0) is bottom left corner
for (int y = height-1; y >= 0; y--) {
for (int x=0; x<width; x++) {
Color v = GetPixel(x,y);
fputc ((unsigned char)(v.r),file);
fputc ((unsigned char)(v.g),file);
fputc ((unsigned char)(v.b),file);
}
}
fclose(file);
return true;
}
// ====================================================================================
bool Image::Load(const std::string &filename) {
int len = filename.length();
if (!(len > 4 && filename.substr(len-4) == std::string(".ppm"))) {
std::cerr << "ERROR: This is not a PPM filename: " << filename << std::endl;
return false;
}
FILE *file = fopen(filename.c_str(),"rb");
if (file == NULL) {
std::cerr << "Unable to open " << filename << " for reading\n";
return false;
}
// misc header information
char tmp[100];
fgets(tmp,100,file);
assert (strstr(tmp,"P6"));
fgets(tmp,100,file);
while (tmp[0] == '#') { fgets(tmp,100,file); }
sscanf(tmp,"%d %d",&width,&height);
fgets(tmp,100,file);
assert (strstr(tmp,"255"));
// the data
delete [] data;
data = new Color[height*width];
// flip y so that (0,0) is bottom left corner
for (int y = height-1; y >= 0; y--) {
for (int x = 0; x < width; x++) {
Color c;
c.r = fgetc(file);
c.g = fgetc(file);
c.b = fgetc(file);
SetPixel(x,y,c);
}
}
fclose(file);
return true;
}
unsigned char* Image::getGLPixelData() {
delete [] gl_data;
gl_data = new unsigned char[width*height*3];
for (int x=0; x<width; x++) {
for (int y=0; y<height; y++) {
Color v = GetPixel(x,y);
gl_data[y*width*3+x*3+0] = v.r;
gl_data[y*width*3+x*3+1] = v.g;
gl_data[y*width*3+x*3+2] = v.b;
}
}
return gl_data;
}
// ====================================================================
// ====================================================================