-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileHelper.cpp
86 lines (78 loc) · 2.39 KB
/
fileHelper.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
#include <iostream>
#include <fstream>
using namespace std;
/**
* Reads in the ppm file
*
* @param filename Name of the input file
* @param img pointer to data of image
* @param width pointer to width of image
* @param height pointer to height of image
* @return image data or nullptr if an error occurs
*/
unsigned char* read(char filename[], int *width, int *height) {
ifstream input(filename, ios::in);
if(input.is_open()) {
string format;
input >> format;
// TEST: File format check
if (format != "P3") {
cerr << "Error: Input file has to be a P3 file (ASCII)" << endl;
cerr << "File Format: " << format << endl;
input.close();
return nullptr;
}
// Read Header
int max;
input >> *width >> *height >> max;
//Read data
cout << "Reading image " << filename << "( width: " << *width << " | height: " << *height << " )" << endl;
size_t size = (*width) * (*height) * 3; // 3 = RGB
auto img = new unsigned char[size];
unsigned int colorCode;
for (int i=0; i < size; i++) {
input >> colorCode;
img[i] = (char) colorCode;
}
input.close();
return img;
}
else {
cerr << "Error: Unable to open " << filename << endl;
return nullptr;
}
}
/**
* Writes the ppm file
*
* @param filename Name of the output file
* @param img pointer to data of image
* @param width pointer to width of image
* @param height pointer to height of image
*/
void write(char filename[], unsigned char *img, int width, int height) {
ofstream output(filename, ios::out);
if(output.is_open()) {
// Write Header
char format[3] = "P3";
output << format << endl
<< width << " " << height << endl
<< 255 << endl;
//Write data
unsigned int colorCode;
cout << "Writing image " << filename << endl;
for (int r=0; r < height; r++) {
for (int c=0; c < width; c++) {
for (int rgb=0; rgb < 3; rgb++) {
colorCode = (unsigned) img[(r*width*3 + c*3) + rgb];
output << colorCode << " ";
}
}
output << endl;
}
output.close();
}
else {
cerr << "Error: Unable to write " << filename << endl;
}
}