-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimg.cpp
More file actions
106 lines (80 loc) · 2.22 KB
/
img.cpp
File metadata and controls
106 lines (80 loc) · 2.22 KB
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
#include "img.hpp"
#include <fstream>
int pbm_write(std::vector<bool>& dat, int w, int h, const std::string& filename) {
if (dat.size() < w * h) return -1;
std::ofstream fp(filename, std::ios::out | std::ios::binary);
if (!fp) return -1;
fp << "P4\n" << w << ' ' << h << '\n';
uint8_t out_byte = 0;
int off = 0;
for (int i = 0; i < w * h; i++) {
out_byte |= static_cast<uint8_t>(dat[i]) << (7 - off);
off++;
//check if last bit of row
if (i % w == w - 1) off = 8;
//output byte
if (off >= 8) {
fp.write(reinterpret_cast<char*>(&out_byte), 1);
out_byte = 0;
off = 0;
}
}
fp.close();
return 0;
}
int pbm_read(std::vector<bool>& dat, int& w, int& h, const std::string& filename) {
std::ifstream fp(filename, std::ios::in | std::ios::binary);
if (!fp) return -1;
std::string magic;
fp >> magic;
if (magic != "P4") {
fp.close();
return -1;
}
fp >> w >> h;
fp.get();
dat.resize(w * h, false);
const int last_byte_size = w % 8 == 0 ? 8 : w % 8;
const int bytes_per_line = w / 8 + (last_byte_size != 8);
const int size = bytes_per_line * h;
int b_ind = 0;
for (int i = 0; i < size; i++) {
uint8_t in_byte;
fp.read(reinterpret_cast<char*>(&in_byte), 1);
const int s = (i % bytes_per_line == bytes_per_line - 1 ? last_byte_size : 8);
for (int j = 0; j < s; j++)
dat[b_ind++] = (in_byte >> (7 - j)) & 1;
}
fp.close();
return 0;
}
int pgm_write(std::vector<uint8_t>& dat, int w, int h, const std::string& filename) {
if (dat.size() < w * h) return -1;
std::ofstream fp(filename, std::ios::out | std::ios::binary);
if (!fp) return -1;
fp << "P5\n" << w << ' ' << h << " 255\n";
int off = 0;
for (int i = 0; i < w * h; i++)
fp.write(reinterpret_cast<char*>(&dat[i]), 1);
fp.close();
return 0;
}
int pgm_read(std::vector<uint8_t>& dat, int& w, int& h, const std::string& filename) {
std::ifstream fp(filename, std::ios::in | std::ios::binary);
if (!fp) return -1;
std::string magic;
fp >> magic;
if (magic != "P5") {
fp.close();
return -1;
}
int maxval;
fp >> w >> h >> maxval;
if (maxval != 255) return -1;
fp.get();
dat.resize(w * h, false);
for (int i = 0; i < w * h; i++)
fp.read(reinterpret_cast<char*>(&dat[i]), 1);
fp.close();
return 0;
}