forked from cfeck/imagezero
-
Notifications
You must be signed in to change notification settings - Fork 11
/
portableimage.cpp
127 lines (112 loc) · 2.1 KB
/
portableimage.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
123
124
125
126
127
#include <imagezero/portableimage.h>
namespace IZ
{
static unsigned char* writeValue(unsigned char* p, unsigned char whiteSpace, int value)
{
unsigned int v = value;
*p++ = whiteSpace;
bool first = true;
unsigned int k = 10000;
while (k > 0)
{
if (v >= k || !first)
{
*p++ = '0' + v / k;
v %= k;
first = false;
}
k /= 10;
}
return p;
}
static const unsigned char* readValue(const unsigned char* p, int& value)
{
// skip white space
unsigned char c;
while (c = *p, true)
{
if (c == ' ' || (c >= '\011' && c <= '\015'))
{
++p;
}
else if (c == '#')
{
do
{
++p;
} while (*p != '\n');
}
else
{
break;
}
}
int v = 0;
unsigned int d;
while (d = *p - '0', d < 10U)
{
++p;
v = 10 * v + d;
}
value = v;
return p;
}
unsigned char* PortableImage::writeHeader(unsigned char* p)
{
*p++ = 'P';
switch (m_components)
{
case 3:
*p++ = '6';
break;
case 1:
*p++ = '5';
break;
default:
return p;
}
p = writeValue(p, '\n', m_width);
p = writeValue(p, ' ', m_height);
p = writeValue(p, '\n', 255);
setSamplesPerLine(m_components * m_width);
*p++ = '\n';
m_data = p;
return p;
}
bool PortableImage::readHeader(const unsigned char* p)
{
if (*p++ != 'P')
{
return false;
}
switch (*p++)
{
case '6':
m_components = 3;
break;
case '5':
m_components = 1;
break;
default:
return false;
}
p = readValue(p, m_width);
p = readValue(p, m_height);
p = readValue(p, m_maxVal);
if (m_maxVal != 255 || m_width < 1 || m_height < 1)
{
return false;
}
setSamplesPerLine(m_components * m_width);
++p; // skip single space
m_data = (unsigned char*) p;
return true;
}
PortableImage::PortableImage()
: m_components(0)
{
}
PortableImage::~PortableImage()
{
}
}