-
Notifications
You must be signed in to change notification settings - Fork 9
/
pngcanvas.py
366 lines (305 loc) · 12.1 KB
/
pngcanvas.py
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
"""Simple PNG Canvas for Python - updated for bytearray()"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
__version__ = "1.0.3"
__license__ = "MIT"
import struct
import sys
import zlib
# Py2 - Py3 compatibility
if sys.version < '3':
range = xrange # NOQA
# Color types: see table 6.1 "PNG image types and colour types"
COLOR_TYPE_GRAYSCALE = 0
COLOR_TYPE_TRUECOLOR = 2
COLOR_TYPE_INDEXED_COLOR = 3
COLOR_TYPE_GRAYSCALE_WITH_ALPHA = 4
COLOR_TYPE_TRUECOLOR_WITH_ALPHA = 6
SIGNATURE = struct.pack(b"8B", 137, 80, 78, 71, 13, 10, 26, 10)
def force_int(*args):
return tuple(int(x) for x in args)
def blend(c1, c2):
"""Alpha blends two colors, using the alpha given by c2"""
return [c1[i] * (0xFF - c2[3]) + c2[i] * c2[3] >> 8 for i in range(3)]
def intensity(c, i):
"""Compute a new alpha given a 0-0xFF intensity"""
return [c[0], c[1], c[2], (c[3] * i) >> 8]
def grayscale(c):
"""Compute perceptive grayscale value"""
return int(c[0] * 0.3 + c[1] * 0.59 + c[2] * 0.11)
def gradient_list(start, end, steps):
"""Compute gradient colors"""
delta = [end[i] - start[i] for i in range(4)]
return [bytearray(start[j] + (delta[j] * i) // steps for j in range(4))
for i in range(steps + 1)]
def rgb2rgba(rgb):
"""Take a row of RGB bytes, and convert to a row of RGBA bytes."""
rgba = []
for i in range(0, len(rgb), 3):
rgba += rgb[i:i+3]
rgba.append(255)
return rgba
class ByteReader(object):
def __init__(self, chunks):
self.chunks = chunks
self.decoded = b''
self.decompressor = zlib.decompressobj()
def read(self, num_bytes):
"""Read `num_bytes` from the compressed data chunks.
Data is returned as `bytes` of length `num_bytes`
Will raise an EOFError if data is unavailable.
Note: Will always return `num_bytes` of data (unlike the file read method).
"""
while len(self.decoded) < num_bytes:
try:
tag, data = next(self.chunks)
except StopIteration:
raise EOFError()
if tag != b'IDAT':
continue
self.decoded += self.decompressor.decompress(data)
r = self.decoded[:num_bytes]
self.decoded = self.decoded[num_bytes:]
return r
class PNGCanvas(object):
def __init__(self, width, height,
bgcolor=(0xff, 0xff, 0xff, 0xff),
color=(0, 0, 0, 0xff)):
self.width = width
self.height = height
self.color = bytearray(color) # rgba
self.bgcolor = bytearray(bgcolor)
self.canvas = bytearray(self.bgcolor * width * height)
def _offset(self, x, y):
"""Helper for internal data"""
x, y = force_int(x, y)
return y * self.width * 4 + x * 4
def point(self, x, y, color=None):
"""Set a pixel"""
if x < 0 or y < 0 or x > self.width - 1 or y > self.height - 1:
return
if color is None:
color = self.color
o = self._offset(x, y)
self.canvas[o:o + 3] = blend(self.canvas[o:o + 3], bytearray(color))
@staticmethod
def rect_helper(x0, y0, x1, y1):
"""Rectangle helper"""
x0, y0, x1, y1 = force_int(x0, y0, x1, y1)
if x0 > x1:
x0, x1 = x1, x0
if y0 > y1:
y0, y1 = y1, y0
return x0, y0, x1, y1
def vertical_gradient(self, x0, y0, x1, y1, start, end):
"""Draw a vertical gradient"""
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
grad = gradient_list(start, end, y1 - y0)
for x in range(x0, x1 + 1):
for y in range(y0, y1 + 1):
self.point(x, y, grad[y - y0])
def rectangle(self, x0, y0, x1, y1):
"""Draw a rectangle"""
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
self.polyline([[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0]])
def filled_rectangle(self, x0, y0, x1, y1):
"""Draw a filled rectangle"""
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
for x in range(x0, x1 + 1):
for y in range(y0, y1 + 1):
self.point(x, y, self.color)
def copy_rect(self, x0, y0, x1, y1, dx, dy, destination):
"""Copy (blit) a rectangle onto another part of the image"""
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
dx, dy = force_int(dx, dy)
for x in range(x0, x1 + 1):
for y in range(y0, y1 + 1):
d = destination._offset(dx + x - x0, dy + y - y0)
o = self._offset(x, y)
destination.canvas[d:d + 4] = self.canvas[o:o + 4]
def blend_rect(self, x0, y0, x1, y1, dx, dy, destination, alpha=0xff):
"""Blend a rectangle onto the image"""
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
for x in range(x0, x1 + 1):
for y in range(y0, y1 + 1):
o = self._offset(x, y)
rgba = self.canvas[o:o + 4]
rgba[3] = alpha
destination.point(dx + x - x0, dy + y - y0, rgba)
def line(self, x0, y0, x1, y1):
"""Draw a line using Xiaolin Wu's antialiasing technique"""
# clean params
x0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1)
if y0 > y1:
y0, y1, x0, x1 = y1, y0, x1, x0
dx = x1 - x0
if dx < 0:
sx = -1
else:
sx = 1
dx *= sx
dy = y1 - y0
# 'easy' cases
if dy == 0:
for x in range(x0, x1, sx):
self.point(x, y0)
return
if dx == 0:
for y in range(y0, y1):
self.point(x0, y)
self.point(x1, y1)
return
if dx == dy:
for x in range(x0, x1, sx):
self.point(x, y0)
y0 += 1
return
# main loop
self.point(x0, y0)
e_acc = 0
if dy > dx: # vertical displacement
e = (dx << 16) // dy
for i in range(y0, y1 - 1):
e_acc_temp, e_acc = e_acc, (e_acc + e) & 0xFFFF
if e_acc <= e_acc_temp:
x0 += sx
w = 0xFF-(e_acc >> 8)
self.point(x0, y0, intensity(self.color, w))
y0 += 1
self.point(x0 + sx, y0, intensity(self.color, (0xFF - w)))
self.point(x1, y1)
return
# horizontal displacement
e = (dy << 16) // dx
for i in range(x0, x1 - sx, sx):
e_acc_temp, e_acc = e_acc, (e_acc + e) & 0xFFFF
if e_acc <= e_acc_temp:
y0 += 1
w = 0xFF-(e_acc >> 8)
self.point(x0, y0, intensity(self.color, w))
x0 += sx
self.point(x0, y0 + 1, intensity(self.color, (0xFF-w)))
self.point(x1, y1)
def polyline(self, arr):
"""Draw a set of lines"""
for i in range(0, len(arr) - 1):
self.line(arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1])
def dump(self):
"""Dump the image data"""
scan_lines = bytearray()
for y in range(self.height):
scan_lines.append(0) # filter type 0 (None)
scan_lines.extend(
self.canvas[(y * self.width * 4):((y + 1) * self.width * 4)]
)
# image represented as RGBA tuples, no interlacing
return SIGNATURE + \
self.pack_chunk(b'IHDR', struct.pack(b"!2I5B",
self.width, self.height,
8, 6, 0, 0, 0)) + \
self.pack_chunk(b'IDAT', zlib.compress(bytes(scan_lines), 9)) + \
self.pack_chunk(b'IEND', b'')
@staticmethod
def pack_chunk(tag, data):
"""Pack a PNG chunk for serializing to disk"""
to_check = tag + data
return (struct.pack(b"!I", len(data)) + to_check +
struct.pack(b"!I", zlib.crc32(to_check) & 0xFFFFFFFF))
def load(self, f):
"""Load a PNG image"""
SUPPORTED_COLOR_TYPES = (COLOR_TYPE_TRUECOLOR, COLOR_TYPE_TRUECOLOR_WITH_ALPHA)
SAMPLES_PER_PIXEL = { COLOR_TYPE_TRUECOLOR: 3,
COLOR_TYPE_TRUECOLOR_WITH_ALPHA: 4 }
assert f.read(8) == SIGNATURE
chunks = iter(self.chunks(f))
header = next(chunks)
assert header[0] == b'IHDR'
(width, height, bit_depth, color_type, compression,
filter_type, interlace) = struct.unpack(b"!2I5B", header[1])
if bit_depth != 8:
raise ValueError('Unsupported PNG format (bit depth={}; must be 8)'.format(bit_depth))
if compression != 0:
raise ValueError('Unsupported PNG format (compression={}; must be 0)'.format(compression))
if filter_type != 0:
raise ValueError('Unsupported PNG format (filter_type={}; must be 0)'.format(filter_type))
if interlace != 0:
raise ValueError('Unsupported PNG format (interlace={}; must be 0)'.format(interlace))
if color_type not in SUPPORTED_COLOR_TYPES:
raise ValueError('Unsupported PNG format (color_type={}; must one of {})'.format(SUPPORTED_COLOR_TYPES))
self.width = width
self.height = height
self.canvas = bytearray(self.bgcolor * width * height)
bytes_per_pixel = SAMPLES_PER_PIXEL[color_type]
bytes_per_row = bytes_per_pixel * width
bytes_per_rgba_row = SAMPLES_PER_PIXEL[COLOR_TYPE_TRUECOLOR_WITH_ALPHA] * width
bytes_per_scanline = bytes_per_row + 1
# Python 2 requires the encode for struct.unpack
scanline_fmt = ('!%dB' % bytes_per_scanline).encode('ascii')
reader = ByteReader(chunks)
old_row = None
cursor = 0
for row in range(height):
scanline = reader.read(bytes_per_scanline)
unpacked = list(struct.unpack(scanline_fmt, scanline))
old_row = self.defilter(unpacked[1:], old_row, unpacked[0], bpp=bytes_per_pixel)
rgba_row = old_row if color_type == COLOR_TYPE_TRUECOLOR_WITH_ALPHA else rgb2rgba(old_row)
self.canvas[cursor:cursor + bytes_per_rgba_row] = rgba_row
cursor += bytes_per_rgba_row
@staticmethod
def defilter(cur, prev, filter_type, bpp=4):
"""Decode a chunk"""
if filter_type == 0: # No filter
return cur
elif filter_type == 1: # Sub
xp = 0
for xc in range(bpp, len(cur)):
cur[xc] = (cur[xc] + cur[xp]) % 256
xp += 1
elif filter_type == 2: # Up
for xc in range(len(cur)):
cur[xc] = (cur[xc] + prev[xc]) % 256
elif filter_type == 3: # Average
xp = 0
for i in range(bpp):
cur[i] = (cur[i] + prev[i] // 2) % 256
for xc in range(bpp, len(cur)):
cur[xc] = (cur[xc] + ((cur[xp] + prev[xc]) // 2)) % 256
xp += 1
elif filter_type == 4: # Paeth
xp = 0
for i in range(bpp):
cur[i] = (cur[i] + prev[i]) % 256
for xc in range(bpp, len(cur)):
a = cur[xp]
b = prev[xc]
c = prev[xp]
p = a + b - c
pa = abs(p - a)
pb = abs(p - b)
pc = abs(p - c)
if pa <= pb and pa <= pc:
value = a
elif pb <= pc:
value = b
else:
value = c
cur[xc] = (cur[xc] + value) % 256
xp += 1
else:
raise ValueError('Unrecognized scanline filter type: {}'.format(filter_type))
return cur
@staticmethod
def chunks(f):
"""Split read PNG image data into chunks"""
while 1:
try:
length = struct.unpack(b"!I", f.read(4))[0]
tag = f.read(4)
data = f.read(length)
crc = struct.unpack(b"!I", f.read(4))[0]
except struct.error:
return
if zlib.crc32(tag + data) & 0xFFFFFFFF != crc:
raise IOError('Checksum fail')
yield tag, data