forked from vedantk/lcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpgm.cpp
More file actions
110 lines (87 loc) · 1.86 KB
/
Copy pathpgm.cpp
File metadata and controls
110 lines (87 loc) · 1.86 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
107
108
109
110
/*
* read/write access to 512x512 PGM files.
*
* Copyright (c) 2009 Vedant Kumar <vminch@gmail.com>
*/
#include "image.hpp"
static int PNMReaderGetChar(FILE* fp) {
static char c;
static int result;
if ((result = getc(fp)) == EOF) {
return '\0';
}
c = (char) result;
if (c == '#') {
do {
if ((result = getc(fp)) == EOF) {
return '\0';
}
c = (char) result;
} while (c != '\n');
}
return c;
}
static int PNMReaderGetInt(FILE* fp) {
char c;
int result = 0;
do {
c = PNMReaderGetChar(fp);
} while ((c < '1') || (c > '9'));
do {
result = result * 10 + (c - '0');
c = PNMReaderGetChar(fp);
} while ((c >= '0') && (c <= '9'));
ungetc(c, fp);
return result;
}
img* pgm_read(FILE* fptr) {
img* dat;
try {
dat = new img;
} catch (bad_alloc& err) {
img_err("*pgm", "OOM");
return NULL;
}
static char magic[3];
int i;
char c;
do {
c = PNMReaderGetChar(fptr);
} while (c != 'P');
magic[0] = c;
magic[1] = PNMReaderGetChar(fptr);
magic[2] = '\0';
i = PNMReaderGetInt(fptr); // rows
i = PNMReaderGetInt(fptr); // cols
i = PNMReaderGetInt(fptr); // max grayscale value
c = getc(fptr);
if (c == 0x0d) {
c = getc(fptr);
if (c != 0x0a) {
ungetc(c, fptr);
}
}
if (strncmp(magic, "P5", 2)) {
img_err("~*.pgm", "Unsupported PGM Binary.");
}
for (int j=0; j < 512; ++j) {
s_fread((char*) Buffer, 1, 512, fptr);
for (ushort i=0; i < 512; ++i) {
dat->pix[j][i] = Buffer[i];
// dat.hist[ Buffer[i] ] += 1;
}
}
fclose(fptr);
return dat;
}
bool pgm_write(img* dat, FILE* fptr) {
fprintf(fptr, "P5\n512 512\n255\n");
for (int j=0; j < 512; ++j) {
for (ushort i=0; i < 512; ++i) {
Buffer[i] = dat->pix[j][i];
}
fwrite((char*) Buffer, 1, 512, fptr);
}
fclose(fptr);
return true;
}