-
Notifications
You must be signed in to change notification settings - Fork 51
/
ppm.cpp
executable file
·122 lines (106 loc) · 2.99 KB
/
ppm.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <iostream>
#include <fstream>
#include <sstream>
#include <exception>
#include <string>
#include "ppm.h"
//init with default values
void ppm::init() {
width = 0;
height = 0;
max_col_val = 255;
}
//create a PPM object
ppm::ppm() {
init();
}
//create a PPM object and fill it with data stored in fname
ppm::ppm(const std::string &fname) {
init();
read(fname);
}
//create an "epmty" PPM image with a given width and height;the R,G,B arrays are filled with zeros
ppm::ppm(const unsigned int _width, const unsigned int _height) {
init();
width = _width;
height = _height;
nr_lines = height;
nr_columns = width;
size = width*height;
buff.resize(3*size);
// fill r, g and b with 0
r.resize(size);
g.resize(size);
b.resize(size);
}
//read the PPM image from fname
void ppm::read(const std::string &fname) {
std::ifstream inp(fname.c_str(), std::ios::in | std::ios::binary);
if (inp.is_open()) {
std::string line;
std::getline(inp, line);
if (line != "P6") {
std::cout << "Error. Unrecognized file format." << std::endl;
return;
}
std::getline(inp, line);
while (line[0] == '#') {
std::getline(inp, line);
}
std::stringstream dimensions(line);
try {
dimensions >> width;
dimensions >> height;
nr_lines = height;
nr_columns = width;
} catch (std::exception &e) {
std::cout << "Header file format error. " << e.what() << std::endl;
return;
}
std::getline(inp, line);
std::stringstream max_val(line);
try {
max_val >> max_col_val;
} catch (std::exception &e) {
std::cout << "Header file format error. " << e.what() << std::endl;
return;
}
size = width*height;
r.reserve(size);
g.reserve(size);
b.reserve(size);
char aux;
for (unsigned int i = 0; i < size; ++i) {
inp.read(&aux, 1);
r[i] = (unsigned char) aux;
inp.read(&aux, 1);
g[i] = (unsigned char) aux;
inp.read(&aux, 1);
b[i] = (unsigned char) aux;
}
} else {
std::cout << "Error. Unable to open " << fname << std::endl;
}
inp.close();
}
//write the PPM image in fname
void ppm::write(const std::string &fname) {
std::ofstream inp(fname.c_str(), std::ios::out | std::ios::binary);
if (inp.is_open()) {
inp << "P6\n";
inp << width;
inp << " ";
inp << height << "\n";
inp << max_col_val << "\n";
unsigned int ps = 0;
for (unsigned int i = 0; i < size; ++i) {
buff[ps] = (char) r[i]; ps++;
buff[ps] = (char) g[i]; ps++;
buff[ps] = (char) b[i]; ps++;
}
inp.write(&buff[0], 3*size);
} else {
std::cout << "Error. Unable to open " << fname << std::endl;
}
inp.close();
}