-
Notifications
You must be signed in to change notification settings - Fork 4
/
png.py
3114 lines (2701 loc) · 114 KB
/
png.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# encoding=utf-8
#
# png.py - PNG encoder/decoder in pure Python
#
# Copyright (C) 2015 Pavel Zlatovratskii <[email protected]>
# Copyright (C) 2006 Johann C. Rocholl <[email protected]>
# Portions Copyright (C) 2009 David Jones <[email protected]>
# And probably portions Copyright (C) 2006 Nicko van Someren <[email protected]>
#
# Original concept by Johann C. Rocholl.
#
# LICENCE (MIT)
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Pure Python PNG Reader/Writer
This Python module implements support for PNG images (see PNG
specification at http://www.w3.org/TR/2003/REC-PNG-20031110/ ). It reads
and writes PNG files with all allowable bit depths
(1/2/4/8/16/24/32/48/64 bits per pixel) and colour combinations:
greyscale (1/2/4/8/16 bit); RGB, RGBA, LA (greyscale with alpha) with
8/16 bits per channel; colour mapped images (1/2/4/8 bit).
Adam7 interlacing is supported for reading and
writing. A number of optional chunks can be specified (when writing)
and understood (when reading): ``tRNS``, ``bKGD``, ``gAMA``.
For help, type ``import png; help(png)`` in your python interpreter.
A good place to start is the :class:`Reader` and :class:`Writer`
classes.
Requires Python 2.3. Best with Python 2.6 and higher. Installation is
trivial, but see the ``README.txt`` file (with the source distribution)
for details.
A note on spelling and terminology
----------------------------------
Generally British English spelling is used in the documentation. So
that's "greyscale" and "colour". This not only matches the author's
native language, it's also used by the PNG specification.
The major colour models supported by PNG (and hence by this module) are:
greyscale, RGB, greyscale--alpha, RGB--alpha. These are sometimes
referred to using the abbreviations: L, RGB, LA, RGBA. In this case
each letter abbreviates a single channel: *L* is for Luminance or Luma
or Lightness which is the channel used in greyscale images; *R*, *G*,
*B* stand for Red, Green, Blue, the components of a colour image; *A*
stands for Alpha, the opacity channel (used for transparency effects,
but higher values are more opaque, so it makes sense to call it
opacity).
A note on formats
-----------------
When getting pixel data out of this module (reading) and presenting
data to this module (writing) there are a number of ways the data could
be represented as a Python value. Generally this module uses one of
three formats called "flat row flat pixel", "boxed row flat pixel", and
"boxed row boxed pixel". Basically the concern is whether each pixel
and each row comes in its own little tuple (box), or not.
Consider an image that is 3 pixels wide by 2 pixels high, and each pixel
has RGB components:
Boxed row flat pixel::
iter([R,G,B, R,G,B, R,G,B],
[R,G,B, R,G,B, R,G,B])
Each row appears as its own sequence, but the pixels are flattened so
that three values for one pixel simply follow the three values for
the previous pixel. This is the most common format used, because it
provides a good compromise between space and convenience.
Row sequence supposed to be compatible with 'buffer' protocol in
addition to standard sequence methods so 'buffer()' can be used to
get fast per-byte access.
All rows are contained in iterable or iterable-compatible container.
(use 'iter()' to ensure)
Flat row flat pixel::
[R,G,B, R,G,B, R,G,B,
R,G,B, R,G,B, R,G,B]
The entire image is one single giant sequence of colour values.
Generally an array will be used (to save space), not a list.
Boxed row boxed pixel::
list([ (R,G,B), (R,G,B), (R,G,B) ],
[ (R,G,B), (R,G,B), (R,G,B) ])
Each row appears in its own list, but each pixel also appears in its own
tuple. A serious memory burn in Python.
In all cases the top row comes first, and for each row the pixels are
ordered from left-to-right. Within a pixel the values appear in the
order, R-G-B-A (or L-A for greyscale--alpha).
There is a fourth format, mentioned because it is used internally,
is close to what lies inside a PNG file itself, and has some support
from the public API. This format is called packed. When packed,
each row is a sequence of bytes (integers from 0 to 255), just as
it is before PNG scanline filtering is applied. When the bit depth
is 8 this is essentially the same as boxed row flat pixel; when the
bit depth is less than 8, several pixels are packed into each byte;
when the bit depth is 16 (the only value more than 8 that is supported
by the PNG image format) each pixel value is decomposed into 2 bytes
(and `packed` is a misnomer). This format is used by the
:meth:`Writer.write_packed` method. It isn't usually a convenient
format, but may be just right if the source data for the PNG image
comes from something that uses a similar format (for example, 1-bit
BMPs, or another PNG file).
And now, my famous members
--------------------------
"""
from array import array
import itertools
import logging
import math
# http://www.python.org/doc/2.4.4/lib/module-operator.html
import operator
import datetime
import time
import struct
import sys
import zlib
# http://www.python.org/doc/2.4.4/lib/module-warnings.html
import warnings
try:
from functools import reduce
except ImportError:
# suppose to get there on python<2.7 where reduce is only built-in function
pass
try:
from itertools import imap as map
except ImportError:
# On Python 3 there is no imap, but map works like imap instead
pass
__version__ = "0.3.0"
__all__ = ['png_signature', 'Image', 'Reader', 'Writer',
'Error', 'FormatError', 'ChunkError',
'Filter', 'register_extra_filter',
'write_chunks', 'from_array', 'parse_mode', 'MergedPlanes',
'PERCEPTUAL', 'RELATIVE_COLORIMETRIC', 'SATURATION',
'ABSOLUTE_COLORIMETRIC']
# The PNG signature.
# http://www.w3.org/TR/PNG/#5PNG-file-signature
png_signature = struct.pack('8B', 137, 80, 78, 71, 13, 10, 26, 10)
_adam7 = ((0, 0, 8, 8),
(4, 0, 8, 8),
(0, 4, 4, 8),
(2, 0, 4, 4),
(0, 2, 2, 4),
(1, 0, 2, 2),
(0, 1, 1, 2))
# registered keywords
# http://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords
_registered_kw = ('Title', 'Author', 'Description', 'Copyright', 'Software',
'Disclaimer', 'Warning', 'Source', 'Comment',
'Creation Time')
# rendering intent
PERCEPTUAL = 0
RELATIVE_COLORIMETRIC = 1
SATURATION = 2
ABSOLUTE_COLORIMETRIC = 3
def group(s, n):
"""Repack iterator items into groups"""
# See http://www.python.org/doc/2.6/library/functions.html#zip
return list(zip(*[iter(s)] * n))
def _rel_import(module, tgt):
"""Using relative import in both Python 2 and Python 3"""
try:
exec("from ." + module + " import " + tgt, globals(), locals())
except SyntaxError:
# On Python < 2.5 relative import cause syntax error
exec("from " + module + " import " + tgt, globals(), locals())
except (ValueError, SystemError):
# relative import in non-package, try absolute
exec("from " + module + " import " + tgt, globals(), locals())
return eval(tgt)
try:
next
except NameError:
def next(it):
"""trivial `next` emulation"""
return it.next()
try:
bytes
except NameError:
bytes = str
# Define a bytearray_to_bytes() function.
# The definition of this function changes according to what
# version of Python we are on.
def bytearray_to_bytes(src):
"""Default version"""
return bytes(src)
def newHarray(length=0):
"""fast init by length"""
return array('H', [0]) * length
# bytearray is faster than array('B'), so we prefer to use it
# where available.
try:
# bytearray exists (>= Python 2.6).
newBarray = bytearray
copyBarray = bytearray
except NameError:
# bytearray does not exist. We're probably < Python 2.6 (the
# version in which bytearray appears).
def bytearray(src=tuple()):
"""Bytearray-like array"""
return array('B', src)
def newBarray(length=0):
"""fast init by length"""
return array('B', [0]) * length
if hasattr(array, '__copy__'):
# a bit faster if possible
copyBarray = array.__copy__
else:
copyBarray = bytearray
def bytearray_to_bytes(row):
"""
Convert bytearray to bytes.
Recal that `row` will actually be an ``array``.
"""
return row.tostring()
try:
from itertools import tee
except ImportError:
def tee(iterable, n=2):
"""Return n independent iterators from a single iterable."""
it = iter(iterable)
deques = [list() for _ in range(n)]
def gen(mydeque):
while True:
if not mydeque: # when the local deque is empty
newval = next(it) # fetch a new value and
for d in deques: # load it to all the deques
d.append(newval)
yield mydeque.pop(0)
return tuple(map(gen, deques))
# Python 3 workaround
try:
basestring
except NameError:
basestring = str
# Conditionally convert to bytes. Works on Python 2 and Python 3.
try:
bytes('', 'ascii')
def strtobytes(x): return bytes(x, 'iso8859-1') # noqa
def bytestostr(x): return str(x, 'iso8859-1') # noqa
except (NameError, TypeError):
# We get NameError when bytes() does not exist (most Python
# 2.x versions), and TypeError when bytes() exists but is on
# Python 2.x (when it is an alias for str() and takes at most
# one argument).
strtobytes = str
bytestostr = str
zerobyte = strtobytes(chr(0))
try:
set
except NameError:
from sets import Set as set
def peekiter(iterable):
"""Return first row and also iterable with same items as original"""
it = iter(iterable)
one = next(it)
def gen():
"""Generator that returns first and proxy other items from source"""
yield one
while True:
yield next(it)
return (one, gen())
def check_palette(palette):
"""
Check a palette argument (to the :class:`Writer` class) for validity.
Returns the palette as a list if okay; raises an exception otherwise.
"""
# None is the default and is allowed.
if palette is None:
return None
p = list(palette)
if not (0 < len(p) <= 256):
raise ValueError("a palette must have between 1 and 256 entries")
seen_triple = False
for i,t in enumerate(p):
if len(t) not in (3,4):
raise ValueError(
"palette entry %d: entries must be 3- or 4-tuples." % i)
if len(t) == 3:
seen_triple = True
if seen_triple and len(t) == 4:
raise ValueError(
"palette entry %d: all 4-tuples must precede all 3-tuples" % i)
for x in t:
if int(x) != x or not(0 <= x <= 255):
raise ValueError(
"palette entry %d: values must be integer: 0 <= x <= 255" % i)
return p
def check_sizes(size, width, height):
"""
Check that these arguments, in supplied, are consistent.
Return a (width, height) pair.
"""
if not size:
return width, height
if len(size) != 2:
raise ValueError(
"size argument should be a pair (width, height)")
if width is not None and width != size[0]:
raise ValueError(
"size[0] (%r) and width (%r) should match when both are used."
% (size[0], width))
if height is not None and height != size[1]:
raise ValueError(
"size[1] (%r) and height (%r) should match when both are used."
% (size[1], height))
return size
def check_color(c, greyscale, which):
"""
Checks that a colour argument is the right form.
Returns the colour
(which, if it's a bar integer, is "corrected" to a 1-tuple).
For transparent or background options.
"""
if c is None:
return c
if greyscale:
try:
len(c)
except TypeError:
c = (c,)
if len(c) != 1:
raise ValueError("%s for greyscale must be 1-tuple" %
which)
if not isinteger(c[0]):
raise ValueError(
"%s colour for greyscale must be integer" % which)
else:
if not (len(c) == 3 and
isinteger(c[0]) and
isinteger(c[1]) and
isinteger(c[2])):
raise ValueError(
"%s colour must be a triple of integers" % which)
return c
def check_time(value):
"""Convert time from most popular representations to datetime"""
if value is None:
return None
if isinstance(value, (time.struct_time, tuple)):
return value
if isinstance(value, datetime.datetime):
return value.timetuple()
if isinstance(value, datetime.date):
res = datetime.datetime.utcnow()
res.replace(year=value.year, month=value.month, day=value.day)
return res.timetuple()
if isinstance(value, datetime.time):
return datetime.datetime.combine(datetime.date.today(),
value).timetuple()
if isinteger(value):
# Handle integer as timestamp
return time.gmtime(value)
if isinstance(value, basestring):
if value.lower() == 'now':
return time.gmtime()
# TODO: parsinng some popular strings
raise ValueError("Unsupported time representation:" + repr(value))
def popdict(src, keys):
"""
Extract all keys (with values) from `src` dictionary as new dictionary
values are removed from source dictionary.
"""
new = {}
for key in keys:
if key in src:
new[key] = src.pop(key)
return new
def try_greyscale(pixels, alpha=False, dirty_alpha=True):
"""
Check if flatboxed RGB `pixels` could be converted to greyscale
If could - return iterator with greyscale pixels,
otherwise return `False` constant
"""
planes = 3 + bool(alpha)
res = list()
apix = list()
for row in pixels:
green = row[1::planes]
if alpha:
apix.append(row[4:planes])
if (green != row[0::planes] or green != row[2::planes]):
return False
else:
res.append(green)
if alpha:
return MergedPlanes(res, 1, apix, 1)
else:
return res
class Error(Exception):
"""Generic PurePNG error"""
def __str__(self):
return self.__class__.__name__ + ': ' + ' '.join(self.args)
class FormatError(Error):
"""
Problem with input file format.
In other words, PNG file does
not conform to the specification in some way and is invalid.
"""
class ChunkError(FormatError):
"""Error in chunk handling"""
class BaseFilter(object):
"""
Basic methods of filtering and other byte manipulations
This part can be compile with Cython (see README.cython)
Private methods are declared as 'cdef' (unavailable from python)
for this compilation, so don't just rename it.
"""
def __init__(self, bitdepth=8):
if bitdepth > 8:
self.fu = bitdepth // 8
else:
self.fu = 1
def __undo_filter_sub(self, scanline):
"""Undo sub filter."""
ai = 0
# Loops starts at index fu.
for i in range(self.fu, len(scanline)):
x = scanline[i]
a = scanline[ai] # result
scanline[i] = (x + a) & 0xff # result
ai += 1
def __do_filter_sub(self, scanline, result):
"""Sub filter."""
ai = 0
for i in range(self.fu, len(result)):
x = scanline[i]
a = scanline[ai]
result[i] = (x - a) & 0xff
ai += 1
def __undo_filter_up(self, scanline):
"""Undo up filter."""
previous = self.prev
for i in range(len(scanline)):
x = scanline[i]
b = previous[i]
scanline[i] = (x + b) & 0xff # result
def __do_filter_up(self, scanline, result):
"""Up filter."""
previous = self.prev
for i in range(len(result)):
x = scanline[i]
b = previous[i]
result[i] = (x - b) & 0xff
def __undo_filter_average(self, scanline):
"""Undo average filter."""
ai = -self.fu
previous = self.prev
for i in range(len(scanline)):
x = scanline[i]
if ai < 0:
a = 0
else:
a = scanline[ai] # result
b = previous[i]
scanline[i] = (x + ((a + b) >> 1)) & 0xff # result
ai += 1
def __do_filter_average(self, scanline, result):
"""Average filter."""
ai = -self.fu
previous = self.prev
for i in range(len(result)):
x = scanline[i]
if ai < 0:
a = 0
else:
a = scanline[ai]
b = previous[i]
result[i] = (x - ((a + b) >> 1)) & 0xff
ai += 1
def __undo_filter_paeth(self, scanline):
"""Undo Paeth filter."""
ai = -self.fu
previous = self.prev
for i in range(len(scanline)):
x = scanline[i]
if ai < 0:
pr = previous[i] # a = c = 0
else:
a = scanline[ai] # result
c = previous[ai]
b = previous[i]
pa = abs(b - c) # b
pb = abs(a - c) # 0
pc = abs(a + b - c - c) # b
if pa <= pb and pa <= pc: # False
pr = a
elif pb <= pc: # True
pr = b
else:
pr = c
scanline[i] = (x + pr) & 0xff # result
ai += 1
def __do_filter_paeth(self, scanline, result):
"""Paeth filter."""
# http://www.w3.org/TR/PNG/#9Filter-type-4-Paeth
ai = -self.fu
previous = self.prev
for i in range(len(result)):
x = scanline[i]
if ai < 0:
pr = previous[i] # a = c = 0
else:
a = scanline[ai]
c = previous[ai]
b = previous[i]
pa = abs(b - c)
pb = abs(a - c)
pc = abs(a + b - c - c)
if pa <= pb and pa <= pc:
pr = a
elif pb <= pc:
pr = b
else:
pr = c
result[i] = (x - pr) & 0xff
ai += 1
def undo_filter(self, filter_type, line):
"""
Undo the filter for a scanline.
`scanline` is a sequence of bytes that does not include
the initial filter type byte.
The scanline will have the effects of filtering removed.
Scanline modified inplace and also returned as result.
"""
assert 0 <= filter_type <= 4
# For the first line of a pass, synthesize a dummy previous line.
if self.prev is None:
self.prev = newBarray(len(line))
# Also it's possible to switch some filters to easier
if filter_type == 2: # "up"
filter_type = 0
elif filter_type == 4: # "paeth"
filter_type = 1
# Call appropriate filter algorithm.
# 0 - do nothing
if filter_type == 1:
self.__undo_filter_sub(line)
elif filter_type == 2:
self.__undo_filter_up(line)
elif filter_type == 3:
self.__undo_filter_average(line)
elif filter_type == 4:
self.__undo_filter_paeth(line)
# This will not work writing cython attributes from python
# Only 'cython from cython' or 'python from python'
self.prev[:] = line[:]
return line
def _filter_scanline(self, filter_type, line, result):
"""
Apply a scanline filter to a scanline.
`filter_type` specifies the filter type (0 to 4)
'line` specifies the current (unfiltered) scanline as a sequence
of bytes;
"""
assert 0 <= filter_type < 5
if self.prev is None:
# We're on the first line. Some of the filters can be reduced
# to simpler cases which makes handling the line "off the top"
# of the image simpler. "up" becomes "none"; "paeth" becomes
# "left" (non-trivial, but true). "average" needs to be handled
# specially.
if filter_type == 2: # "up"
filter_type = 0
elif filter_type == 3:
self.prev = newBarray(len(line))
elif filter_type == 4: # "paeth"
filter_type = 1
if filter_type == 1:
self.__do_filter_sub(line, result)
elif filter_type == 2:
self.__do_filter_up(line, result)
elif filter_type == 3:
self.__do_filter_average(line, result)
elif filter_type == 4:
self.__do_filter_paeth(line, result)
# Todo: color conversion functions should be moved
# to a separate part in future
def convert_la_to_rgba(self, row, result):
"""Convert a grayscale image with alpha to RGBA."""
for i in range(len(row) // 3):
for j in range(3):
result[(4 * i) + j] = row[2 * i]
result[(4 * i) + 3] = row[(2 * i) + 1]
def convert_l_to_rgba(self, row, result):
"""
Convert a grayscale image to RGBA.
This method assumes the alpha channel in result is already
correctly initialized.
"""
for i in range(len(row) // 3):
for j in range(3):
result[(4 * i) + j] = row[i]
def convert_rgb_to_rgba(self, row, result):
"""
Convert an RGB image to RGBA.
This method assumes the alpha channel in result is already
correctly initialized.
"""
for i in range(len(row) // 3):
for j in range(3):
result[(4 * i) + j] = row[(3 * i) + j]
iBaseFilter = BaseFilter # 'i' means 'internal'
try:
BaseFilter = _rel_import('pngfilters', 'BaseFilter')
except:
# Whatever happens we could use internal part
if not(sys.exc_info()[0] is ImportError):
logging.error("Error during import of compiled filters!")
logging.error(sys.exc_info()[1])
logging.error("Fallback to pure python mode!")
BaseFilter = iBaseFilter
class Writer(object):
"""PNG encoder in pure Python."""
def __init__(self, width=None, height=None,
greyscale=False,
alpha=False,
bitdepth=8,
palette=None,
transparent=None,
background=None,
gamma=None,
compression=None,
interlace=False,
chunk_limit=2 ** 20,
icc_profile=None,
**kwargs
):
"""
Create a PNG encoder object.
Arguments:
width, height
Image size in pixels, as two separate arguments.
greyscale
Input data is greyscale, not RGB.
alpha
Input data has alpha channel (RGBA or LA).
bitdepth
Bit depth: from 1 to 16.
palette
Create a palette for a colour mapped image (colour type 3).
transparent
Specify a transparent colour (create a ``tRNS`` chunk).
background
Specify a default background colour (create a ``bKGD`` chunk).
gamma
Specify a gamma value (create a ``gAMA`` chunk).
compression
zlib compression level: 0 (none) to 9 (more compressed);
default: -1 or None.
interlace
Create an interlaced image.
chunk_limit
Write multiple ``IDAT`` chunks to save memory.
icc_profile
tuple of (`name`, `databytes`) or just data bytes
to write ICC Profile
Extra keywords:
text
see :meth:`set_text`
modification_time
see :meth:`set_modification_time`
resolution
see :meth:`set_resolution`
filter_type
Enable and specify PNG filter
see :meth:`set_filter_type`
The image size (in pixels) can be specified either by using the
`width` and `height` arguments, or with the single `size`
argument. If `size` is used it should be a pair (*width*,
*height*).
`greyscale` and `alpha` are booleans that specify whether
an image is greyscale (or colour), and whether it has an
alpha channel (or not).
`bitdepth` specifies the bit depth of the source pixel values.
Each source pixel value must be an integer between 0 and
``2**bitdepth-1``. For example, 8-bit images have values
between 0 and 255. PNG only stores images with bit depths of
1,2,4,8, or 16. When `bitdepth` is not one of these values,
the next highest valid bit depth is selected, and an ``sBIT``
(significant bits) chunk is generated that specifies the
original precision of the source image. In this case the
supplied pixel values will be rescaled to fit the range of
the selected bit depth.
The details of which bit depth / colour model combinations the
PNG file format supports directly, are somewhat arcane
(refer to the PNG specification for full details). Briefly:
"small" bit depths (1,2,4) are only allowed with greyscale and
colour mapped images; colour mapped images cannot have bit depth
16.
For colour mapped images (in other words, when the `palette`
argument is specified) the `bitdepth` argument must match one of
the valid PNG bit depths: 1, 2, 4, or 8. (It is valid to have a
PNG image with a palette and an ``sBIT`` chunk, but the meaning
is slightly different; it would be awkward to press the
`bitdepth` argument into service for this.)
The `palette` option, when specified, causes a colour mapped image
to be created: the PNG colour type is set to 3; `greyscale` must not
be set; `alpha` must not be set; `transparent` must not be set;
the bit depth must be 1, 2, 4, or 8.
When a colour mapped image is created, the pixel values
are palette indexes and the `bitdepth` argument specifies the size
of these indexes (not the size of the colour values in the palette).
The palette argument value should be a sequence of 3- or
4-tuples. 3-tuples specify RGB palette entries; 4-tuples
specify RGBA palette entries. If both 4-tuples and 3-tuples
appear in the sequence then all the 4-tuples must come
before all the 3-tuples. A ``PLTE`` chunk is created; if there
are 4-tuples then a ``tRNS`` chunk is created as well. The
``PLTE`` chunk will contain all the RGB triples in the same
sequence; the ``tRNS`` chunk will contain the alpha channel for
all the 4-tuples, in the same sequence. Palette entries
are always 8-bit.
If specified, the `transparent` and `background` parameters must
be a tuple with three integer values for red, green, blue, or
a simple integer (or singleton tuple) for a greyscale image.
If specified, the `gamma` parameter must be a positive number
(generally, a `float`). A ``gAMA`` chunk will be created.
Note that this will not change the values of the pixels as
they appear in the PNG file, they are assumed to have already
been converted appropriately for the gamma specified.
The `compression` argument specifies the compression level to
be used by the ``zlib`` module. Values from 1 to 9 specify
compression, with 9 being "more compressed" (usually smaller
and slower, but it doesn't always work out that way). 0 means
no compression. -1 and ``None`` both mean that the default
level of compession will be picked by the ``zlib`` module
(which is generally acceptable).
If `interlace` is true then an interlaced image is created
(using PNG's so far only interace method, *Adam7*). This does
not affect how the pixels should be presented to the encoder,
rather it changes how they are arranged into the PNG file.
On slow connexions interlaced images can be partially decoded
by the browser to give a rough view of the image that is
successively refined as more image data appears.
.. note ::
Enabling the `interlace` option requires the entire image
to be processed in working memory.
`chunk_limit` is used to limit the amount of memory used whilst
compressing the image. In order to avoid using large amounts of
memory, multiple ``IDAT`` chunks may be created.
"""
width, height = check_sizes(kwargs.pop('size', None),
width, height)
if width <= 0 or height <= 0:
raise ValueError("width and height must be greater than zero")
if not isinteger(width) or not isinteger(height):
raise ValueError("width and height must be integers")
# http://www.w3.org/TR/PNG/#7Integers-and-byte-order
if width > 2**32-1 or height > 2**32-1:
raise ValueError("width and height cannot exceed 2**32-1")
if alpha and transparent is not None:
raise ValueError(
"transparent colour not allowed with alpha channel")
if 'bytes_per_sample' in kwargs and not bitdepth:
warnings.warn('please use bitdepth instead of bytes_per_sample',
DeprecationWarning)
if kwargs['bytes_per_sample'] not in (0.125, 0.25, 0.5, 1, 2):
raise ValueError(
"bytes per sample must be .125, .25, .5, 1, or 2")
bitdepth = int(8 * kwargs.pop('bytes_per_sample'))
if 'resolution' not in kwargs and 'physical' in kwargs:
kwargs['resolution'] = kwargs.pop('physical')
warnings.warn('please use resolution instead of physilcal',
DeprecationWarning)
if not isinteger(bitdepth) or bitdepth < 1 or 16 < bitdepth:
raise ValueError("bitdepth (%r) must be a postive integer <= 16" %
bitdepth)
self.pixbitdepth = bitdepth
self.palette = check_palette(palette)
if self.palette:
if bitdepth not in (1, 2, 4, 8):
raise ValueError("with palette bitdepth must be 1, 2, 4, or 8")
if transparent is not None:
raise ValueError("transparent and palette not compatible")
if alpha:
raise ValueError("alpha and palette not compatible")
if greyscale:
if greyscale == 'try':
greyscale = False
raise ValueError("greyscale and palette not compatible")
self.transparent = check_color(transparent, greyscale, 'transparent')
self.background = check_color(background, greyscale, 'background')
# At the moment the `planes` argument is ignored;
# its purpose is to act as a dummy so that
# ``Writer(x, y, **info)`` works, where `info` is a dictionary
# returned by Reader.read and friends.
# Ditto for `colormap` and `maxval`.
popdict(kwargs, ('planes', 'colormap', 'maxval'))
for ex_kw in ('filter_type', 'text', 'resolution', 'modification_time',
'rendering_intent', 'white_point', 'rgb_points'):
getattr(self, 'set_' + ex_kw)(kwargs.pop(ex_kw, None))
# Keyword text support
kw_text = popdict(kwargs, _registered_kw)
if kw_text:
kw_text.update(self.text)
self.set_text(kw_text)
if kwargs:
warnings.warn("Unknown writer args: " + str(kwargs))
# It's important that the true boolean values (greyscale, alpha,
# colormap, interlace) are converted to bool because Iverson's
# convention is relied upon later on.
self.width = width
self.height = height
self.gamma = gamma
if icc_profile:
if 'icc_profile_name' in kwargs:
warnings.warn("Use tuple (`name`, `data`) to provide"
" ICC Profile name", DeprecationWarning)
self.set_icc_profile(icc_profile, kwargs['icc_profile_name'])
else:
self.set_icc_profile(icc_profile)
else:
self.icc_profile = None
if greyscale == 'try':
self.greyscale = 'try'
else:
self.greyscale = bool(greyscale)
self.alpha = bool(alpha)
self.bitdepth = int(bitdepth)
self.compression = compression
self.chunk_limit = chunk_limit
self.interlace = bool(interlace)
if bool(self.palette) and (self.greyscale or self.alpha):
raise FormatError("Paletted image could not be grayscale or"
" contain alpha plane")
self.planes = (3, 1)[(self.greyscale and self.greyscale != 'try') or
bool(self.palette)] + self.alpha
def set_icc_profile(self, profile=None, name='ICC Profile'):
"""
Add ICC Profile.
Prefered way is tuple (`profile_name`, `profile_bytes`), but only
bytes with name as separate argument is also supported.
"""
if isinstance(profile, (basestring, bytes)):
icc_profile = [name, profile]