2
# The Python Imaging Library.
7
# See "PNG (Portable Network Graphics) Specification, version 1.0;
8
# W3C Recommendation", 1996-10-01, Thomas Boutell (ed.).
11
# 1996-05-06 fl Created (couldn't resist it)
12
# 1996-12-14 fl Upgraded, added read and verify support (0.2)
13
# 1996-12-15 fl Separate PNG stream parser
14
# 1996-12-29 fl Added write support, added getchunks
15
# 1996-12-30 fl Eliminated circular references in decoder (0.3)
16
# 1998-07-12 fl Read/write 16-bit images as mode I (0.4)
17
# 2001-02-08 fl Added transparency support (from Zircon) (0.5)
18
# 2001-04-16 fl Don't close data source in "open" method (0.6)
19
# 2004-02-24 fl Don't even pretend to support interlaced files (0.7)
20
# 2004-08-31 fl Do basic sanity check on chunk identifiers (0.8)
21
# 2004-09-20 fl Added PngInfo chunk container
22
# 2004-12-18 fl Added DPI read support (based on code by Niki Spahiev)
23
# 2008-08-13 fl Added tRNS support for RGB images
24
# 2009-03-06 fl Support for preserving ICC profiles (by Florian Hoech)
25
# 2009-03-08 fl Added zTXT support (from Lowell Alleman)
26
# 2009-03-29 fl Read interlaced PNG files (from Conrado Porto Lopes Gouvua)
28
# Copyright (c) 1997-2009 by Secret Labs AB
29
# Copyright (c) 1996 by Fredrik Lundh
31
# See the README file for information on usage and redistribution.
38
import Image, ImageFile, ImagePalette, zlib
42
return ord(c[1]) + (ord(c[0])<<8)
44
return ord(c[3]) + (ord(c[2])<<8) + (ord(c[1])<<16) + (ord(c[0])<<24)
46
is_cid = re.compile("\w\w\w\w").match
49
_MAGIC = "\211PNG\r\n\032\n"
53
# supported bits/color combinations, and corresponding modes/rawmodes
58
(16,0): ("I", "I;16B"),
59
(8, 2): ("RGB", "RGB"),
60
(16,2): ("RGB", "RGB;16B"),
66
(16,4): ("RGBA", "LA;16B"), # LA;16B->LA not yet available
67
(8, 6): ("RGBA", "RGBA"),
68
(16,6): ("RGBA", "RGBA;16B"),
72
# --------------------------------------------------------------------
73
# Support classes. Suitable for PNG and related formats like MNG etc.
77
def __init__(self, fp):
82
if not hasattr(Image.core, "crc32"):
83
self.crc = self.crc_skip
86
"Fetch a new chunk. Returns header information."
89
cid, pos, len = self.queue[-1]
99
raise SyntaxError, "broken PNG file (chunk %s)" % repr(cid)
104
self.queue = self.crc = self.fp = None
106
def push(self, cid, pos, len):
108
self.queue.append((cid, pos, len))
110
def call(self, cid, pos, len):
111
"Call the appropriate chunk handler"
114
print "STREAM", cid, pos, len
115
return getattr(self, "chunk_" + cid)(pos, len)
117
def crc(self, cid, data):
118
"Read and verify checksum"
120
crc1 = Image.core.crc32(data, Image.core.crc32(cid))
121
crc2 = i16(self.fp.read(2)), i16(self.fp.read(2))
123
raise SyntaxError, "broken PNG file"\
124
"(bad header checksum in %s)" % cid
126
def crc_skip(self, cid, data):
127
"Read checksum. Used if the C module is not present"
131
def verify(self, endchunk = "IEND"):
133
# Simple approach; just calculate checksum for all remaining
134
# blocks. Must be called directly after open.
139
cid, pos, len = self.read()
142
self.crc(cid, ImageFile._safe_read(self.fp, len))
148
# --------------------------------------------------------------------
149
# PNG chunk container (for use with save(pnginfo=))
156
def add(self, cid, data):
157
self.chunks.append((cid, data))
159
def add_text(self, key, value, zip=0):
162
self.add("zTXt", key + "\0\0" + zlib.compress(value))
164
self.add("tEXt", key + "\0" + value)
166
# --------------------------------------------------------------------
167
# PNG image stream (IHDR/IEND)
169
class PngStream(ChunkStream):
171
def __init__(self, fp):
173
ChunkStream.__init__(self, fp)
175
# local copies of Image attributes
181
self.im_palette = None
183
def chunk_iCCP(self, pos, len):
186
s = ImageFile._safe_read(self.fp, len)
187
# according to PNG spec, the iCCP chunk contains:
188
# Profile name 1-79 bytes (character string)
189
# Null separator 1 byte (null character)
190
# Compression method 1 byte (0)
191
# Compressed profile n bytes (zlib with deflate compression)
192
i = string.find(s, chr(0))
194
print "iCCP profile name", s[:i]
195
print "Compression method", ord(s[i])
196
comp_method = ord(s[i])
198
raise SyntaxError("Unknown compression method %s in iCCP chunk" % comp_method)
200
icc_profile = zlib.decompress(s[i+2:])
202
icc_profile = None # FIXME
203
self.im_info["icc_profile"] = icc_profile
206
def chunk_IHDR(self, pos, len):
209
s = ImageFile._safe_read(self.fp, len)
210
self.im_size = i32(s), i32(s[4:])
212
self.im_mode, self.im_rawmode = _MODES[(ord(s[8]), ord(s[9]))]
216
self.im_info["interlace"] = 1
218
raise SyntaxError, "unknown filter category"
221
def chunk_IDAT(self, pos, len):
224
self.im_tile = [("zip", (0,0)+self.im_size, pos, self.im_rawmode)]
228
def chunk_IEND(self, pos, len):
233
def chunk_PLTE(self, pos, len):
236
s = ImageFile._safe_read(self.fp, len)
237
if self.im_mode == "P":
238
self.im_palette = "RGB", s
241
def chunk_tRNS(self, pos, len):
244
s = ImageFile._safe_read(self.fp, len)
245
if self.im_mode == "P":
246
i = string.find(s, chr(0))
248
self.im_info["transparency"] = i
249
elif self.im_mode == "L":
250
self.im_info["transparency"] = i16(s)
251
elif self.im_mode == "RGB":
252
self.im_info["transparency"] = i16(s), i16(s[2:]), i16(s[4:])
255
def chunk_gAMA(self, pos, len):
258
s = ImageFile._safe_read(self.fp, len)
259
self.im_info["gamma"] = i32(s) / 100000.0
262
def chunk_pHYs(self, pos, len):
265
s = ImageFile._safe_read(self.fp, len)
266
px, py = i32(s), i32(s[4:])
268
if unit == 1: # meter
269
dpi = int(px * 0.0254 + 0.5), int(py * 0.0254 + 0.5)
270
self.im_info["dpi"] = dpi
272
self.im_info["aspect"] = px, py
275
def chunk_tEXt(self, pos, len):
278
s = ImageFile._safe_read(self.fp, len)
280
k, v = string.split(s, "\0", 1)
282
k = s; v = "" # fallback for broken tEXt tags
284
self.im_info[k] = self.im_text[k] = v
287
def chunk_zTXt(self, pos, len):
290
s = ImageFile._safe_read(self.fp, len)
291
k, v = string.split(s, "\0", 1)
292
comp_method = ord(v[0])
294
raise SyntaxError("Unknown compression method %s in zTXt chunk" % comp_method)
296
self.im_info[k] = self.im_text[k] = zlib.decompress(v[1:])
299
# --------------------------------------------------------------------
303
return prefix[:8] == _MAGIC
306
# Image plugin for PNG images.
308
class PngImageFile(ImageFile.ImageFile):
311
format_description = "Portable network graphics"
315
if self.fp.read(8) != _MAGIC:
316
raise SyntaxError, "not a PNG file"
319
# Parse headers up to the first IDAT chunk
321
self.png = PngStream(self.fp)
328
cid, pos, len = self.png.read()
331
s = self.png.call(cid, pos, len)
334
except AttributeError:
336
print cid, pos, len, "(unknown)"
337
s = ImageFile._safe_read(self.fp, len)
342
# Copy relevant attributes from the PngStream. An alternative
343
# would be to let the PngStream class modify these attributes
344
# directly, but that introduces circular references which are
345
# difficult to break if things go wrong in the decoder...
346
# (believe me, I've tried ;-)
348
self.mode = self.png.im_mode
349
self.size = self.png.im_size
350
self.info = self.png.im_info
351
self.text = self.png.im_text # experimental
352
self.tile = self.png.im_tile
354
if self.png.im_palette:
355
rawmode, data = self.png.im_palette
356
self.palette = ImagePalette.raw(rawmode, data)
358
self.__idat = len # used by load_read()
365
raise RuntimeError("verify must be called directly after open")
367
# back up to beginning of IDAT block
368
self.fp.seek(self.tile[0][2] - 8)
375
def load_prepare(self):
376
"internal: prepare to read PNG file"
378
if self.info.get("interlace"):
379
self.decoderconfig = self.decoderconfig + (1,)
381
ImageFile.ImageFile.load_prepare(self)
383
def load_read(self, bytes):
384
"internal: read more image data"
386
while self.__idat == 0:
387
# end of chunk, skip forward to next one
389
self.fp.read(4) # CRC
391
cid, pos, len = self.png.read()
393
if cid not in ["IDAT", "DDAT"]:
394
self.png.push(cid, pos, len)
397
self.__idat = len # empty chunks are allowed
399
# read more data from this chunk
403
bytes = min(bytes, self.__idat)
405
self.__idat = self.__idat - bytes
407
return self.fp.read(bytes)
411
"internal: finished reading image data"
417
# --------------------------------------------------------------------
421
return chr(i>>8&255) + chr(i&255)
424
return chr(i>>24&255) + chr(i>>16&255) + chr(i>>8&255) + chr(i&255)
427
# supported PIL modes, and corresponding rawmodes/bits/color combinations
428
"1": ("1", chr(1)+chr(0)),
429
"L;1": ("L;1", chr(1)+chr(0)),
430
"L;2": ("L;2", chr(2)+chr(0)),
431
"L;4": ("L;4", chr(4)+chr(0)),
432
"L": ("L", chr(8)+chr(0)),
433
"LA": ("LA", chr(8)+chr(4)),
434
"I": ("I;16B", chr(16)+chr(0)),
435
"P;1": ("P;1", chr(1)+chr(3)),
436
"P;2": ("P;2", chr(2)+chr(3)),
437
"P;4": ("P;4", chr(4)+chr(3)),
438
"P": ("P", chr(8)+chr(3)),
439
"RGB": ("RGB", chr(8)+chr(2)),
440
"RGBA":("RGBA", chr(8)+chr(6)),
443
def putchunk(fp, cid, *data):
444
"Write a PNG chunk (including CRC field)"
446
data = string.join(data, "")
448
fp.write(o32(len(data)) + cid)
450
hi, lo = Image.core.crc32(data, Image.core.crc32(cid))
451
fp.write(o16(hi) + o16(lo))
454
# wrap output from the encoder in IDAT chunks
456
def __init__(self, fp, chunk):
459
def write(self, data):
460
self.chunk(self.fp, "IDAT", data)
462
def _save(im, fp, filename, chunk=putchunk, check=0):
463
# save an image to disk (called by the save method)
470
# attempt to minimize storage requirements for palette images
472
if im.encoderinfo.has_key("bits"):
474
# number of bits specified by user
475
n = 1 << im.encoderinfo["bits"]
479
# check palette contents
492
mode = "%s;%d" % (mode, bits)
495
if im.encoderinfo.has_key("dictionary"):
496
dictionary = im.encoderinfo["dictionary"]
500
im.encoderconfig = (im.encoderinfo.has_key("optimize"), dictionary)
502
# get the corresponding PNG mode
504
rawmode, mode = _OUTMODES[mode]
506
raise IOError, "cannot write mode %s as PNG" % mode
512
# write minimal PNG file
517
o32(im.size[0]), o32(im.size[1]), # 0: size
518
mode, # 8: depth/type
519
chr(0), # 10: compression
520
chr(0), # 11: filter category
521
chr(0)) # 12: interlace flag
524
chunk(fp, "PLTE", im.im.getpalette("RGB"))
526
if im.encoderinfo.has_key("transparency"):
528
transparency = max(0, min(255, im.encoderinfo["transparency"]))
529
chunk(fp, "tRNS", chr(255) * transparency + chr(0))
531
transparency = max(0, min(65535, im.encoderinfo["transparency"]))
532
chunk(fp, "tRNS", o16(transparency))
533
elif im.mode == "RGB":
534
red, green, blue = im.encoderinfo["transparency"]
535
chunk(fp, "tRNS", o16(red) + o16(green) + o16(blue))
537
raise IOError("cannot use transparency for this mode")
540
# FIXME: to be supported some day
541
chunk(fp, "gAMA", o32(int(gamma * 100000.0)))
543
dpi = im.encoderinfo.get("dpi")
546
o32(int(dpi[0] / 0.0254 + 0.5)),
547
o32(int(dpi[1] / 0.0254 + 0.5)),
550
info = im.encoderinfo.get("pnginfo")
552
for cid, data in info.chunks:
555
# ICC profile writing support -- 2008-06-06 Florian Hoech
556
if im.info.has_key("icc_profile"):
558
# according to PNG spec, the iCCP chunk contains:
559
# Profile name 1-79 bytes (character string)
560
# Null separator 1 byte (null character)
561
# Compression method 1 byte (0)
562
# Compressed profile n bytes (zlib with deflate compression)
565
p = ICCProfile.ICCProfile(im.info["icc_profile"])
566
name = p.tags.desc.get("ASCII", p.tags.desc.get("Unicode", p.tags.desc.get("Macintosh", p.tags.desc.get("en", {}).get("US", "ICC Profile")))).encode("latin1", "replace")[:79]
569
data = name + "\0\0" + zlib.compress(im.info["icc_profile"])
570
chunk(fp, "iCCP", data)
572
ImageFile._save(im, _idat(fp, chunk), [("zip", (0,0)+im.size, 0, rawmode)])
574
chunk(fp, "IEND", "")
582
# --------------------------------------------------------------------
583
# PNG chunk converter
585
def getchunks(im, **params):
586
"""Return a list of PNG chunks representing this image."""
590
def write(self, data):
592
def append(self, chunk):
593
self.data.append(chunk)
595
def append(fp, cid, *data):
596
data = string.join(data, "")
597
hi, lo = Image.core.crc32(data, Image.core.crc32(cid))
598
crc = o16(hi) + o16(lo)
599
fp.append((cid, data, crc))
604
im.encoderinfo = params
605
_save(im, fp, None, append)
612
# --------------------------------------------------------------------
615
Image.register_open("PNG", PngImageFile, _accept)
616
Image.register_save("PNG", _save)
618
Image.register_extension("PNG", ".png")
620
Image.register_mime("PNG", "image/png")