NovaBryan/EVE_Dump
Log | Files | 📦 下载最新源码 (.zip) | Refs | README

png.py (98056B)


      1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\carbon\common\lib\png.py
      2 from __future__ import generators
      3 __version__ = '$URL: http://pypng.googlecode.com/svn/trunk/code/png.py $ $Rev: 228 $'
      4 from array import array
      5 try:
      6     import itertools
      7 except:
      8     pass
      9 
     10 import math
     11 import operator
     12 import struct
     13 import sys
     14 import zlib
     15 import warnings
     16 __all__ = ['Image',
     17  'Reader',
     18  'Writer',
     19  'write_chunks',
     20  'from_array',
     21  'crop']
     22 _signature = struct.pack('8B', 137, 80, 78, 71, 13, 10, 26, 10)
     23 _adam7 = ((0,
     24   0,
     25   8,
     26   8),
     27  (4,
     28   0,
     29   8,
     30   8),
     31  (0,
     32   4,
     33   4,
     34   8),
     35  (2,
     36   0,
     37   4,
     38   4),
     39  (0,
     40   2,
     41   2,
     42   4),
     43  (1,
     44   0,
     45   2,
     46   2),
     47  (0,
     48   1,
     49   1,
     50   2))
     51 
     52 def group(s, n):
     53     return zip(*([iter(s)] * n))
     54 
     55 
     56 def isarray(x):
     57     try:
     58         return isinstance(x, array)
     59     except:
     60         return False
     61 
     62 
     63 try:
     64     array.tostring
     65 except:
     66 
     67     def tostring(row):
     68         l = len(row)
     69         return struct.pack(('%dB' % l), *row)
     70 
     71 
     72 else:
     73 
     74     def tostring(row):
     75         return row.tostring()
     76 
     77 
     78 try:
     79     bytes('', 'ascii')
     80 
     81     def strtobytes(x):
     82         return bytes(x, 'iso8859-1')
     83 
     84 
     85     def bytestostr(x):
     86         return str(x, 'iso8859-1')
     87 
     88 
     89 except:
     90     strtobytes = str
     91     bytestostr = str
     92 
     93 def interleave_planes(ipixels, apixels, ipsize, apsize):
     94     itotal = len(ipixels)
     95     atotal = len(apixels)
     96     newtotal = itotal + atotal
     97     newpsize = ipsize + apsize
     98     out = array(ipixels.typecode)
     99     out.extend(ipixels)
    100     out.extend(apixels)
    101     for i in range(ipsize):
    102         out[i:newtotal:newpsize] = ipixels[i:itotal:ipsize]
    103 
    104     for i in range(apsize):
    105         out[i + ipsize:newtotal:newpsize] = apixels[i:atotal:apsize]
    106 
    107     return out
    108 
    109 
    110 def check_palette(palette):
    111     if palette is None:
    112         return
    113     p = list(palette)
    114     if not 0 < len(p) <= 256:
    115         raise ValueError('a palette must have between 1 and 256 entries')
    116     seen_triple = False
    117     for i, t in enumerate(p):
    118         if len(t) not in (3, 4):
    119             raise ValueError('palette entry %d: entries must be 3- or 4-tuples.' % i)
    120         if len(t) == 3:
    121             seen_triple = True
    122         if seen_triple and len(t) == 4:
    123             raise ValueError('palette entry %d: all 4-tuples must precede all 3-tuples' % i)
    124         for x in t:
    125             if int(x) != x or not 0 <= x <= 255:
    126                 raise ValueError('palette entry %d: values must be integer: 0 <= x <= 255' % i)
    127 
    128     return p
    129 
    130 
    131 class Error(Exception):
    132     prefix = 'Error'
    133 
    134     def __str__(self):
    135         return self.prefix + ': ' + ' '.join(self.args)
    136 
    137 
    138 class FormatError(Error):
    139     prefix = 'FormatError'
    140 
    141 
    142 class ChunkError(FormatError):
    143     prefix = 'ChunkError'
    144 
    145 
    146 class Writer():
    147 
    148     def __init__(self, width = None, height = None, size = None, greyscale = False, alpha = False, bitdepth = 8, palette = None, transparent = None, background = None, gamma = None, compression = None, interlace = False, bytes_per_sample = None, planes = None, colormap = None, maxval = None, chunk_limit = 2 ** 20):
    149 
    150         def isinteger(x):
    151             try:
    152                 return int(x) == x
    153             except:
    154                 return False
    155 
    156         def check_color(c, which):
    157             if c is None:
    158                 return c
    159             if greyscale:
    160                 try:
    161                     l = len(c)
    162                 except TypeError:
    163                     c = (c,)
    164 
    165                 if len(c) != 1:
    166                     raise ValueError('%s for greyscale must be 1-tuple' % which)
    167                 if not isinteger(c[0]):
    168                     raise ValueError('%s colour for greyscale must be integer' % which)
    169             elif not (len(c) == 3 and isinteger(c[0]) and isinteger(c[1]) and isinteger(c[2])):
    170                 raise ValueError('%s colour must be a triple of integers' % which)
    171             return c
    172 
    173         if size:
    174             if len(size) != 2:
    175                 raise ValueError('size argument should be a pair (width, height)')
    176             if width is not None and width != size[0]:
    177                 raise ValueError('size[0] (%r) and width (%r) should match when both are used.' % (size[0], width))
    178             if height is not None and height != size[1]:
    179                 raise ValueError('size[1] (%r) and height (%r) should match when both are used.' % (size[1], height))
    180             width, height = size
    181         del size
    182         if width <= 0 or height <= 0:
    183             raise ValueError('width and height must be greater than zero')
    184         if not isinteger(width) or not isinteger(height):
    185             raise ValueError('width and height must be integers')
    186         if width > 4294967295L or height > 4294967295L:
    187             raise ValueError('width and height cannot exceed 2**32-1')
    188         if alpha and transparent is not None:
    189             raise ValueError('transparent colour not allowed with alpha channel')
    190         if bytes_per_sample is not None:
    191             warnings.warn('please use bitdepth instead of bytes_per_sample', DeprecationWarning)
    192             if bytes_per_sample not in (0.125, 0.25, 0.5, 1, 2):
    193                 raise ValueError('bytes per sample must be .125, .25, .5, 1, or 2')
    194             bitdepth = int(8 * bytes_per_sample)
    195         del bytes_per_sample
    196         if not isinteger(bitdepth) or bitdepth < 1 or 16 < bitdepth:
    197             raise ValueError('bitdepth (%r) must be a postive integer <= 16' % bitdepth)
    198         self.rescale = None
    199         if palette:
    200             if bitdepth not in (1, 2, 4, 8):
    201                 raise ValueError('with palette, bitdepth must be 1, 2, 4, or 8')
    202             if transparent is not None:
    203                 raise ValueError('transparent and palette not compatible')
    204             if alpha:
    205                 raise ValueError('alpha and palette not compatible')
    206             if greyscale:
    207                 raise ValueError('greyscale and palette not compatible')
    208         elif alpha or not greyscale:
    209             if bitdepth not in (8, 16):
    210                 targetbitdepth = (8, 16)[bitdepth > 8]
    211                 self.rescale = (bitdepth, targetbitdepth)
    212                 bitdepth = targetbitdepth
    213                 del targetbitdepth
    214         elif bitdepth not in (1, 2, 4, 8, 16):
    215             if bitdepth > 8:
    216                 targetbitdepth = 16
    217             elif bitdepth == 3:
    218                 targetbitdepth = 4
    219             else:
    220                 targetbitdepth = 8
    221             self.rescale = (bitdepth, targetbitdepth)
    222             bitdepth = targetbitdepth
    223             del targetbitdepth
    224         if bitdepth < 8 and (alpha or not greyscale and not palette):
    225             raise ValueError('bitdepth < 8 only permitted with greyscale or palette')
    226         if bitdepth > 8 and palette:
    227             raise ValueError('bit depth must be 8 or less for images with palette')
    228         transparent = check_color(transparent, 'transparent')
    229         background = check_color(background, 'background')
    230         self.width = width
    231         self.height = height
    232         self.transparent = transparent
    233         self.background = background
    234         self.gamma = gamma
    235         self.greyscale = bool(greyscale)
    236         self.alpha = bool(alpha)
    237         self.colormap = bool(palette)
    238         self.bitdepth = int(bitdepth)
    239         self.compression = compression
    240         self.chunk_limit = chunk_limit
    241         self.interlace = bool(interlace)
    242         self.palette = check_palette(palette)
    243         self.color_type = 4 * self.alpha + 2 * (not greyscale) + 1 * self.colormap
    244         self.color_planes = (3, 1)[self.greyscale or self.colormap]
    245         self.planes = self.color_planes + self.alpha
    246         self.psize = self.bitdepth / 8 * self.planes
    247 
    248     def make_palette(self):
    249         p = array('B')
    250         t = array('B')
    251         for x in self.palette:
    252             p.extend(x[0:3])
    253             if len(x) > 3:
    254                 t.append(x[3])
    255 
    256         p = tostring(p)
    257         t = tostring(t)
    258         if t:
    259             return (p, t)
    260         return (p, None)
    261 
    262     def write(self, outfile, rows):
    263         if self.interlace:
    264             fmt = 'BH'[self.bitdepth > 8]
    265             a = array(fmt, itertools.chain(*rows))
    266             return self.write_array(outfile, a)
    267         nrows = self.write_passes(outfile, rows)
    268         if nrows != self.height:
    269             raise ValueError('rows supplied (%d) does not match height (%d)' % (nrows, self.height))
    270 
    271     def write_passes(self, outfile, rows, packed = False):
    272         outfile.write(_signature)
    273         write_chunk(outfile, 'IHDR', struct.pack('!2I5B', self.width, self.height, self.bitdepth, self.color_type, 0, 0, self.interlace))
    274         if self.gamma is not None:
    275             write_chunk(outfile, 'gAMA', struct.pack('!L', int(round(self.gamma * 100000.0))))
    276         if self.rescale:
    277             write_chunk(outfile, 'sBIT', struct.pack(('%dB' % self.planes), *([self.rescale[0]] * self.planes)))
    278         if self.palette:
    279             p, t = self.make_palette()
    280             write_chunk(outfile, 'PLTE', p)
    281             if t:
    282                 write_chunk(outfile, 'tRNS', t)
    283         if self.transparent is not None:
    284             if self.greyscale:
    285                 write_chunk(outfile, 'tRNS', struct.pack('!1H', *self.transparent))
    286             else:
    287                 write_chunk(outfile, 'tRNS', struct.pack('!3H', *self.transparent))
    288         if self.background is not None:
    289             if self.greyscale:
    290                 write_chunk(outfile, 'bKGD', struct.pack('!1H', *self.background))
    291             else:
    292                 write_chunk(outfile, 'bKGD', struct.pack('!3H', *self.background))
    293         if self.compression is not None:
    294             compressor = zlib.compressobj(self.compression)
    295         else:
    296             compressor = zlib.compressobj()
    297         data = array('B')
    298         if self.bitdepth == 8 or packed:
    299             extend = data.extend
    300         elif self.bitdepth == 16:
    301 
    302             def extend(sl):
    303                 fmt = '!%dH' % len(sl)
    304                 data.extend(array('B', struct.pack(fmt, *sl)))
    305 
    306         else:
    307             spb = int(8 / self.bitdepth)
    308 
    309             def extend(sl):
    310                 a = array('B', sl)
    311                 l = float(len(a))
    312                 extra = math.ceil(l / float(spb)) * spb - l
    313                 a.extend([0] * int(extra))
    314                 l = group(a, spb)
    315                 l = map(lambda e: reduce(lambda x, y: (x << self.bitdepth) + y, e), l)
    316                 data.extend(l)
    317 
    318         if self.rescale:
    319             oldextend = extend
    320             factor = float(2 ** self.rescale[1] - 1) / float(2 ** self.rescale[0] - 1)
    321 
    322             def extend(sl):
    323                 oldextend(map(lambda x: int(round(factor * x)), sl))
    324 
    325         enumrows = enumerate(rows)
    326         del rows
    327         data.append(0)
    328         i, row = enumrows.next()
    329         try:
    330             extend(row)
    331         except:
    332 
    333             def wrapmapint(f):
    334                 return lambda sl: f(map(int, sl))
    335 
    336             extend = wrapmapint(extend)
    337             del wrapmapint
    338             extend(row)
    339 
    340         for i, row in enumrows:
    341             data.append(0)
    342             extend(row)
    343             if len(data) > self.chunk_limit:
    344                 compressed = compressor.compress(tostring(data))
    345                 if len(compressed):
    346                     write_chunk(outfile, 'IDAT', compressed)
    347                 del data[:]
    348 
    349         if len(data):
    350             compressed = compressor.compress(tostring(data))
    351         else:
    352             compressed = ''
    353         flushed = compressor.flush()
    354         if len(compressed) or len(flushed):
    355             write_chunk(outfile, 'IDAT', compressed + flushed)
    356         write_chunk(outfile, 'IEND')
    357         return i + 1
    358 
    359     def write_array(self, outfile, pixels):
    360         if self.interlace:
    361             self.write_passes(outfile, self.array_scanlines_interlace(pixels))
    362         else:
    363             self.write_passes(outfile, self.array_scanlines(pixels))
    364 
    365     def write_packed(self, outfile, rows):
    366         if self.rescale:
    367             raise Error('write_packed method not suitable for bit depth %d' % self.rescale[0])
    368         return self.write_passes(outfile, rows, packed=True)
    369 
    370     def convert_pnm(self, infile, outfile):
    371         if self.interlace:
    372             pixels = array('B')
    373             pixels.fromfile(infile, self.bitdepth / 8 * self.color_planes * self.width * self.height)
    374             self.write_passes(outfile, self.array_scanlines_interlace(pixels))
    375         else:
    376             self.write_passes(outfile, self.file_scanlines(infile))
    377 
    378     def convert_ppm_and_pgm(self, ppmfile, pgmfile, outfile):
    379         pixels = array('B')
    380         pixels.fromfile(ppmfile, self.bitdepth / 8 * self.color_planes * self.width * self.height)
    381         apixels = array('B')
    382         apixels.fromfile(pgmfile, self.bitdepth / 8 * self.width * self.height)
    383         pixels = interleave_planes(pixels, apixels, self.bitdepth / 8 * self.color_planes, self.bitdepth / 8)
    384         if self.interlace:
    385             self.write_passes(outfile, self.array_scanlines_interlace(pixels))
    386         else:
    387             self.write_passes(outfile, self.array_scanlines(pixels))
    388 
    389     def file_scanlines(self, infile):
    390         vpr = self.width * self.planes
    391         row_bytes = vpr
    392         if self.bitdepth > 8:
    393             row_bytes *= 2
    394             fmt = '>%dH' % vpr
    395 
    396             def line():
    397                 return array('H', struct.unpack(fmt, infile.read(row_bytes)))
    398 
    399         else:
    400 
    401             def line():
    402                 scanline = array('B', infile.read(row_bytes))
    403                 return scanline
    404 
    405         for y in range(self.height):
    406             yield line()
    407 
    408     def array_scanlines(self, pixels):
    409         vpr = self.width * self.planes
    410         stop = 0
    411         for y in range(self.height):
    412             start = stop
    413             stop = start + vpr
    414             yield pixels[start:stop]
    415 
    416     def array_scanlines_interlace(self, pixels):
    417         fmt = 'BH'[self.bitdepth > 8]
    418         vpr = self.width * self.planes
    419         for xstart, ystart, xstep, ystep in _adam7:
    420             if xstart >= self.width:
    421                 continue
    422             ppr = int(math.ceil((self.width - xstart) / float(xstep)))
    423             row_len = ppr * self.planes
    424             for y in range(ystart, self.height, ystep):
    425                 if xstep == 1:
    426                     offset = y * vpr
    427                     yield pixels[offset:offset + vpr]
    428                 else:
    429                     row = array(fmt)
    430                     row.extend(pixels[0:row_len])
    431                     offset = y * vpr + xstart * self.planes
    432                     end_offset = (y + 1) * vpr
    433                     skip = self.planes * xstep
    434                     for i in range(self.planes):
    435                         row[i::self.planes] = pixels[offset + i:end_offset:skip]
    436 
    437                     yield row
    438 
    439 
    440 def write_chunk(outfile, tag, data = strtobytes('')):
    441     outfile.write(struct.pack('!I', len(data)))
    442     tag = strtobytes(tag)
    443     outfile.write(tag)
    444     outfile.write(data)
    445     checksum = zlib.crc32(tag)
    446     checksum = zlib.crc32(data, checksum)
    447     checksum &= 4294967295L
    448     outfile.write(struct.pack('!I', checksum))
    449 
    450 
    451 def write_chunks(out, chunks):
    452     out.write(_signature)
    453     for chunk in chunks:
    454         write_chunk(out, *chunk)
    455 
    456 
    457 def filter_scanline(type, line, fo, prev = None):
    458     out = array('B', [type])
    459 
    460     def sub():
    461         ai = -fo
    462         for x in line:
    463             if ai >= 0:
    464                 x = x - line[ai] & 255
    465             out.append(x)
    466             ai += 1
    467 
    468     def up():
    469         for i, x in enumerate(line):
    470             x = x - prev[i] & 255
    471             out.append(x)
    472 
    473     def average():
    474         ai = -fo
    475         for i, x in enumerate(line):
    476             if ai >= 0:
    477                 x = x - (line[ai] + prev[i] >> 1) & 255
    478             else:
    479                 x = x - (prev[i] >> 1) & 255
    480             out.append(x)
    481             ai += 1
    482 
    483     def paeth():
    484         ai = -fo
    485         for i, x in enumerate(line):
    486             a = 0
    487             b = prev[i]
    488             c = 0
    489             if ai >= 0:
    490                 a = line[ai]
    491                 c = prev[ai]
    492             p = a + b - c
    493             pa = abs(p - a)
    494             pb = abs(p - b)
    495             pc = abs(p - c)
    496             if pa <= pb and pa <= pc:
    497                 Pr = a
    498             elif pb <= pc:
    499                 Pr = b
    500             else:
    501                 Pr = c
    502             x = x - Pr & 255
    503             out.append(x)
    504             ai += 1
    505 
    506     if not prev:
    507         if type == 2:
    508             return line
    509         if type == 3:
    510             prev = [0] * len(line)
    511         elif type == 4:
    512             type = 1
    513     if type == 0:
    514         out.extend(line)
    515     elif type == 1:
    516         sub()
    517     elif type == 2:
    518         up()
    519     elif type == 3:
    520         average()
    521     else:
    522         paeth()
    523     return out
    524 
    525 
    526 def from_array(a, mode = None, info = {}):
    527     info = dict(info)
    528     bitdepth = None
    529     try:
    530         mode = mode.split(';')
    531         if len(mode) not in (1, 2):
    532             raise Error()
    533         if mode[0] not in ('L', 'LA', 'RGB', 'RGBA'):
    534             raise Error()
    535         if len(mode) == 2:
    536             try:
    537                 bitdepth = int(mode[1])
    538             except:
    539                 raise Error()
    540 
    541     except Error:
    542         raise Error("mode string should be 'RGB' or 'L;16' or similar.")
    543 
    544     mode = mode[0]
    545     if bitdepth:
    546         if info.get('bitdepth') and bitdepth != info['bitdepth']:
    547             raise Error('mode bitdepth (%d) should match info bitdepth (%d).' % (bitdepth, info['bitdepth']))
    548         info['bitdepth'] = bitdepth
    549     if 'size' in info:
    550         for dimension, axis in [('width', 0), ('height', 1)]:
    551             if dimension in info:
    552                 if info[dimension] != info['size'][axis]:
    553                     raise Error("info[%r] shhould match info['size'][%r]." % (dimension, axis))
    554 
    555         info['width'], info['height'] = info['size']
    556     if 'height' not in info:
    557         try:
    558             l = len(a)
    559         except:
    560             raise Error("len(a) does not work, supply info['height'] instead.")
    561 
    562         info['height'] = l
    563     if 'greyscale' in info:
    564         if bool(info['greyscale']) != ('L' in mode):
    565             raise Error("info['greyscale'] should match mode.")
    566     info['greyscale'] = 'L' in mode
    567     if 'alpha' in info:
    568         if bool(info['alpha']) != ('A' in mode):
    569             raise Error("info['alpha'] should match mode.")
    570     info['alpha'] = 'A' in mode
    571     planes = len(mode)
    572     if 'planes' in info:
    573         if info['planes'] != planes:
    574             raise Error("info['planes'] should match mode.")
    575     a, t = itertools.tee(a)
    576     row = t.next()
    577     del t
    578     try:
    579         row[0][0]
    580         threed = True
    581         testelement = row[0]
    582     except:
    583         threed = False
    584         testelement = row
    585 
    586     if 'width' not in info:
    587         if threed:
    588             width = len(row)
    589         else:
    590             width = len(row) // planes
    591         info['width'] = width
    592     if 'bitdepth' not in info:
    593         try:
    594             dtype = testelement.dtype
    595         except:
    596             try:
    597                 bitdepth = 8 * testelement.itemsize
    598             except:
    599                 bitdepth = 8
    600 
    601         else:
    602             if dtype.kind == 'b':
    603                 bitdepth = 1
    604             else:
    605                 bitdepth = 8 * dtype.itemsize
    606 
    607         info['bitdepth'] = bitdepth
    608     for thing in 'width height bitdepth greyscale alpha'.split():
    609         pass
    610 
    611     return Image(a, info)
    612 
    613 
    614 fromarray = from_array
    615 
    616 class Image():
    617 
    618     def __init__(self, rows, info):
    619         self.rows = rows
    620         self.info = info
    621 
    622     def save(self, file):
    623         w = Writer(**self.info)
    624         try:
    625             file.write
    626 
    627             def close():
    628                 pass
    629 
    630         except:
    631             file = open(file, 'wb')
    632 
    633             def close():
    634                 file.close()
    635 
    636         try:
    637             w.write(file, self.rows)
    638         finally:
    639             close()
    640 
    641 
    642 class _readable():
    643 
    644     def __init__(self, buf):
    645         self.buf = buf
    646         self.offset = 0
    647 
    648     def read(self, n):
    649         r = self.buf[self.offset:self.offset + n]
    650         if isarray(r):
    651             r = r.tostring()
    652         self.offset += n
    653         return r
    654 
    655 
    656 class Reader():
    657 
    658     def __init__(self, _guess = None, **kw):
    659         if _guess is not None and len(kw) != 0 or _guess is None and len(kw) != 1:
    660             raise TypeError('Reader() takes exactly 1 argument')
    661         self.signature = None
    662         self.transparent = None
    663         self.atchunk = None
    664         if _guess is not None:
    665             if isarray(_guess):
    666                 kw['bytes'] = _guess
    667             elif isinstance(_guess, str):
    668                 kw['filename'] = _guess
    669             elif isinstance(_guess, file):
    670                 kw['file'] = _guess
    671         if 'filename' in kw:
    672             self.file = open(kw['filename'], 'rb')
    673         elif 'file' in kw:
    674             self.file = kw['file']
    675         elif 'bytes' in kw:
    676             self.file = _readable(kw['bytes'])
    677         else:
    678             raise TypeError('expecting filename, file or bytes array')
    679 
    680     def chunk(self, seek = None):
    681         self.validate_signature()
    682         while True:
    683             if not self.atchunk:
    684                 self.atchunk = self.chunklentype()
    685             length, type = self.atchunk
    686             self.atchunk = None
    687             data = self.file.read(length)
    688             if len(data) != length:
    689                 raise ChunkError('Chunk %s too short for required %i octets.' % (type, length))
    690             checksum = self.file.read(4)
    691             if len(checksum) != 4:
    692                 raise ValueError('Chunk %s too short for checksum.', tag)
    693             if seek and type != seek:
    694                 continue
    695             verify = zlib.crc32(strtobytes(type))
    696             verify = zlib.crc32(data, verify)
    697             verify &= 4294967295L
    698             verify = struct.pack('!I', verify)
    699             if checksum != verify:
    700                 a, = struct.unpack('!I', checksum)
    701                 b, = struct.unpack('!I', verify)
    702                 raise ChunkError('Checksum error in %s chunk: 0x%08X != 0x%08X.' % (type, a, b))
    703             return (type, data)
    704 
    705     def chunks(self):
    706         while True:
    707             t, v = self.chunk()
    708             yield (t, v)
    709             if t == 'IEND':
    710                 break
    711 
    712     def undo_filter(self, filter_type, scanline, previous):
    713         result = array('B', scanline)
    714         if filter_type == 0:
    715             return result
    716         if filter_type not in (1, 2, 3, 4):
    717             raise FormatError('Invalid PNG Filter Type.  See http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters .')
    718         fu = max(1, self.psize)
    719         if not previous:
    720             previous = array('B', [0] * len(scanline))
    721 
    722         def sub():
    723             ai = 0
    724             for i in range(fu, len(result)):
    725                 x = scanline[i]
    726                 a = result[ai]
    727                 result[i] = x + a & 255
    728                 ai += 1
    729 
    730         def up():
    731             for i in range(len(result)):
    732                 x = scanline[i]
    733                 b = previous[i]
    734                 result[i] = x + b & 255
    735 
    736         def average():
    737             ai = -fu
    738             for i in range(len(result)):
    739                 x = scanline[i]
    740                 if ai < 0:
    741                     a = 0
    742                 else:
    743                     a = result[ai]
    744                 b = previous[i]
    745                 result[i] = x + (a + b >> 1) & 255
    746                 ai += 1
    747 
    748         def paeth():
    749             ai = -fu
    750             for i in range(len(result)):
    751                 x = scanline[i]
    752                 if ai < 0:
    753                     a = c = 0
    754                 else:
    755                     a = result[ai]
    756                     c = previous[ai]
    757                 b = previous[i]
    758                 p = a + b - c
    759                 pa = abs(p - a)
    760                 pb = abs(p - b)
    761                 pc = abs(p - c)
    762                 if pa <= pb and pa <= pc:
    763                     pr = a
    764                 elif pb <= pc:
    765                     pr = b
    766                 else:
    767                     pr = c
    768                 result[i] = x + pr & 255
    769                 ai += 1
    770 
    771         (None,
    772          sub,
    773          up,
    774          average,
    775          paeth)[filter_type]()
    776         return result
    777 
    778     def deinterlace(self, raw):
    779         vpr = self.width * self.planes
    780         fmt = 'BH'[self.bitdepth > 8]
    781         a = array(fmt, [0] * vpr * self.height)
    782         source_offset = 0
    783         for xstart, ystart, xstep, ystep in _adam7:
    784             if xstart >= self.width:
    785                 continue
    786             recon = None
    787             ppr = int(math.ceil((self.width - xstart) / float(xstep)))
    788             row_size = int(math.ceil(self.psize * ppr))
    789             for y in range(ystart, self.height, ystep):
    790                 filter_type = raw[source_offset]
    791                 source_offset += 1
    792                 scanline = raw[source_offset:source_offset + row_size]
    793                 source_offset += row_size
    794                 recon = self.undo_filter(filter_type, scanline, recon)
    795                 flat = self.serialtoflat(recon, ppr)
    796                 if xstep == 1:
    797                     offset = y * vpr
    798                     a[offset:offset + vpr] = flat
    799                 else:
    800                     offset = y * vpr + xstart * self.planes
    801                     end_offset = (y + 1) * vpr
    802                     skip = self.planes * xstep
    803                     for i in range(self.planes):
    804                         a[offset + i:end_offset:skip] = flat[i::self.planes]
    805 
    806         return a
    807 
    808     def iterboxed(self, rows):
    809 
    810         def asvalues(raw):
    811             if self.bitdepth == 8:
    812                 return raw
    813             if self.bitdepth == 16:
    814                 raw = tostring(raw)
    815                 return array('H', struct.unpack('!%dH' % (len(raw) // 2), raw))
    816             width = self.width
    817             spb = 8 // self.bitdepth
    818             out = array('B')
    819             mask = 2 ** self.bitdepth - 1
    820             shifts = map(self.bitdepth.__mul__, reversed(range(spb)))
    821             for o in raw:
    822                 out.extend(map(lambda i: mask & o >> i, shifts))
    823 
    824             return out[:width]
    825 
    826         return itertools.imap(asvalues, rows)
    827 
    828     def serialtoflat(self, bytes, width = None):
    829         if self.bitdepth == 8:
    830             return bytes
    831         if self.bitdepth == 16:
    832             bytes = tostring(bytes)
    833             return array('H', struct.unpack('!%dH' % (len(bytes) // 2), bytes))
    834         if width is None:
    835             width = self.width
    836         spb = 8 // self.bitdepth
    837         out = array('B')
    838         mask = 2 ** self.bitdepth - 1
    839         shifts = map(self.bitdepth.__mul__, reversed(range(spb)))
    840         l = width
    841         for o in bytes:
    842             out.extend([ mask & o >> s for s in shifts ][:l])
    843             l -= spb
    844             if l <= 0:
    845                 l = width
    846 
    847         return out
    848 
    849     def iterstraight(self, raw):
    850         rb = self.row_bytes
    851         a = array('B')
    852         recon = None
    853         for some in raw:
    854             a.extend(some)
    855             while len(a) >= rb + 1:
    856                 filter_type = a[0]
    857                 scanline = a[1:rb + 1]
    858                 del a[:rb + 1]
    859                 recon = self.undo_filter(filter_type, scanline, recon)
    860                 yield recon
    861 
    862         if len(a) != 0:
    863             raise FormatError('Wrong size for decompressed IDAT chunk.')
    864 
    865     def validate_signature(self):
    866         if self.signature:
    867             return
    868         self.signature = self.file.read(8)
    869         if self.signature != _signature:
    870             raise FormatError('PNG file has invalid signature.')
    871 
    872     def preamble(self):
    873         self.validate_signature()
    874         while True:
    875             if not self.atchunk:
    876                 self.atchunk = self.chunklentype()
    877                 if self.atchunk is None:
    878                     raise FormatError('This PNG file has no IDAT chunks.')
    879             if self.atchunk[1] == 'IDAT':
    880                 return
    881             self.process_chunk()
    882 
    883     def chunklentype(self):
    884         x = self.file.read(8)
    885         if not x:
    886             return None
    887         if len(x) != 8:
    888             raise FormatError('End of file whilst reading chunk length and type.')
    889         length, type = struct.unpack('!I4s', x)
    890         type = bytestostr(type)
    891         if length > 2147483647L:
    892             raise FormatError('Chunk %s is too large: %d.' % (type, length))
    893         return (length, type)
    894 
    895     def process_chunk(self):
    896         type, data = self.chunk()
    897         if type == 'IHDR':
    898             if len(data) != 13:
    899                 raise FormatError('IHDR chunk has incorrect length.')
    900             self.width, self.height, self.bitdepth, self.color_type, self.compression, self.filter, self.interlace = struct.unpack('!2I5B', data)
    901             if self.bitdepth not in (1, 2, 4, 8, 16):
    902                 raise Error('invalid bit depth %d' % self.bitdepth)
    903             if self.color_type not in (0, 2, 3, 4, 6):
    904                 raise Error('invalid colour type %d' % self.color_type)
    905             if self.color_type & 1 and self.bitdepth > 8 or self.bitdepth < 8 and self.color_type not in (0, 3):
    906                 raise FormatError('Illegal combination of bit depth (%d) and colour type (%d). See http://www.w3.org/TR/2003/REC-PNG-20031110/#table111 .' % (self.bitdepth, self.color_type))
    907             if self.compression != 0:
    908                 raise Error('unknown compression method %d' % self.compression)
    909             if self.filter != 0:
    910                 raise FormatError('Unknown filter method %d, see http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters .' % self.filter)
    911             if self.interlace not in (0, 1):
    912                 raise FormatError('Unknown interlace method %d, see http://www.w3.org/TR/2003/REC-PNG-20031110/#8InterlaceMethods .' % self.interlace)
    913             colormap = bool(self.color_type & 1)
    914             greyscale = not self.color_type & 2
    915             alpha = bool(self.color_type & 4)
    916             color_planes = (3, 1)[greyscale or colormap]
    917             planes = color_planes + alpha
    918             self.colormap = colormap
    919             self.greyscale = greyscale
    920             self.alpha = alpha
    921             self.color_planes = color_planes
    922             self.planes = planes
    923             self.psize = float(self.bitdepth) / float(8) * planes
    924             if int(self.psize) == self.psize:
    925                 self.psize = int(self.psize)
    926             self.row_bytes = int(math.ceil(self.width * self.psize))
    927             self.plte = None
    928             self.trns = None
    929             self.sbit = None
    930         elif type == 'PLTE':
    931             if self.plte:
    932                 warnings.warn('Multiple PLTE chunks present.')
    933             self.plte = data
    934             if len(data) % 3 != 0:
    935                 raise FormatError("PLTE chunk's length should be a multiple of 3.")
    936             if len(data) > 2 ** self.bitdepth * 3:
    937                 raise FormatError('PLTE chunk is too long.')
    938             if len(data) == 0:
    939                 raise FormatError('Empty PLTE is not allowed.')
    940         elif type == 'bKGD':
    941             try:
    942                 if self.colormap:
    943                     if not self.plte:
    944                         warnings.warn('PLTE chunk is required before bKGD chunk.')
    945                     self.background = struct.unpack('B', data)
    946                 else:
    947                     self.background = struct.unpack('!%dH' % self.color_planes, data)
    948             except struct.error:
    949                 raise FormatError('bKGD chunk has incorrect length.')
    950 
    951         elif type == 'tRNS':
    952             self.trns = data
    953             if self.colormap:
    954                 if not self.plte:
    955                     warnings.warn('PLTE chunk is required before tRNS chunk.')
    956                 elif len(data) > len(self.plte) / 3:
    957                     raise FormatError('tRNS chunk is too long.')
    958             else:
    959                 if self.alpha:
    960                     raise FormatError('tRNS chunk is not valid with colour type %d.' % self.color_type)
    961                 try:
    962                     self.transparent = struct.unpack('!%dH' % self.color_planes, data)
    963                 except struct.error:
    964                     raise FormatError('tRNS chunk has incorrect length.')
    965 
    966         elif type == 'gAMA':
    967             try:
    968                 self.gamma = struct.unpack('!L', data)[0] / 100000.0
    969             except struct.error:
    970                 raise FormatError('gAMA chunk has incorrect length.')
    971 
    972         elif type == 'sBIT':
    973             self.sbit = data
    974             if self.colormap and len(data) != 3 or not self.colormap and len(data) != self.planes:
    975                 raise FormatError('sBIT chunk has incorrect length.')
    976 
    977     def read(self):
    978 
    979         def iteridat():
    980             while True:
    981                 try:
    982                     type, data = self.chunk()
    983                 except ValueError as e:
    984                     raise ChunkError(e.args[0])
    985 
    986                 if type == 'IEND':
    987                     break
    988                 if type != 'IDAT':
    989                     continue
    990                 if self.colormap and not self.plte:
    991                     warnings.warn('PLTE chunk is required before IDAT chunk')
    992                 yield data
    993 
    994         def iterdecomp(idat):
    995             d = zlib.decompressobj()
    996             for data in idat:
    997                 yield array('B', d.decompress(data))
    998 
    999             yield array('B', d.flush())
   1000 
   1001         self.preamble()
   1002         raw = iterdecomp(iteridat())
   1003         if self.interlace:
   1004             raw = array('B', itertools.chain(*raw))
   1005             arraycode = 'BH'[self.bitdepth > 8]
   1006             pixels = itertools.imap((lambda *row: array(arraycode, row)), *([iter(self.deinterlace(raw))] * self.width * self.planes))
   1007         else:
   1008             pixels = self.iterboxed(self.iterstraight(raw))
   1009         meta = dict()
   1010         for attr in 'greyscale alpha planes bitdepth interlace'.split():
   1011             meta[attr] = getattr(self, attr)
   1012 
   1013         meta['size'] = (self.width, self.height)
   1014         for attr in 'gamma transparent background'.split():
   1015             a = getattr(self, attr, None)
   1016             if a is not None:
   1017                 meta[attr] = a
   1018 
   1019         return (self.width,
   1020          self.height,
   1021          pixels,
   1022          meta)
   1023 
   1024     def read_flat(self):
   1025         x, y, pixel, meta = self.read()
   1026         arraycode = 'BH'[meta['bitdepth'] > 8]
   1027         pixel = array(arraycode, itertools.chain(*pixel))
   1028         return (x,
   1029          y,
   1030          pixel,
   1031          meta)
   1032 
   1033     def palette(self, alpha = 'natural'):
   1034         if not self.plte:
   1035             raise FormatError('Required PLTE chunk is missing in colour type 3 image.')
   1036         plte = group(array('B', self.plte), 3)
   1037         if self.trns or alpha == 'force':
   1038             trns = array('B', self.trns or '')
   1039             trns.extend([255] * (len(plte) - len(trns)))
   1040             plte = map(operator.add, plte, group(trns, 1))
   1041         return plte
   1042 
   1043     def asDirect(self):
   1044         self.preamble()
   1045         if not self.colormap and not self.trns and not self.sbit:
   1046             return self.read()
   1047         x, y, pixels, meta = self.read()
   1048         if self.colormap:
   1049             meta['colormap'] = False
   1050             meta['alpha'] = bool(self.trns)
   1051             meta['bitdepth'] = 8
   1052             meta['planes'] = 3 + bool(self.trns)
   1053             plte = self.palette()
   1054 
   1055             def iterpal(pixels):
   1056                 for row in pixels:
   1057                     row = map(plte.__getitem__, row)
   1058                     yield array('B', itertools.chain(*row))
   1059 
   1060             pixels = iterpal(pixels)
   1061         elif self.trns:
   1062             it = self.transparent
   1063             maxval = 2 ** meta['bitdepth'] - 1
   1064             planes = meta['planes']
   1065             meta['alpha'] = True
   1066             meta['planes'] += 1
   1067             typecode = 'BH'[meta['bitdepth'] > 8]
   1068 
   1069             def itertrns(pixels):
   1070                 for row in pixels:
   1071                     row = group(row, planes)
   1072                     opa = map(it.__ne__, row)
   1073                     opa = map(maxval.__mul__, opa)
   1074                     opa = zip(opa)
   1075                     yield array(typecode, itertools.chain(*map(operator.add, row, opa)))
   1076 
   1077             pixels = itertrns(pixels)
   1078         targetbitdepth = None
   1079         if self.sbit:
   1080             sbit = struct.unpack('%dB' % len(self.sbit), self.sbit)
   1081             targetbitdepth = max(sbit)
   1082             if targetbitdepth > meta['bitdepth']:
   1083                 raise Error('sBIT chunk %r exceeds bitdepth %d' % (sbit, self.bitdepth))
   1084             if min(sbit) <= 0:
   1085                 raise Error('sBIT chunk %r has a 0-entry' % sbit)
   1086             if targetbitdepth == meta['bitdepth']:
   1087                 targetbitdepth = None
   1088         if targetbitdepth:
   1089             shift = meta['bitdepth'] - targetbitdepth
   1090             meta['bitdepth'] = targetbitdepth
   1091 
   1092             def itershift(pixels):
   1093                 for row in pixels:
   1094                     yield map(shift.__rrshift__, row)
   1095 
   1096             pixels = itershift(pixels)
   1097         return (x,
   1098          y,
   1099          pixels,
   1100          meta)
   1101 
   1102     def asFloat(self, maxval = 1.0):
   1103         x, y, pixels, info = self.asDirect()
   1104         sourcemaxval = 2 ** info['bitdepth'] - 1
   1105         del info['bitdepth']
   1106         info['maxval'] = float(maxval)
   1107         factor = float(maxval) / float(sourcemaxval)
   1108 
   1109         def iterfloat():
   1110             for row in pixels:
   1111                 yield map(factor.__mul__, row)
   1112 
   1113         return (x,
   1114          y,
   1115          iterfloat(),
   1116          info)
   1117 
   1118     def _as_rescale(self, get, targetbitdepth):
   1119         width, height, pixels, meta = get()
   1120         maxval = 2 ** meta['bitdepth'] - 1
   1121         targetmaxval = 2 ** targetbitdepth - 1
   1122         factor = float(targetmaxval) / float(maxval)
   1123         meta['bitdepth'] = targetbitdepth
   1124 
   1125         def iterscale():
   1126             for row in pixels:
   1127                 yield map(lambda x: int(round(x * factor)), row)
   1128 
   1129         return (width,
   1130          height,
   1131          iterscale(),
   1132          meta)
   1133 
   1134     def asRGB8(self):
   1135         return self._as_rescale(self.asRGB, 8)
   1136 
   1137     def asRGBA8(self):
   1138         return self._as_rescale(self.asRGBA, 8)
   1139 
   1140     def asRGB(self):
   1141         width, height, pixels, meta = self.asDirect()
   1142         if meta['alpha']:
   1143             raise Error('will not convert image with alpha channel to RGB')
   1144         if not meta['greyscale']:
   1145             return (width,
   1146              height,
   1147              pixels,
   1148              meta)
   1149         meta['greyscale'] = False
   1150         typecode = 'BH'[meta['bitdepth'] > 8]
   1151 
   1152         def iterrgb():
   1153             for row in pixels:
   1154                 a = array(typecode, [0]) * 3 * width
   1155                 for i in range(3):
   1156                     a[i::3] = row
   1157 
   1158                 yield a
   1159 
   1160         return (width,
   1161          height,
   1162          iterrgb(),
   1163          meta)
   1164 
   1165     def asRGBA(self):
   1166         width, height, pixels, meta = self.asDirect()
   1167         if meta['alpha'] and not meta['greyscale']:
   1168             return (width,
   1169              height,
   1170              pixels,
   1171              meta)
   1172         typecode = 'BH'[meta['bitdepth'] > 8]
   1173         maxval = 2 ** meta['bitdepth'] - 1
   1174 
   1175         def newarray():
   1176             return array(typecode, [0]) * 4 * width
   1177 
   1178         if meta['alpha'] and meta['greyscale']:
   1179 
   1180             def convert():
   1181                 for row in pixels:
   1182                     a = newarray()
   1183                     for i in range(3):
   1184                         a[i::4] = row[0::2]
   1185 
   1186                     a[3::4] = row[1::2]
   1187                     yield a
   1188 
   1189         elif meta['greyscale']:
   1190 
   1191             def convert():
   1192                 for row in pixels:
   1193                     a = newarray()
   1194                     for i in range(3):
   1195                         a[i::4] = row
   1196 
   1197                     a[3::4] = array(typecode, [maxval]) * width
   1198                     yield a
   1199 
   1200         else:
   1201 
   1202             def convert():
   1203                 for row in pixels:
   1204                     a = newarray()
   1205                     for i in range(3):
   1206                         a[i::4] = row[i::3]
   1207 
   1208                     a[3::4] = array(typecode, [maxval]) * width
   1209                     yield a
   1210 
   1211         meta['alpha'] = True
   1212         meta['greyscale'] = False
   1213         return (width,
   1214          height,
   1215          convert(),
   1216          meta)
   1217 
   1218 
   1219 try:
   1220     array('B').extend([])
   1221     array('B', array('B'))
   1222 except:
   1223     try:
   1224 
   1225         class _array_shim(array):
   1226             true_array = array
   1227 
   1228             def __new__(cls, typecode, init = None):
   1229                 super_new = super(_array_shim, cls).__new__
   1230                 it = super_new(cls, typecode)
   1231                 if init is None:
   1232                     return it
   1233                 it.extend(init)
   1234                 return it
   1235 
   1236             def extend(self, extension):
   1237                 super_extend = super(_array_shim, self).extend
   1238                 if isinstance(extension, self.true_array):
   1239                     return super_extend(extension)
   1240                 if not isinstance(extension, (list, str)):
   1241                     extension = list(extension)
   1242                 return super_extend(self.true_array(self.typecode, extension))
   1243 
   1244 
   1245         array = _array_shim
   1246     except:
   1247 
   1248         def array(typecode, init = ()):
   1249             if type(init) == str:
   1250                 return map(ord, init)
   1251             return list(init)
   1252 
   1253 
   1254 try:
   1255     enumerate
   1256 except:
   1257 
   1258     def enumerate(seq):
   1259         i = 0
   1260         for x in seq:
   1261             yield (i, x)
   1262             i += 1
   1263 
   1264 
   1265 try:
   1266     reversed
   1267 except:
   1268 
   1269     def reversed(l):
   1270         l = list(l)
   1271         l.reverse()
   1272         for x in l:
   1273             yield x
   1274 
   1275 
   1276 try:
   1277     itertools
   1278 except:
   1279 
   1280     class _dummy_itertools():
   1281         pass
   1282 
   1283 
   1284     itertools = _dummy_itertools()
   1285 
   1286     def _itertools_imap(f, seq):
   1287         for x in seq:
   1288             yield f(x)
   1289 
   1290 
   1291     itertools.imap = _itertools_imap
   1292 
   1293     def _itertools_chain(*iterables):
   1294         for it in iterables:
   1295             for element in it:
   1296                 yield element
   1297 
   1298 
   1299     itertools.chain = _itertools_chain
   1300 
   1301 try:
   1302     from io import BytesIO
   1303 except:
   1304     from StringIO import StringIO as BytesIO
   1305 
   1306 import tempfile
   1307 import unittest
   1308 
   1309 def test():
   1310     unittest.main(__name__)
   1311 
   1312 
   1313 def topngbytes(name, rows, x, y, **k):
   1314     import os
   1315     print name
   1316     f = BytesIO()
   1317     w = Writer(x, y, **k)
   1318     w.write(f, rows)
   1319     if os.environ.get('PYPNG_TEST_TMP'):
   1320         w = open(name, 'wb')
   1321         w.write(f.getvalue())
   1322         w.close()
   1323     return f.getvalue()
   1324 
   1325 
   1326 def testWithIO(inp, out, f):
   1327     import os
   1328     try:
   1329         oldin, sys.stdin = sys.stdin, inp
   1330         oldout, sys.stdout = sys.stdout, out
   1331         x = f()
   1332     finally:
   1333         sys.stdin = oldin
   1334         sys.stdout = oldout
   1335 
   1336     if os.environ.get('PYPNG_TEST_TMP') and hasattr(out, 'getvalue'):
   1337         name = mycallersname()
   1338         if name:
   1339             w = open(name + '.png', 'wb')
   1340             w.write(out.getvalue())
   1341             w.close()
   1342     return x
   1343 
   1344 
   1345 def mycallersname():
   1346     import inspect
   1347     frame = inspect.currentframe()
   1348     if not frame:
   1349         return
   1350     frame_, filename_, lineno_, funname, linelist_, listi_ = inspect.getouterframes(frame)[2]
   1351     return funname
   1352 
   1353 
   1354 def seqtobytes(s):
   1355     return strtobytes(''.join((chr(x) for x in s)))
   1356 
   1357 
   1358 class Test(unittest.TestCase):
   1359 
   1360     class failureException(Exception):
   1361         pass
   1362 
   1363     def helperLN(self, n):
   1364         mask = (1 << n) - 1
   1365         w = Writer(15, 17, greyscale=True, bitdepth=n, chunk_limit=99)
   1366         f = BytesIO()
   1367         w.write_array(f, array('B', map(mask.__and__, range(1, 256))))
   1368         r = Reader(bytes=f.getvalue())
   1369         x, y, pixels, meta = r.read()
   1370         self.assertEqual(x, 15)
   1371         self.assertEqual(y, 17)
   1372         self.assertEqual(list(itertools.chain(*pixels)), map(mask.__and__, range(1, 256)))
   1373 
   1374     def testL8(self):
   1375         return self.helperLN(8)
   1376 
   1377     def testL4(self):
   1378         return self.helperLN(4)
   1379 
   1380     def testL2(self):
   1381         w = Writer(1, 4, greyscale=True, bitdepth=2)
   1382         f = BytesIO()
   1383         w.write_array(f, array('B', range(4)))
   1384         r = Reader(bytes=f.getvalue())
   1385         x, y, pixels, meta = r.asRGB8()
   1386         self.assertEqual(x, 1)
   1387         self.assertEqual(y, 4)
   1388         for i, row in enumerate(pixels):
   1389             self.assertEqual(len(row), 3)
   1390             self.assertEqual(list(row), [85 * i] * 3)
   1391 
   1392     def testP2(self):
   1393         a = (255, 255, 255)
   1394         b = (200, 120, 120)
   1395         c = (50, 99, 50)
   1396         w = Writer(1, 4, bitdepth=2, palette=[a, b, c])
   1397         f = BytesIO()
   1398         w.write_array(f, array('B', (0, 1, 1, 2)))
   1399         r = Reader(bytes=f.getvalue())
   1400         x, y, pixels, meta = r.asRGB8()
   1401         self.assertEqual(x, 1)
   1402         self.assertEqual(y, 4)
   1403         self.assertEqual(list(pixels), map(list, [a,
   1404          b,
   1405          b,
   1406          c]))
   1407 
   1408     def testPtrns(self):
   1409         a = (50, 99, 50, 50)
   1410         b = (200, 120, 120, 80)
   1411         c = (255, 255, 255)
   1412         d = (200, 120, 120)
   1413         e = (50, 99, 50)
   1414         w = Writer(3, 3, bitdepth=4, palette=[a,
   1415          b,
   1416          c,
   1417          d,
   1418          e])
   1419         f = BytesIO()
   1420         w.write_array(f, array('B', (4, 3, 2, 3, 2, 0, 2, 0, 1)))
   1421         r = Reader(bytes=f.getvalue())
   1422         x, y, pixels, meta = r.asRGBA8()
   1423         self.assertEqual(x, 3)
   1424         self.assertEqual(y, 3)
   1425         c = c + (255,)
   1426         d = d + (255,)
   1427         e = e + (255,)
   1428         boxed = [(e, d, c), (d, c, a), (c, a, b)]
   1429         flat = map(lambda row: itertools.chain(*row), boxed)
   1430         self.assertEqual(map(list, pixels), map(list, flat))
   1431 
   1432     def testRGBtoRGBA(self):
   1433         r = Reader(bytes=_pngsuite['basn2c08'])
   1434         x, y, pixels, meta = r.asRGBA8()
   1435         row9 = list(pixels)[9]
   1436         self.assertEqual(row9[0:8], [255,
   1437          223,
   1438          255,
   1439          255,
   1440          255,
   1441          222,
   1442          255,
   1443          255])
   1444 
   1445     def testLtoRGBA(self):
   1446         r = Reader(bytes=_pngsuite['basi0g08'])
   1447         x, y, pixels, meta = r.asRGBA()
   1448         row9 = list(list(pixels)[9])
   1449         self.assertEqual(row9[0:8], [222,
   1450          222,
   1451          222,
   1452          255,
   1453          221,
   1454          221,
   1455          221,
   1456          255])
   1457 
   1458     def testCtrns(self):
   1459         r = Reader(bytes=_pngsuite['tbrn2c08'])
   1460         x, y, pixels, meta = r.asRGBA8()
   1461         row0 = list(pixels)[0]
   1462         self.assertEqual(tuple(row0[0:4]), (127, 127, 127, 0))
   1463 
   1464     def testAdam7read(self):
   1465         for candidate in _pngsuite:
   1466             if not candidate.startswith('basn'):
   1467                 continue
   1468             candi = candidate.replace('n', 'i')
   1469             if candi not in _pngsuite:
   1470                 continue
   1471             print 'adam7 read', candidate
   1472             straight = Reader(bytes=_pngsuite[candidate])
   1473             adam7 = Reader(bytes=_pngsuite[candi])
   1474             straight = straight.read()[2]
   1475             adam7 = adam7.read()[2]
   1476             self.assertEqual(map(list, straight), map(list, adam7))
   1477 
   1478     def testAdam7write(self):
   1479         for name, bytes in _pngsuite.items():
   1480             if name[3:5] not in ('n0', 'n2', 'n4', 'n6'):
   1481                 continue
   1482             it = Reader(bytes=bytes)
   1483             x, y, pixels, meta = it.read()
   1484             pngi = topngbytes('adam7wn' + name + '.png', pixels, x=x, y=y, bitdepth=it.bitdepth, greyscale=it.greyscale, alpha=it.alpha, transparent=it.transparent, interlace=False)
   1485             x, y, ps, meta = Reader(bytes=pngi).read()
   1486             it = Reader(bytes=bytes)
   1487             x, y, pixels, meta = it.read()
   1488             pngs = topngbytes('adam7wi' + name + '.png', pixels, x=x, y=y, bitdepth=it.bitdepth, greyscale=it.greyscale, alpha=it.alpha, transparent=it.transparent, interlace=True)
   1489             x, y, pi, meta = Reader(bytes=pngs).read()
   1490             self.assertEqual(map(list, ps), map(list, pi))
   1491 
   1492     def testPGMin(self):
   1493 
   1494         def do():
   1495             return _main(['testPGMin'])
   1496 
   1497         s = BytesIO()
   1498         s.write(strtobytes('P5 2 2 3\n'))
   1499         s.write(strtobytes('\x00\x01\x02\x03'))
   1500         s.flush()
   1501         s.seek(0)
   1502         o = BytesIO()
   1503         testWithIO(s, o, do)
   1504         r = Reader(bytes=o.getvalue())
   1505         x, y, pixels, meta = r.read()
   1506         self.assertTrue(r.greyscale)
   1507         self.assertEqual(r.bitdepth, 2)
   1508 
   1509     def testPAMin(self):
   1510 
   1511         def do():
   1512             return _main(['testPAMin'])
   1513 
   1514         s = BytesIO()
   1515         s.write(strtobytes('P7\nWIDTH 3\nHEIGHT 1\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n'))
   1516         flat = [255,
   1517          0,
   1518          0,
   1519          255,
   1520          0,
   1521          255,
   1522          0,
   1523          120,
   1524          0,
   1525          0,
   1526          255,
   1527          30]
   1528         asbytes = seqtobytes(flat)
   1529         s.write(asbytes)
   1530         s.flush()
   1531         s.seek(0)
   1532         o = BytesIO()
   1533         testWithIO(s, o, do)
   1534         r = Reader(bytes=o.getvalue())
   1535         x, y, pixels, meta = r.read()
   1536         self.assertTrue(r.alpha)
   1537         self.assertTrue(not r.greyscale)
   1538         self.assertEqual(list(itertools.chain(*pixels)), flat)
   1539 
   1540     def testLA4(self):
   1541         bytes = topngbytes('la4.png', [[5, 12]], 1, 1, greyscale=True, alpha=True, bitdepth=4)
   1542         sbit = Reader(bytes=bytes).chunk('sBIT')[1]
   1543         self.assertEqual(sbit, strtobytes('\x04\x04'))
   1544 
   1545     def testPNMsbit(self):
   1546 
   1547         def do():
   1548             return _main(['testPNMsbit'])
   1549 
   1550         s = BytesIO()
   1551         s.write(strtobytes('P6 8 1 1\n'))
   1552         for pixel in range(8):
   1553             s.write(struct.pack('<I', 16513 * pixel & 65793)[:3])
   1554 
   1555         s.flush()
   1556         s.seek(0)
   1557         o = BytesIO()
   1558         testWithIO(s, o, do)
   1559         r = Reader(bytes=o.getvalue())
   1560         sbit = r.chunk('sBIT')[1]
   1561         self.assertEqual(sbit, strtobytes('\x01\x01\x01'))
   1562 
   1563     def testLtrns0(self):
   1564         return self.helperLtrns(0)
   1565 
   1566     def testLtrns1(self):
   1567         return self.helperLtrns((0,))
   1568 
   1569     def helperLtrns(self, transparent):
   1570         pixels = zip([0,
   1571          56,
   1572          76,
   1573          84,
   1574          92,
   1575          64,
   1576          56,
   1577          0])
   1578         o = BytesIO()
   1579         w = Writer(8, 8, greyscale=True, bitdepth=1, transparent=transparent)
   1580         w.write_packed(o, pixels)
   1581         r = Reader(bytes=o.getvalue())
   1582         x, y, pixels, meta = r.asDirect()
   1583         self.assertTrue(meta['alpha'])
   1584         self.assertTrue(meta['greyscale'])
   1585         self.assertEqual(meta['bitdepth'], 1)
   1586 
   1587     def testWinfo(self):
   1588         r = Reader(bytes=_pngsuite['basn2c16'])
   1589         info = r.read()[3]
   1590         w = Writer(**info)
   1591 
   1592     def testPackedIter(self):
   1593         w = Writer(16, 2, greyscale=True, alpha=False, bitdepth=1)
   1594         o = BytesIO()
   1595         w.write_packed(o, [itertools.chain([10], [170]), itertools.chain([15], [255])])
   1596         r = Reader(bytes=o.getvalue())
   1597         x, y, pixels, info = r.asDirect()
   1598         pixels = list(pixels)
   1599         self.assertEqual(len(pixels), 2)
   1600         self.assertEqual(len(pixels[0]), 16)
   1601 
   1602     def testInterlacedArray(self):
   1603         r = Reader(bytes=_pngsuite['basi0g08'])
   1604         list(r.read()[2])[0].tostring
   1605 
   1606     def testTrnsArray(self):
   1607         r = Reader(bytes=_pngsuite['tbrn2c08'])
   1608         list(r.asDirect()[2])[0].tostring
   1609 
   1610     def testEmpty(self):
   1611         r = Reader(bytes='')
   1612         self.assertRaises(FormatError, r.asDirect)
   1613 
   1614     def testSigOnly(self):
   1615         r = Reader(bytes=_signature)
   1616         self.assertRaises(FormatError, r.asDirect)
   1617 
   1618     def testExtraPixels(self):
   1619 
   1620         def eachchunk(chunk):
   1621             if chunk[0] != 'IDAT':
   1622                 return chunk
   1623             data = zlib.decompress(chunk[1])
   1624             data += strtobytes('\x00garbage')
   1625             data = zlib.compress(data)
   1626             chunk = (chunk[0], data)
   1627             return chunk
   1628 
   1629         self.assertRaises(FormatError, self.helperFormat, eachchunk)
   1630 
   1631     def testNotEnoughPixels(self):
   1632 
   1633         def eachchunk(chunk):
   1634             if chunk[0] != 'IDAT':
   1635                 return chunk
   1636             data = zlib.decompress(chunk[1])
   1637             data = data[:-1]
   1638             data = zlib.compress(data)
   1639             return (chunk[0], data)
   1640 
   1641         self.assertRaises(FormatError, self.helperFormat, eachchunk)
   1642 
   1643     def helperFormat(self, f):
   1644         r = Reader(bytes=_pngsuite['basn0g01'])
   1645         o = BytesIO()
   1646 
   1647         def newchunks():
   1648             for chunk in r.chunks():
   1649                 yield f(chunk)
   1650 
   1651         write_chunks(o, newchunks())
   1652         r = Reader(bytes=o.getvalue())
   1653         return list(r.asDirect()[2])
   1654 
   1655     def testBadFilter(self):
   1656 
   1657         def eachchunk(chunk):
   1658             if chunk[0] != 'IDAT':
   1659                 return chunk
   1660             data = zlib.decompress(chunk[1])
   1661             data = strtobytes('\x99') + data[1:]
   1662             data = zlib.compress(data)
   1663             return (chunk[0], data)
   1664 
   1665         self.assertRaises(FormatError, self.helperFormat, eachchunk)
   1666 
   1667     def testFlat(self):
   1668         import hashlib
   1669         r = Reader(bytes=_pngsuite['basn0g02'])
   1670         x, y, pixel, meta = r.read_flat()
   1671         d = hashlib.md5(seqtobytes(pixel)).digest()
   1672         self.assertEqual(_enhex(d), '255cd971ab8cd9e7275ff906e5041aa0')
   1673 
   1674     def testfromarray(self):
   1675         img = from_array([[0, 51, 102], [255, 204, 153]], 'L')
   1676         img.save('testfromarray.png')
   1677 
   1678     def testfromarrayL16(self):
   1679         img = from_array(group(range(65536), 256), 'L;16')
   1680         img.save('testL16.png')
   1681 
   1682     def testfromarrayRGB(self):
   1683         img = from_array([[0,
   1684           0,
   1685           0,
   1686           0,
   1687           0,
   1688           1,
   1689           0,
   1690           1,
   1691           0,
   1692           0,
   1693           1,
   1694           1], [1,
   1695           0,
   1696           0,
   1697           1,
   1698           0,
   1699           1,
   1700           1,
   1701           1,
   1702           0,
   1703           1,
   1704           1,
   1705           1]], 'RGB;1')
   1706         o = BytesIO()
   1707         img.save(o)
   1708 
   1709     def testfromarrayIter(self):
   1710         import itertools
   1711         i = itertools.islice(itertools.count(10), 20)
   1712         i = itertools.imap(lambda x: [x, x, x], i)
   1713         img = from_array(i, 'RGB;5', dict(height=20))
   1714         f = open('testiter.png', 'wb')
   1715         img.save(f)
   1716         f.close()
   1717 
   1718     def testNumpyuint16(self):
   1719         try:
   1720             import numpy
   1721         except ImportError:
   1722             print >> sys.stderr, 'skipping numpy test'
   1723             return
   1724 
   1725         rows = [map(numpy.uint16, range(0, 65536, 21845))]
   1726         b = topngbytes('numpyuint16.png', rows, 4, 1, greyscale=True, alpha=False, bitdepth=16)
   1727 
   1728     def testNumpyuint8(self):
   1729         try:
   1730             import numpy
   1731         except ImportError:
   1732             print >> sys.stderr, 'skipping numpy test'
   1733             return
   1734 
   1735         rows = [map(numpy.uint8, range(0, 256, 85))]
   1736         b = topngbytes('numpyuint8.png', rows, 4, 1, greyscale=True, alpha=False, bitdepth=8)
   1737 
   1738     def testNumpybool(self):
   1739         try:
   1740             import numpy
   1741         except ImportError:
   1742             print >> sys.stderr, 'skipping numpy test'
   1743             return
   1744 
   1745         rows = [map(numpy.bool, [0, 1])]
   1746         b = topngbytes('numpybool.png', rows, 2, 1, greyscale=True, alpha=False, bitdepth=1)
   1747 
   1748     def testNumpyarray(self):
   1749         try:
   1750             import numpy
   1751         except ImportError:
   1752             print >> sys.stderr, 'skipping numpy test'
   1753             return
   1754 
   1755         pixels = numpy.array([[0, 21845], [21845, 43690]], numpy.uint16)
   1756         img = from_array(pixels, 'L')
   1757         img.save('testnumpyL16.png')
   1758 
   1759 
   1760 def _dehex(s):
   1761     import re
   1762     import binascii
   1763     s = re.sub('[^a-fA-F\\d]', '', s)
   1764     return binascii.unhexlify(strtobytes(s))
   1765 
   1766 
   1767 def _enhex(s):
   1768     import binascii
   1769     return bytestostr(binascii.hexlify(s))
   1770 
   1771 
   1772 _pngsuite = {'basi0g01': _dehex('\n89504e470d0a1a0a0000000d49484452000000200000002001000000012c0677\ncf0000000467414d41000186a031e8965f0000009049444154789c2d8d310ec2\n300c45dfc682c415187a00a42e197ab81e83b127e00c5639001363a580d8582c\n65c910357c4b78b0bfbfdf4f70168c19e7acb970a3f2d1ded9695ce5bf5963df\nd92aaf4c9fd927ea449e6487df5b9c36e799b91bdf082b4d4bd4014fe4014b01\nab7a17aee694d28d328a2d63837a70451e1648702d9a9ff4a11d2f7a51aa21e5\na18c7ffd0094e3511d661822f20000000049454e44ae426082\n'),
   1773  'basi0g02': _dehex('\n89504e470d0a1a0a0000000d49484452000000200000002002000000016ba60d\n1f0000000467414d41000186a031e8965f0000005149444154789c635062e860\n00e17286bb609c93c370ec189494960631366e4467b3ae675dcf10f521ea0303\n90c1ca006444e11643482064114a4852c710baea3f18c31918020c30410403a6\n0ac1a09239009c52804d85b6d97d0000000049454e44ae426082\n'),
   1774  'basi0g04': _dehex('\n89504e470d0a1a0a0000000d4948445200000020000000200400000001e4e6f8\nbf0000000467414d41000186a031e8965f000000ae49444154789c658e5111c2\n301044171c141c141c041c843a287510ea20d441c041c141c141c04191102454\n03994998cecd7edcecedbb9bdbc3b2c2b6457545fbc4bac1be437347f7c66a77\n3c23d60db15e88f5c5627338a5416c2e691a9b475a89cd27eda12895ae8dfdab\n43d61e590764f5c83a226b40d669bec307f93247701687723abf31ff83a2284b\na5b4ae6b63ac6520ad730ca4ed7b06d20e030369bd6720ed383290360406d24e\n13811f2781eba9d34d07160000000049454e44ae426082\n'),
   1775  'basi0g08': _dehex('\n89504e470d0a1a0a0000000d4948445200000020000000200800000001211615\nbe0000000467414d41000186a031e8965f000000b549444154789cb5905d0ac2\n3010849dbac81c42c47bf843cf253e8878b0aa17110f214bdca6be240f5d21a5\n94ced3e49bcd322c1624115515154998aa424822a82a5624a1aa8a8b24c58f99\n999908130989a04a00d76c2c09e76cf21adcb209393a6553577da17140a2c59e\n70ecbfa388dff1f03b82fb82bd07f05f7cb13f80bb07ad2fd60c011c3c588eef\nf1f4e03bbec7ce832dca927aea005e431b625796345307b019c845e6bfc3bb98\n769d84f9efb02ea6c00f9bb9ff45e81f9f280000000049454e44ae426082\n'),
   1776  'basi0g16': _dehex('\n89504e470d0a1a0a0000000d49484452000000200000002010000000017186c9\nfd0000000467414d41000186a031e8965f000000e249444154789cb5913b0ec2\n301044c7490aa8f85d81c3e4301c8f53a4ca0da8902c8144b3920b4043111282\n23bc4956681a6bf5fc3c5a3ba0448912d91a4de2c38dd8e380231eede4c4f7a1\n4677700bec7bd9b1d344689315a3418d1a6efbe5b8305ba01f8ff4808c063e26\nc60d5c81edcf6c58c535e252839e93801b15c0a70d810ae0d306b205dc32b187\n272b64057e4720ff0502154034831520154034c3df81400510cdf0015c86e5cc\n5c79c639fddba9dcb5456b51d7980eb52d8e7d7fa620a75120d6064641a05120\nb606771a05626b401a05f1f589827cf0fe44c1f0bae0055698ee8914fffffe00\n00000049454e44ae426082\n'),
   1777  'basi2c08': _dehex('\n89504e470d0a1a0a0000000d49484452000000200000002008020000018b1fdd\n350000000467414d41000186a031e8965f000000f249444154789cd59341aa04\n210c44abc07b78133d59d37333bd89d76868b566d10cf4675af8596431a11662\n7c5688919280e312257dd6a0a4cf1a01008ee312a5f3c69c37e6fcc3f47e6776\na07f8bdaf5b40feed2d33e025e2ff4fe2d4a63e1a16d91180b736d8bc45854c5\n6d951863f4a7e0b66dcf09a900f3ffa2948d4091e53ca86c048a64390f662b50\n4a999660ced906182b9a01a8be00a56404a6ede182b1223b4025e32c4de34304\n63457680c93aada6c99b73865aab2fc094920d901a203f5ddfe1970d28456783\n26cffbafeffcd30654f46d119be4793f827387fc0d189d5bc4d69a3c23d45a7f\ndb803146578337df4d0a3121fc3d330000000049454e44ae426082\n'),
   1778  'basi2c16': _dehex('\n89504e470d0a1a0a0000000d4948445200000020000000201002000001db8f01\n760000000467414d41000186a031e8965f0000020a49444154789cd5962173e3\n3010853fcf1838cc61a1818185a53e56787fa13fa130852e3b5878b4b0b03081\nb97f7030070b53e6b057a0a8912bbb9163b9f109ececbc59bd7dcf2b45492409\nd66f00eb1dd83cb5497d65456aeb8e1040913b3b2c04504c936dd5a9c7e2c6eb\nb1b8f17a58e8d043da56f06f0f9f62e5217b6ba3a1b76f6c9e99e8696a2a72e2\nc4fb1e4d452e92ec9652b807486d12b6669be00db38d9114b0c1961e375461a5\n5f76682a85c367ad6f682ff53a9c2a353191764b78bb07d8ddc3c97c1950f391\n6745c7b9852c73c2f212605a466a502705c8338069c8b9e84efab941eb393a97\nd4c9fd63148314209f1c1d3434e847ead6380de291d6f26a25c1ebb5047f5f24\nd85c49f0f22cc1d34282c72709cab90477bf25b89d49f0f351822297e0ea9704\nf34c82bc94002448ede51866e5656aef5d7c6a385cb4d80e6a538ceba04e6df2\n480e9aa84ddedb413bb5c97b3838456df2d4fec2c7a706983e7474d085fae820\na841776a83073838973ac0413fea2f1dc4a06e71108fda73109bdae48954ad60\nbf867aac3ce44c7c1589a711cf8a81df9b219679d96d1cec3d8bbbeaa2012626\ndf8c7802eda201b2d2e0239b409868171fc104ba8b76f10b4da09f6817ffc609\nc413ede267fd1fbab46880c90f80eccf0013185eb48b47ba03df2bdaadef3181\ncb8976f18e13188768170f98c0f844bb78cb04c62ddac59d09fc3fa25dfc1da4\n14deb3df1344f70000000049454e44ae426082\n'),
   1779  'basi3p08': _dehex('\n89504e470d0a1a0a0000000d494844520000002000000020080300000133a3ba\n500000000467414d41000186a031e8965f00000300504c5445224400f5ffed77\nff77cbffff110a003a77002222ffff11ff110000222200ffac5566ff66ff6666\nff01ff221200dcffffccff994444ff005555220000cbcbff44440055ff55cbcb\n00331a00ffecdcedffffe4ffcbffdcdc44ff446666ff330000442200ededff66\n6600ffa444ffffaaeded0000cbcbfefffffdfffeffff0133ff33552a000101ff\n8888ff00aaaa010100440000888800ffe4cbba5b0022ff22663200ffff99aaaa\nff550000aaaa00cb630011ff11d4ffaa773a00ff4444dc6b0066000001ff0188\n4200ecffdc6bdc00ffdcba00333300ed00ed7300ffff88994a0011ffff770000\nff8301ffbabafe7b00fffeff00cb00ff999922ffff880000ffff77008888ffdc\nff1a33000000aa33ffff009900990000000001326600ffbaff44ffffffaaff00\n770000fefeaa00004a9900ffff66ff22220000998bff1155ffffff0101ff88ff\n005500001111fffffefffdfea4ff4466ffffff66ff003300ffff55ff77770000\n88ff44ff00110077ffff006666ffffed000100fff5ed1111ffffff44ff22ffff\neded11110088ffff00007793ff2200dcdc3333fffe00febabaff99ffff333300\n63cb00baba00acff55ffffdcffff337bfe00ed00ed5555ffaaffffdcdcff5555\n00000066dcdc00dc00dc83ff017777fffefeffffffcbff5555777700fefe00cb\n00cb0000fe010200010000122200ffff220044449bff33ffd4aa0000559999ff\n999900ba00ba2a5500ffcbcbb4ff66ff9b33ffffbaaa00aa42880053aa00ffaa\naa0000ed00babaffff1100fe00000044009999990099ffcc99ba000088008800\ndc00ff93220000dcfefffeaa5300770077020100cb0000000033ffedff00ba00\nff3333edffedffc488bcff7700aa00660066002222dc0000ffcbffdcffdcff8b\n110000cb00010155005500880000002201ffffcbffcbed0000ff88884400445b\nba00ffbc77ff99ff006600baffba00777773ed00fe00003300330000baff77ff\n004400aaffaafffefe000011220022c4ff8800eded99ff99ff55ff002200ffb4\n661100110a1100ff1111dcffbabaffff88ff88010001ff33ffb98ed362000002\na249444154789c65d0695c0b001806f03711a9904a94d24dac63292949e5a810\nd244588a14ca5161d1a1323973252242d62157d12ae498c8124d25ca3a11398a\n16e55a3cdffab0ffe7f77d7fcff3528645349b584c3187824d9d19d4ec2e3523\n9eb0ae975cf8de02f2486d502191841b42967a1ad49e5ddc4265f69a899e26b5\ne9e468181baae3a71a41b95669da8df2ea3594c1b31046d7b17bfb86592e4cbe\nd89b23e8db0af6304d756e60a8f4ad378bdc2552ae5948df1d35b52143141533\n33bbbbababebeb3b3bc9c9c9c6c6c0c0d7b7b535323225a5aa8a02024a4bedec\n0a0a2a2bcdcd7d7cf2f3a9a9c9cdcdd8b8adcdd5b5ababa828298982824a4ab2\nb21212acadbdbc1414e2e24859b9a72730302f4f49292c4c57373c9c0a0b7372\n8c8c1c1c3a3a92936d6dfdfd293e3e26262a4a4eaea2424b4b5fbfbc9c323278\n3c0b0ba1303abaae8ecdeeed950d6669a9a7a7a141d4de9e9d5d5cdcd2229b94\nc572716132f97cb1d8db9bc3110864a39795d9db6b6a26267a7a9a98d4d6a6a7\ncb76090ef6f030354d4d75766e686030545464cb393a1a1ac6c68686eae8f8f9\na9aa4644c8b66d6e1689dcdd2512a994cb35330b0991ad9f9b6b659596a6addd\nd8282fafae5e5323fb8f41d01f76c22fd8061be01bfc041a0323e1002c81cd30\n0b9ec027a0c930014ec035580fc3e112bc069a0b53e11c0c8095f00176c163a0\ne5301baec06a580677600ddc05ba0f13e120bc81a770133ec355a017300d4ec2\n0c7800bbe1219c02fa08f3e13c1c85dbb00a2ec05ea0dff00a6ec15a98027360\n070c047a06d7e1085c84f1b014f6c03fa0b33018b6c0211801ebe018fc00da0a\n6f61113c877eb01d4ec317a085700f26c130f80efbe132bc039a0733e106fc81\nf7f017f6c10aa0d1300a0ec374780943e1382c06fa0a9b60238c83473016cec0\n02f80f73fefe1072afc1e50000000049454e44ae426082\n'),
   1780  'basi6a08': _dehex('\n89504e470d0a1a0a0000000d4948445200000020000000200806000001047d4a\n620000000467414d41000186a031e8965f0000012049444154789cc595414ec3\n3010459fa541b8bbb26641b8069b861e8b4d12c1c112c1452a710a2a65d840d5\n949041fc481ec98ae27c7f3f8d27e3e4648047600fec0d1f390fbbe2633a31e2\n9389e4e4ea7bfdbf3d9a6b800ab89f1bd6b553cfcbb0679e960563d72e0a9293\nb7337b9f988cc67f5f0e186d20e808042f1c97054e1309da40d02d7e27f92e03\n6cbfc64df0fc3117a6210a1b6ad1a00df21c1abcf2a01944c7101b0cb568a001\n909c9cf9e399cf3d8d9d4660a875405d9a60d000b05e2de55e25780b7a5268e0\n622118e2399aab063a815808462f1ab86890fc2e03e48bb109ded7d26ce4bf59\n0db91bac0050747fec5015ce80da0e5700281be533f0ce6d5900b59bcb00ea6d\n200314cf801faab200ea752803a8d7a90c503a039f824a53f4694e7342000000\n0049454e44ae426082\n'),
   1781  'basn0g01': _dehex('\n89504e470d0a1a0a0000000d49484452000000200000002001000000005b0147\n590000000467414d41000186a031e8965f0000005b49444154789c2dccb10903\n300c05d1ebd204b24a200b7a346f90153c82c18d0a61450751f1e08a2faaead2\na4846ccea9255306e753345712e211b221bf4b263d1b427325255e8bdab29e6f\n6aca30692e9d29616ee96f3065f0bf1f1087492fd02f14c90000000049454e44\nae426082\n'),
   1782  'basn0g02': _dehex('\n89504e470d0a1a0a0000000d49484452000000200000002002000000001ca13d\n890000000467414d41000186a031e8965f0000001f49444154789c6360085df5\n1f8cf1308850c20053868f0133091f6390b90700bd497f818b0989a900000000\n49454e44ae426082\n'),
   1783  'Basn0g03': _dehex('\n89504e470d0a1a0a0000000d494844520000002000000020040000000093e1c8\n2900000001734249540371d88211000000fd49444154789c6d90d18906210c84\nc356f22356b2889588604301b112112b11d94a96bb495cf7fe87f32d996f2689\n44741cc658e39c0b118f883e1f63cc89dafbc04c0f619d7d898396c54b875517\n83f3a2e7ac09a2074430e7f497f00f1138a5444f82839c5206b1f51053cca968\n63258821e7f2b5438aac16fbecc052b646e709de45cf18996b29648508728612\n952ca606a73566d44612b876845e9a347084ea4868d2907ff06be4436c4b41a3\na3e1774285614c5affb40dbd931a526619d9fa18e4c2be420858de1df0e69893\na0e3e5523461be448561001042b7d4a15309ce2c57aef2ba89d1c13794a109d7\nb5880aa27744fc5c4aecb5e7bcef5fe528ec6293a930690000000049454e44ae\n426082\n'),
   1784  'basn0g04': _dehex('\n89504e470d0a1a0a0000000d494844520000002000000020040000000093e1c8\n290000000467414d41000186a031e8965f0000004849444154789c6360601014\n545232367671090d4d4b2b2f6720430095dbd1418e002a77e64c720450b9ab56\n912380caddbd9b1c0154ee9933e408a072efde25470095fbee1d1902001f14ee\n01eaff41fa0000000049454e44ae426082\n'),
   1785  'basn0g08': _dehex('\n89504e470d0a1a0a0000000d4948445200000020000000200800000000561125\n280000000467414d41000186a031e8965f0000004149444154789c6364602400\n1408c8b30c05058c0f0829f8f71f3f6079301c1430ca11906764a2795c0c0605\n8c8ff0cafeffcff887e67131181430cae0956564040050e5fe7135e2d8590000\n000049454e44ae426082\n'),
   1786  'basn0g16': _dehex('\n89504e470d0a1a0a0000000d49484452000000200000002010000000000681f9\n6b0000000467414d41000186a031e8965f0000005e49444154789cd5d2310ac0\n300c4351395bef7fc6dca093c0287b32d52a04a3d98f3f3880a7b857131363a0\n3a82601d089900dd82f640ca04e816dc06422640b7a03d903201ba05b7819009\nd02d680fa44c603f6f07ec4ff41938cf7f0016d84bd85fae2b9fd70000000049\n454e44ae426082\n'),
   1787  'basn2c08': _dehex('\n89504e470d0a1a0a0000000d4948445200000020000000200802000000fc18ed\na30000000467414d41000186a031e8965f0000004849444154789cedd5c10900\n300c024085ec91fdb772133b442bf4a1f8cee12bb40d043b800a14f81ca0ede4\n7d4c784081020f4a871fc284071428f0a0743823a94081bb7077a3c00182b1f9\n5e0f40cf4b0000000049454e44ae426082\n'),
   1788  'basn2c16': _dehex('\n89504e470d0a1a0a0000000d4948445200000020000000201002000000ac8831\ne00000000467414d41000186a031e8965f000000e549444154789cd596c10a83\n301044a7e0417fcb7eb7fdadf6961e06039286266693cc7a188645e43dd6a08f\n1042003e2fe09aef6472737e183d27335fcee2f35a77b702ebce742870a23397\nf3edf2705dd10160f3b2815fe8ecf2027974a6b0c03f74a6e4192843e75c6c03\n35e8ec3202f5e84c0181bbe8cca967a00d9df3491bb040671f2e6087ce1c2860\n8d1e05f8c7ee0f1d00b667e70df44467ef26d01fbd9bc028f42860f71d188bce\nfb8d3630039dbd59601e7ab3c06cf428507f0634d039afdc80123a7bb1801e7a\nb1802a7a14c89f016d74ce331bf080ce9e08f8414f04bca133bfe642fe5e07bb\nc4ec0000000049454e44ae426082\n'),
   1789  'basn6a08': _dehex('\n89504e470d0a1a0a0000000d4948445200000020000000200806000000737a7a\nf40000000467414d41000186a031e8965f0000006f49444154789cedd6310a80\n300c46e12764684fa1f73f55048f21c4ddc545781d52e85028fc1f4d28d98a01\n305e7b7e9cffba33831d75054703ca06a8f90d58a0074e351e227d805c8254e3\n1bb0420f5cdc2e0079208892ffe2a00136a07b4007943c1004d900195036407f\n011bf00052201a9c160fb84c0000000049454e44ae426082\n'),
   1790  'cs3n3p08': _dehex('\n89504e470d0a1a0a0000000d494844520000002000000020080300000044a48a\nc60000000467414d41000186a031e8965f0000000373424954030303a392a042\n00000054504c544592ff0000ff9200ffff00ff0000dbff00ff6dffb600006dff\nb6ff00ff9200dbff000049ffff2400ff000024ff0049ff0000ffdb00ff4900ff\nb6ffff0000ff2400b6ffffdb000092ffff6d000024ffff49006dff00df702b17\n0000004b49444154789c85cac70182000000b1b3625754b0edbfa72324ef7486\n184ed0177a437b680bcdd0031c0ed00ea21f74852ed00a1c9ed0086da0057487\n6ed0121cd6d004bda0013a421ff803224033e177f4ae260000000049454e44ae\n426082\n'),
   1791  's09n3p02': _dehex('\n89504e470d0a1a0a0000000d49484452000000090000000902030000009dffee\n830000000467414d41000186a031e8965f000000037342495404040477f8b5a3\n0000000c504c544500ff000077ffff00ffff7700ff5600640000001f49444154\n789c63600002fbff0c0c56ab19182ca381581a4283f82071200000696505c36a\n437f230000000049454e44ae426082\n'),
   1792  'tbgn3p08': _dehex('\n89504e470d0a1a0a0000000d494844520000002000000020080300000044a48a\nc60000000467414d41000186a031e8965f00000207504c54457f7f7fafafafab\nabab110000222200737300999999510d00444400959500959595e6e600919191\n8d8d8d620d00898989666600b7b700911600000000730d007373736f6f6faaaa\n006b6b6b676767c41a00cccc0000f30000ef00d51e0055555567670000dd0051\n515100d1004d4d4de61e0038380000b700160d0d00ab00560d00090900009500\n009100008d003333332f2f2f2f2b2f2b2b000077007c7c001a05002b27000073\n002b2b2b006f00bb1600272727780d002323230055004d4d00cc1e00004d00cc\n1a000d00003c09006f6f00002f003811271111110d0d0d55554d090909001100\n4d0900050505000d00e2e200000900000500626200a6a6a6a2a2a29e9e9e8484\n00fb00fbd5d500801100800d00ea00ea555500a6a600e600e6f7f700e200e233\n0500888888d900d9848484c01a007777003c3c05c8c8008080804409007c7c7c\nbb00bbaa00aaa600a61e09056262629e009e9a009af322005e5e5e05050000ee\n005a5a5adddd00a616008d008d00e20016050027270088110078780000c40078\n00787300736f006f44444400aa00c81e004040406600663c3c3c090000550055\n1a1a00343434d91e000084004d004d007c004500453c3c00ea1e00222222113c\n113300331e1e1efb22001a1a1a004400afaf00270027003c001616161e001e0d\n160d2f2f00808000001e00d1d1001100110d000db7b7b7090009050005b3b3b3\n6d34c4230000000174524e530040e6d86600000001624b474402660b7c640000\n01f249444154789c6360c0048c8c58049100575f215ee92e6161ef109cd2a15e\n4b9645ce5d2c8f433aa4c24f3cbd4c98833b2314ab74a186f094b9c2c27571d2\n6a2a58e4253c5cda8559057a392363854db4d9d0641973660b0b0bb76bb16656\n06970997256877a07a95c75a1804b2fbcd128c80b482a0b0300f8a824276a9a8\nec6e61612b3e57ee06fbf0009619d5fac846ac5c60ed20e754921625a2daadc6\n1967e29e97d2239c8aec7e61fdeca9cecebef54eb36c848517164514af16169e\n866444b2b0b7b55534c815cc2ec22d89cd1353800a8473100a4485852d924a6a\n412adc74e7ad1016ceed043267238c901716f633a812022998a4072267c4af02\n92127005c0f811b62830054935ce017b38bf0948cc5c09955f030a24617d9d46\n63371fd940b0827931cbfdf4956076ac018b592f72d45594a9b1f307f3261b1a\n084bc2ad50018b1900719ba6ba4ca325d0427d3f6161449486f981144cf3100e\n2a5f2a1ce8683e4ddf1b64275240c8438d98af0c729bbe07982b8a1c94201dc2\nb3174c9820bcc06201585ad81b25b64a2146384e3798290c05ad280a18c0a62e\ne898260c07fca80a24c076cc864b777131a00190cdfa3069035eccbc038c30e1\n3e88b46d16b6acc5380d6ac202511c392f4b789aa7b0b08718765990111606c2\n9e854c38e5191878fbe471e749b0112bb18902008dc473b2b2e8e72700000000\n49454e44ae426082\n'),
   1793  'Tp2n3p08': _dehex('\n89504e470d0a1a0a0000000d494844520000002000000020080300000044a48a\nc60000000467414d41000186a031e8965f00000300504c544502ffff80ff05ff\n7f0703ff7f0180ff04ff00ffff06ff000880ff05ff7f07ffff06ff000804ff00\n0180ff02ffff03ff7f02ffff80ff0503ff7f0180ffff0008ff7f0704ff00ffff\n06ff000802ffffff7f0704ff0003ff7fffff0680ff050180ff04ff000180ffff\n0008ffff0603ff7f80ff05ff7f0702ffffff000880ff05ffff0603ff7f02ffff\nff7f070180ff04ff00ffff06ff000880ff050180ffff7f0702ffff04ff0003ff\n7fff7f0704ff0003ff7f0180ffffff06ff000880ff0502ffffffff0603ff7fff\n7f0702ffff04ff000180ff80ff05ff0008ff7f07ffff0680ff0504ff00ff0008\n0180ff03ff7f02ffff02ffffffff0604ff0003ff7f0180ffff000880ff05ff7f\n0780ff05ff00080180ff02ffffff7f0703ff7fffff0604ff00ff7f07ff0008ff\nff0680ff0504ff0002ffff0180ff03ff7fff0008ffff0680ff0504ff000180ff\n02ffff03ff7fff7f070180ff02ffff04ff00ffff06ff0008ff7f0780ff0503ff\n7fffff06ff0008ff7f0780ff0502ffff03ff7f0180ff04ff0002ffffff7f07ff\nff0604ff0003ff7fff00080180ff80ff05ffff0603ff7f0180ffff000804ff00\n80ff0502ffffff7f0780ff05ffff0604ff000180ffff000802ffffff7f0703ff\n7fff0008ff7f070180ff03ff7f02ffff80ff05ffff0604ff00ff0008ffff0602\nffff0180ff04ff0003ff7f80ff05ff7f070180ff04ff00ff7f0780ff0502ffff\nff000803ff7fffff0602ffffff7f07ffff0680ff05ff000804ff0003ff7f0180\nff02ffff0180ffff7f0703ff7fff000804ff0080ff05ffff0602ffff04ff00ff\nff0603ff7fff7f070180ff80ff05ff000803ff7f0180ffff7f0702ffffff0008\n04ff00ffff0680ff0503ff7f0180ff04ff0080ff05ffff06ff000802ffffff7f\n0780ff05ff0008ff7f070180ff03ff7f04ff0002ffffffff0604ff00ff7f07ff\n000880ff05ffff060180ff02ffff03ff7f80ff05ffff0602ffff0180ff03ff7f\n04ff00ff7f07ff00080180ffff000880ff0502ffff04ff00ff7f0703ff7fffff\n06ff0008ffff0604ff00ff7f0780ff0502ffff03ff7f0180ffdeb83387000000\nf874524e53000000000000000008080808080808081010101010101010181818\n1818181818202020202020202029292929292929293131313131313131393939\n393939393941414141414141414a4a4a4a4a4a4a4a52525252525252525a5a5a\n5a5a5a5a5a62626262626262626a6a6a6a6a6a6a6a73737373737373737b7b7b\n7b7b7b7b7b83838383838383838b8b8b8b8b8b8b8b94949494949494949c9c9c\n9c9c9c9c9ca4a4a4a4a4a4a4a4acacacacacacacacb4b4b4b4b4b4b4b4bdbdbd\nbdbdbdbdbdc5c5c5c5c5c5c5c5cdcdcdcdcdcdcdcdd5d5d5d5d5d5d5d5dedede\ndededededee6e6e6e6e6e6e6e6eeeeeeeeeeeeeeeef6f6f6f6f6f6f6f6b98ac5\nca0000012c49444154789c6360e7169150d230b475f7098d4ccc28a96ced9e32\n63c1da2d7b8e9fb97af3d1fb8f3f18e8a0808953544a4dd7c4c2c9233c2621bf\nb4aab17fdacce5ab36ee3a72eafaad87efbefea68702362e7159652d031b07cf\nc0b8a4cce28aa68e89f316aedfb4ffd0b92bf79fbcfcfe931e0a183904e55435\n8decdcbcc22292b3caaadb7b27cc5db67af3be63e72fdf78fce2d31f7a2860e5\n119356d037b374f10e8a4fc92eaa6fee99347fc9caad7b0f9ebd74f7c1db2fbf\ne8a180995f484645dbdccad12f38363dafbcb6a573faeca5ebb6ed3e7ce2c29d\ne76fbefda38702063e0149751d537b67ff80e8d4dcc29a86bea97316add9b0e3\nc0e96bf79ebdfafc971e0a587885e515f58cad5d7d43a2d2720aeadaba26cf5a\nbc62fbcea3272fde7efafac37f3a28000087c0fe101bc2f85f0000000049454e\n44ae426082\n'),
   1794  'tbbn1g04': _dehex('\n89504e470d0a1a0a0000000d494844520000002000000020040000000093e1c8\n290000000467414d41000186a031e8965f0000000274524e530007e8f7589b00\n000002624b47440000aa8d23320000013e49444154789c55d1cd4b024118c7f1\nefbe6419045b6a48a72d352808b435284f9187ae9b098627a1573a19945beba5\ne8129e8222af11d81e3a4545742de8ef6af6d5762e0fbf0fc33c33f36085cb76\nbc4204778771b867260683ee57e13f0c922df5c719c2b3b6c6c25b2382cea4b9\n9f7d4f244370746ac71f4ca88e0f173a6496749af47de8e44ba8f3bf9bdfa98a\n0faf857a7dd95c7dc8d7c67c782c99727997f41eb2e3c1e554152465bb00fe8e\nb692d190b718d159f4c0a45c4435915a243c58a7a4312a7a57913f05747594c6\n46169866c57101e4d4ce4d511423119c419183a3530cc63db88559ae28e7342a\n1e9c8122b71139b8872d6e913153224bc1f35b60e4445bd4004e20ed6682c759\n1d9873b3da0fbf50137dc5c9bde84fdb2ec8bde1189e0448b63584735993c209\n7a601bd2710caceba6158797285b7f2084a2f82c57c01a0000000049454e44ae\n426082\n'),
   1795  'tbrn2c08': _dehex('\n89504e470d0a1a0a0000000d4948445200000020000000200802000000fc18ed\na30000000467414d41000186a031e8965f0000000674524e53007f007f007f8a\n33334f00000006624b474400ff0000000033277cf3000004d649444154789cad\n965f68537714c73fd912d640235e692f34d0406fa0c1663481045ab060065514\n56660a295831607df0a1488715167060840a1614e6431e9cb34fd2c00a762c85\nf6a10f816650c13b0cf40612e1822ddc4863bd628a8924d23d6464f9d3665dd9\nf7e977ce3dbff3cd3939bfdfef6bb87dfb364782dbed065ebe7cd93acc78b4ec\na228debd7bb7bfbfbfbbbbfb7f261045311a8d261209405194274f9ea4d3e916\nf15f1c3eb5dd6e4fa5fecce526239184a2b0b8486f6f617171b1f5ae4311381c\n8e57af5e5dbd7a351088150a78bd389d44222c2f93cdfe66b7db8f4ee07038b6\nb6b6bebf766d7e7e7e60a06432313b4ba984c3c1c4049a46b95c5a58583822c1\ndbb76f27272733d1b9df853c3030c0f232562b9108cf9eb1b888d7cbf030abab\n31abd5fa1f08dc6ef7e7cf9f1f3f7e1c8944745d4f1400c62c001313acad21cb\nb8dd2c2c603271eb1640341aad4c6d331aa7e8c48913a150a861307ecc11e964\n74899919bc5e14e56fffc404f1388502f178dceff7ef4bf0a5cfe7abb533998c\ne5f9ea2f1dd88c180d64cb94412df3dd57e83a6b3b3c7a84c98420100c72fd3a\n636348bae726379fe69e8e8d8dbd79f3a6558b0607079796965256479b918085\n7b02db12712b6181950233023f3f647494ee6e2e5ea45864cce5b8a7fe3acffc\n3aebb22c2bd5d20e22d0757d7b7bbbbdbd3d94a313bed1b0aa3cd069838b163a\n8d4c59585f677292d0b84d9a995bd337def3fe6bbe5e6001989b9b6bfe27ea08\n36373781542ab56573248b4c5bc843ac4048c7ab21aa24ca00534c25482828a3\n8c9ee67475bbaaaab22cb722c8e57240a150301a8d219de94e44534d7d90e885\n87acb0e2c4f9800731629b6c5ee14a35a6b9887d2a0032994cb9cf15dbe59650\nff7b46a04c9a749e7cc5112214266cc65c31354d5b5d5d3d90209bcd5616a552\na95c2e87f2a659bd9ee01c2cd73964e438f129a6aa9e582c363838b80f81d7eb\n5555b56a2a8ad2d9d7affd0409f8015c208013fea00177b873831b0282c964f2\n783c1e8fa7582cee5f81a669b5e6eeeeaee58e8559b0c233d8843c7c0b963a82\n34e94b5cb2396d7d7d7db22c8ba258fb0afd43f0e2c58b919191ba9de9b4d425\n118329b0c3323c8709d02041b52b4ea7f39de75d2a934a2693c0a953a76a93d4\n5d157ebf7f6565a5542a553df97c5e10045dd731c130b86113cc300cbd489224\n08422a952a140a95788fc763b1d41558d7a2d7af5f5fb870a1d6a3aaaacd6603\n18802da84c59015bd2e6897b745d9765b99a1df0f97c0daf74e36deaf7fbcd66\n73ad2797cb89a2c839880188a2e8743a8bc5a22ccbba5e376466b3b9bdbdbd21\n6123413a9d0e0402b51e4dd3bababa788eb022b85caeb6b6364551b6b7b76942\n43f7f727007a7a7a04a1ee8065b3595fde2768423299ac1ec6669c3973e65004\nc0f8f878ad69341a33994ced2969c0d0d0502412f9f8f163f3a7fd654b474787\n288ad53e74757535df6215b85cae60302849d2410aecc037f9f2e5cbd5b5c160\n680eb0dbede170381c0e7ff8f0a185be3b906068684892a4ca7a6f6faff69328\n8ad3d3d3f7efdfdfdbdbfb57e96868a14d0d0643381c96242997cbe5f3794010\n84603078fcf8f1d6496bd14a3aba5c2ea7d369341a5555b5582c8140e0fcf9f3\n1b1b1b87cf4eeb0a8063c78e45a3d19e9e1ebfdfdf5a831e844655d18093274f\n9e3d7bf6d3a74f3b3b3b47c80efc05ff7af28fefb70d9b0000000049454e44ae\n426082\n'),
   1796  'basn6a16': _dehex('\n89504e470d0a1a0a0000000d494844520000002000000020100600000023eaa6\nb70000000467414d41000186a031e8965f00000d2249444154789cdd995f6c1c\nd775c67ff38fb34b724d2ee55a8e4b04a0ac87049100cab4dbd8c6528902cb4d\n10881620592e52d4325ac0905bc98a94025e71fd622cb5065ac98a0c283050c0\n728a00b6e542a1d126885cd3298928891d9a0444037e904434951d4b90b84b2f\nc9dde1fcebc33977a95555348f411e16dfce9d3b77ee77eebde77ce78c95a669\n0ad07c17009a13edd898b87dfb1fcb7d2b4d1bff217f33df80deb1e6267df0ff\nc1e6e6dfafdf1f5a7fd30f9aef66b6d546dd355bf02c40662e3307f9725a96c6\n744c3031f83782f171c148dbc3bf1774f5dad1e79d6f095a3f54d4fbec5234ef\nd9a2f8d73afe4f14f57ef4f42def7b44f19060f06b45bddf1c5534d77fd922be\n2973a15a82e648661c6e3240aa3612ead952b604bde57458894f29deaf133bac\n13d2766f5227a4a3b8cf08da7adfd6fbd6bd8a4fe9dbb43d35e3dfa3f844fbf8\n9119bf4f7144094fb56333abf8a86063ca106f94b3a3b512343765e60082097f\n1bb86ba72439a653519b09f5cee1ce61c897d37eedf5553580ae60f4af8af33a\nb14fd400b6a0f34535c0434afc0b3a9f07147527a5fa7ca218ff56c74d74dc3f\n155cfd3325fc278acf2ae1cb4a539f5f9937c457263b0bd51234c732a300cdd1\ncc1840f0aaff54db0e4874ed5a9b5d6d27d4bb36746d80de72baa877ff4b275a\nd7895ed1897ea4139b5143fcbb1a62560da1ed9662aaed895ec78a91c18795b8\n5e07ab4af8ba128e95e682e0728bf8f2e5ae815a091a53d902ac1920d8e05f06\n589de8d8d66680789f4e454fb9d9ec66cd857af796ee2d902fa73fd5bba775a2\n153580ae44705ed0d37647d15697cb8f14bfa3e3e8fdf8031d47af571503357c\nf30d25acedcbbf135c9a35c49766ba07ab255859e8ec03684e66860182dff8f7\n0304bff6ff1c20fc81b7afdd00a71475539a536e36bb5973a19e3b923b02bde5\ne4efd4003ac170eb2d13fe274157afedbd82d6fb3a9a1e85e4551d47cf7078f8\n9671fe4289ebf5f2bf08d63f37c4eb4773c55a0996efeefa0ca011671d8060ca\n2f0004c7fcc300e166ef0240f825efe3361f106d57d423d0723f7acacd66376b\n2ed47b7a7a7a205f4ef4ac4691e0aad9aa0d41cf13741c3580a506487574ddca\n61a8c403c1863ebfbcac3475168b2de28b8b3d77544bb05ce92a02aceced3c0d\nd0cc65ea371b201cf1c601c24dde1c4078cedbdeb60322f50126a019bf6edc9b\n39e566b39b3517eaf97c3e0fbde5e4491d45bd74537145d155b476aa0176e868\nc6abebf30dbd5e525c54ac8e18e2d56abeb756827a3d970358a97416019a6f64\nf60004fdfe1580d5c98e618070cc1b05887eee7e0d209a70db7d8063029889b4\nc620ead78d7b33a7dc6c76b3e6427ddddbebde867c393aa7845e5403e8ca794a\nd0d6fb897af5f03525fe5782f5e7046bdaef468bf88d1debc6ab25583cd17310\n6079b9ab0ba059c914018245bf076075b5a303200c3c1f209a733701444fbbaf\n00c4134ebb016c5d0b23614c243701cdf875e3decce9349bddacb9505fbf7dfd\n76e82d87736a00f5d2b5ffd4b7dce2719a4d25ae717ee153c1abef18e257cfad\n7fa45682da48ef38c052b53b0fd06864b300c151ff08c0ea431de701a287dd5f\n004497dc7b01a253ee3e80b8c7f91c20f967fb6fdb7c80ada7d8683723614c24\n3701cdf875e3decc29379bddacb950ef3fd47f08f2e5a61ea4aa2a3eb757cd55\n13345efcfa59c12b2f19e2578ef77fb75a82854ffbee01a83f977b11a031931d\n040802df07082b5e11207cc17b1e209a770700e2df0a83e409fb7580f827c230\n99b06fd901fb058d6835dacd481813c94d40337eddb83773cacd66376b2ed437\nbebcf165e82d2f4e4beb7f3fa6e652c2d7ee10bc78c010bfb87fe3c95a09ae9f\nbd732740bd2fb700d0f865f64180e059ff044018ca0ca28a5b04883f701e0088\nbfec7c0c909cb71f0448c6ec518074b375012079d9dedf66004bcfbc51eb2dd1\naadacd481813c94d40337eddb83773cacd66376b2ed487868686205fbe7c49ef\n5605a73f34c4a7a787eeab96e0da81bb4e022c15ba27019a5b339300e16bf286\na8eae601e25866907cdf3e0890acb36f00245fb57f05904e59c300e92561946e\nb2e600d209ab7d07f04d458dfb46ad1bd16ab49b913026929b8066fcba716fe6\n949bcd6ed65ca8ef7e7cf7e3d05b7e7c8f217ee6cdddbb6a25a856f37980e0c7\nfe4e80a82623c48193014846ec7180f4acf518409aca0cd28a5504e03b32c374\nde1a00608a0240faaa327a4b19fe946fb6f90054dbb5f2333d022db56eb4966a\n3723614c243701cdf8f556bea8a7dc6c76b3e66bd46584ddbbcebc0990cf4b0f\nff4070520c282338a7e26700ec725202b01e4bcf0258963c6f1d4d8f0030cb20\n805549c520930c03584fa522b676f11600ffc03fde3e1b3489a9c9054c9aa23b\nc08856a3dd8c843191dc0434e3d78d7b33a75c36fb993761f7ae5a69f72ef97f\ne6ad336fed7e1c60e8bee96980bbdebbb60da07b7069062033d9dc0ae03d296f\n70ab511ec071640676252902d833c916007b3e1900b0a6d2028035968e025861\nea01581369fb11488c34d18cbc95989afccca42baad65ba2d5683723614c24d7\n8066fcbab8b7e96918baaf5aaa56219f975fb50a43f7c9bde90fa73f1c1a02d8\n78f2e27e803b77ca08b90519315b6fe400fc1392097a9eccc0ad444500e70199\na1331f0f00d8934901c07e5d526ceb87c2d07e2579badd005a2b31a5089391b7\n1253358049535a6add8856dd0146c298482e01ede27ed878b256ba7600ee3a09\nc18fc1df09fe01084ec25defc1b56db0f1a4f4bd78e0e2818d2f0334e7330300\n7df7c888b917e50dd9c1c60c80efcb0cbc63e1f700bce7c31700dccbd1060027\n8add9b0de06c8e2f00d84962b7d7030e2a61538331b98051f92631bd253f336a\ndd8856a3dd44c25c390efddfad96ae9f853b77c25201ba27c533b8bdf28b6ad0\n3d084b33d2e7fa59099e9901b8f2d29597fa0f01848f78e70082117f1ca07b76\n6910209b9519f895a008d031bbba05c09d8f06005c5b18b8fba25300cea6780e\nc03e911c6ccf06d507b48a4fa606634a114609de929f9934c5a87511ad57cfc1\nfa476aa5854fa1ef1e3910b905686e85cc24c40138198915f133d2d6dc2a7dea\n7df2ccc2a752faf2cec1d577aebeb37e3b4034eeee0008dff3be0e6b923773b4\n7904c0ef9119767cb4fa1500ef1361e08e452500f71561e84cc4ed3e20fab6a2\nc905f40cb76a3026bf3319b91ac2e46792a6dcd801ebc6aba5da08f48ecb81c8\nbd088d5f42f6417191de93908c803d0e76199292b485af41b60e8d9c3c537f0e\n8211f0c7211a077707dc18b931b2ee6d80a4d7ae024491ebc24d4a708ff70680\n7f25e807e8785f1878e322d6ddaf453f0770ff2dfa769b01423dbbad72a391b6\n5a7c3235985629423372494cab55c8f7d64a8b27a0e7202c55a13b0f8d19c80e\n4ae9ca3f015115dc3ca467c17a4c7ee95970ab10e5a54ff0ac3cd39881ee5958\n1a84f03df0be0e492fd855a8d6aa35d10b4962dbb0a604a3d3ee5e80a8eee600\na24977f8660378bf0bbf00e01d0a8fb7f980f04b8aa6ce6aca8d5a7533c52753\n839152c4e222f4dc512dd5eb90cbc981e8ea12cf90cd8a8bf47d89159e2741d3\n7124f65b96fcd254dae258fa84a13c13043246a32129574787e49eae2b49b86d\nc3e2e78b9ff7f4002415bb08907c66df0d103b4e0c104db90500ff70700c203a\nee1e82dba4c3e16e256c0acca6ceaae9afd1f612d7eb472157ac95962bd05594\n7dd1598466053245088e827f44628657942a825b84e4fb601f84b4025611aca3\n901e01bb024911dc0a4445f08e41f83df02b10142173149ab71baf027611ea95\n7a257704201d14cd9af4d90b00f194530088cb4e09c0df1c5c0088f7393f6833\nc0aa3ac156655de3bca9b34ab9716906ba07aba5e5bba1eb3358d90b9da7c533\n64f6888bf47b60f521e8380fe10be03d2feac17900927560df40f4e48f805960\n50328d648bf4893f9067c217a0631656b7c898c122847bc07b03a2d3e0ee85e4\n33b0ef867450c4fad2ecd26cf7168074c0ba0c904cdac300c9cfec4701924df6\n1cdca61e10685c6f7d52d0caba1498972f43d740adb4b2009d7d7220b20e3473\n90a943d00ffe959bb6eac3e0fe42ea49ee00c45f06e76329b1dabf127d690d80\n5581b408f63c2403e0cc433c00ee658836803b0fd100747c04ab5f917704fd10\nd5c1cd41ec801343d207f602a403605d86e5f9e5f9ae0d00e994556833806685\nc931fb709b0f08b4e869bea5c827859549e82c544b8d29c816a0390999613920\n7e610d5727a16318c2003c1fa24be0de2b32caf92224e7c17e5004b6350c4c01\n05601218066b0ad28224e149019c086257ca315102de2712903bde97b8144d82\n3b2c6ac52d403c054e019249b087f53d0558995a99ea946c70cc927458b3c1ff\n550f30050df988d4284376b4566a8e416654cc921985e037e0df0fc131f00f4b\nacf0c6211c036f14a239703741740adc7da227edd7e56b833d0ae92549b4d357\n25dfb49ed2ff63908e6adf27d6d0dda7638d4154d2778daca17f58e61297c129\n41f233b01f5dc3740cac51688c35c6b22580f48224fee9b83502569a66b629f1\n09f3713473413e2666e7fe6f6c6efefdfafda1f56f6e06f93496d9d67cb7366a\n9964b6f92e64b689196ec6c604646fd3fe4771ff1bf03f65d8ecc3addbb5f300\n00000049454e44ae426082\n')}
   1797 
   1798 def test_suite(options, args):
   1799 
   1800     def test_gradient_horizontal_lr(x, y):
   1801         return x
   1802 
   1803     def test_gradient_horizontal_rl(x, y):
   1804         return 1 - x
   1805 
   1806     def test_gradient_vertical_tb(x, y):
   1807         return y
   1808 
   1809     def test_gradient_vertical_bt(x, y):
   1810         return 1 - y
   1811 
   1812     def test_radial_tl(x, y):
   1813         return max(1 - math.sqrt(x * x + y * y), 0.0)
   1814 
   1815     def test_radial_center(x, y):
   1816         return test_radial_tl(x - 0.5, y - 0.5)
   1817 
   1818     def test_radial_tr(x, y):
   1819         return test_radial_tl(1 - x, y)
   1820 
   1821     def test_radial_bl(x, y):
   1822         return test_radial_tl(x, 1 - y)
   1823 
   1824     def test_radial_br(x, y):
   1825         return test_radial_tl(1 - x, 1 - y)
   1826 
   1827     def test_stripe(x, n):
   1828         return float(int(x * n) & 1)
   1829 
   1830     def test_stripe_h_2(x, y):
   1831         return test_stripe(x, 2)
   1832 
   1833     def test_stripe_h_4(x, y):
   1834         return test_stripe(x, 4)
   1835 
   1836     def test_stripe_h_10(x, y):
   1837         return test_stripe(x, 10)
   1838 
   1839     def test_stripe_v_2(x, y):
   1840         return test_stripe(y, 2)
   1841 
   1842     def test_stripe_v_4(x, y):
   1843         return test_stripe(y, 4)
   1844 
   1845     def test_stripe_v_10(x, y):
   1846         return test_stripe(y, 10)
   1847 
   1848     def test_stripe_lr_10(x, y):
   1849         return test_stripe(x + y, 10)
   1850 
   1851     def test_stripe_rl_10(x, y):
   1852         return test_stripe(1 + x - y, 10)
   1853 
   1854     def test_checker(x, y, n):
   1855         return float(int(x * n) & 1 ^ int(y * n) & 1)
   1856 
   1857     def test_checker_8(x, y):
   1858         return test_checker(x, y, 8)
   1859 
   1860     def test_checker_15(x, y):
   1861         return test_checker(x, y, 15)
   1862 
   1863     def test_zero(x, y):
   1864         return 0
   1865 
   1866     def test_one(x, y):
   1867         return 1
   1868 
   1869     test_patterns = {'GLR': test_gradient_horizontal_lr,
   1870      'GRL': test_gradient_horizontal_rl,
   1871      'GTB': test_gradient_vertical_tb,
   1872      'GBT': test_gradient_vertical_bt,
   1873      'RTL': test_radial_tl,
   1874      'RTR': test_radial_tr,
   1875      'RBL': test_radial_bl,
   1876      'RBR': test_radial_br,
   1877      'RCTR': test_radial_center,
   1878      'HS2': test_stripe_h_2,
   1879      'HS4': test_stripe_h_4,
   1880      'HS10': test_stripe_h_10,
   1881      'VS2': test_stripe_v_2,
   1882      'VS4': test_stripe_v_4,
   1883      'VS10': test_stripe_v_10,
   1884      'LRS': test_stripe_lr_10,
   1885      'RLS': test_stripe_rl_10,
   1886      'CK8': test_checker_8,
   1887      'CK15': test_checker_15,
   1888      'ZERO': test_zero,
   1889      'ONE': test_one}
   1890 
   1891     def test_pattern(width, height, bitdepth, pattern):
   1892         maxval = 2 ** bitdepth - 1
   1893         if maxval > 255:
   1894             a = array('H')
   1895         else:
   1896             a = array('B')
   1897         fw = float(width)
   1898         fh = float(height)
   1899         pfun = test_patterns[pattern]
   1900         for y in range(height):
   1901             fy = float(y) / fh
   1902             for x in range(width):
   1903                 a.append(int(round(pfun(float(x) / fw, fy) * maxval)))
   1904 
   1905         return a
   1906 
   1907     def test_rgba(size = 256, bitdepth = 8, red = 'GTB', green = 'GLR', blue = 'RTL', alpha = None):
   1908         i = test_pattern(size, size, bitdepth, red)
   1909         psize = 1
   1910         for channel in (green, blue, alpha):
   1911             if channel:
   1912                 c = test_pattern(size, size, bitdepth, channel)
   1913                 i = interleave_planes(i, c, psize, 1)
   1914                 psize += 1
   1915 
   1916         return i
   1917 
   1918     def pngsuite_image(name):
   1919         if name not in _pngsuite:
   1920             raise NotImplementedError('cannot find PngSuite file %s (use -L for a list)' % name)
   1921         r = Reader(bytes=_pngsuite[name])
   1922         w, h, pixels, meta = r.asDirect()
   1923         if meta['greyscale'] and meta['alpha'] and meta['bitdepth'] < 8:
   1924             factor = 255 // (2 ** meta['bitdepth'] - 1)
   1925 
   1926             def rescale(data):
   1927                 for row in data:
   1928                     yield map(factor.__mul__, row)
   1929 
   1930             pixels = rescale(pixels)
   1931             meta['bitdepth'] = 8
   1932         arraycode = 'BH'[meta['bitdepth'] > 8]
   1933         return (w, array(arraycode, itertools.chain(*pixels)), meta)
   1934 
   1935     size = 256
   1936     if options.test_size:
   1937         size = options.test_size
   1938     options.bitdepth = options.test_depth
   1939     options.greyscale = bool(options.test_black)
   1940     kwargs = {}
   1941     if options.test_red:
   1942         kwargs['red'] = options.test_red
   1943     if options.test_green:
   1944         kwargs['green'] = options.test_green
   1945     if options.test_blue:
   1946         kwargs['blue'] = options.test_blue
   1947     if options.test_alpha:
   1948         kwargs['alpha'] = options.test_alpha
   1949     if options.greyscale:
   1950         if options.test_red or options.test_green or options.test_blue:
   1951             raise ValueError('cannot specify colours (R, G, B) when greyscale image (black channel, K) is specified')
   1952         kwargs['red'] = options.test_black
   1953         kwargs['green'] = None
   1954         kwargs['blue'] = None
   1955     options.alpha = bool(options.test_alpha)
   1956     if not args:
   1957         pixels = test_rgba(size, options.bitdepth, **kwargs)
   1958     else:
   1959         size, pixels, meta = pngsuite_image(args[0])
   1960         for k in ['bitdepth', 'alpha', 'greyscale']:
   1961             setattr(options, k, meta[k])
   1962 
   1963     writer = Writer(size, size, bitdepth=options.bitdepth, transparent=options.transparent, background=options.background, gamma=options.gamma, greyscale=options.greyscale, alpha=options.alpha, compression=options.compression, interlace=options.interlace)
   1964     writer.write_array(sys.stdout, pixels)
   1965 
   1966 
   1967 def read_pam_header(infile):
   1968     header = dict()
   1969     while True:
   1970         l = infile.readline().strip()
   1971         if l == strtobytes('ENDHDR'):
   1972             break
   1973         if not l:
   1974             raise EOFError('PAM ended prematurely')
   1975         if l[0] == strtobytes('#'):
   1976             continue
   1977         l = l.split(None, 1)
   1978         if l[0] not in header:
   1979             header[l[0]] = l[1]
   1980         else:
   1981             header[l[0]] += strtobytes(' ') + l[1]
   1982 
   1983     required = ['WIDTH',
   1984      'HEIGHT',
   1985      'DEPTH',
   1986      'MAXVAL']
   1987     required = [ strtobytes(x) for x in required ]
   1988     WIDTH, HEIGHT, DEPTH, MAXVAL = required
   1989     present = [ x for x in required if x in header ]
   1990     if len(present) != len(required):
   1991         raise Error('PAM file must specify WIDTH, HEIGHT, DEPTH, and MAXVAL')
   1992     width = int(header[WIDTH])
   1993     height = int(header[HEIGHT])
   1994     depth = int(header[DEPTH])
   1995     maxval = int(header[MAXVAL])
   1996     if width <= 0 or height <= 0 or depth <= 0 or maxval <= 0:
   1997         raise Error('WIDTH, HEIGHT, DEPTH, MAXVAL must all be positive integers')
   1998     return ('P7',
   1999      width,
   2000      height,
   2001      depth,
   2002      maxval)
   2003 
   2004 
   2005 def read_pnm_header(infile, supported = ('P5', 'P6')):
   2006     supported = [ strtobytes(x) for x in supported ]
   2007     type = infile.read(3).rstrip()
   2008     if type not in supported:
   2009         raise NotImplementedError('file format %s not supported' % type)
   2010     if type == strtobytes('P7'):
   2011         return read_pam_header(infile)
   2012     expected = 4
   2013     pbm = ('P1', 'P4')
   2014     if type in pbm:
   2015         expected = 3
   2016     header = [type]
   2017 
   2018     def getc():
   2019         c = infile.read(1)
   2020         if not c:
   2021             raise Error('premature EOF reading PNM header')
   2022         return c
   2023 
   2024     c = getc()
   2025     while True:
   2026         while c.isspace():
   2027             c = getc()
   2028 
   2029         while c == '#':
   2030             while c not in '\n\r':
   2031                 c = getc()
   2032 
   2033         if not c.isdigit():
   2034             raise Error('unexpected character %s found in header' % c)
   2035         token = strtobytes('')
   2036         while c.isdigit():
   2037             token += c
   2038             c = getc()
   2039 
   2040         header.append(int(token))
   2041         if len(header) == expected:
   2042             break
   2043 
   2044     while c == '#':
   2045         while c not in '\n\r':
   2046             c = getc()
   2047 
   2048     if not c.isspace():
   2049         raise Error('expected header to end with whitespace, not %s' % c)
   2050     if type in pbm:
   2051         header.append(1)
   2052     depth = (1, 3)[type == strtobytes('P6')]
   2053     return (header[0],
   2054      header[1],
   2055      header[2],
   2056      depth,
   2057      header[3])
   2058 
   2059 
   2060 def write_pnm(file, width, height, pixels, meta):
   2061     bitdepth = meta['bitdepth']
   2062     maxval = 2 ** bitdepth - 1
   2063     planes = meta['planes']
   2064     if planes in (1, 3):
   2065         if 1 == planes:
   2066             fmt = 'P5'
   2067         else:
   2068             fmt = 'P6'
   2069         file.write('%s %d %d %d\n' % (fmt,
   2070          width,
   2071          height,
   2072          maxval))
   2073     if planes in (2, 4):
   2074         if 2 == planes:
   2075             tupltype = 'GRAYSCALE_ALPHA'
   2076         else:
   2077             tupltype = 'RGB_ALPHA'
   2078         file.write('P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n' % (width,
   2079          height,
   2080          planes,
   2081          maxval,
   2082          tupltype))
   2083     vpr = planes * width
   2084     fmt = '>%d' % vpr
   2085     if maxval > 255:
   2086         fmt = fmt + 'H'
   2087     else:
   2088         fmt = fmt + 'B'
   2089     for row in pixels:
   2090         file.write(struct.pack(fmt, *row))
   2091 
   2092     file.flush()
   2093 
   2094 
   2095 def color_triple(color):
   2096     if color.startswith('#') and len(color) == 4:
   2097         return (int(color[1], 16), int(color[2], 16), int(color[3], 16))
   2098     if color.startswith('#') and len(color) == 7:
   2099         return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16))
   2100     if color.startswith('#') and len(color) == 13:
   2101         return (int(color[1:5], 16), int(color[5:9], 16), int(color[9:13], 16))
   2102 
   2103 
   2104 def _main(argv):
   2105     from optparse import OptionParser
   2106     import re
   2107     version = '%prog ' + re.sub('( ?\\$|URL: |Rev:)', '', __version__)
   2108     parser = OptionParser(version=version)
   2109     parser.set_usage('%prog [options] [imagefile]')
   2110     parser.add_option('-r', '--read-png', default=False, action='store_true', help='Read PNG, write PNM')
   2111     parser.add_option('-i', '--interlace', default=False, action='store_true', help='create an interlaced PNG file (Adam7)')
   2112     parser.add_option('-t', '--transparent', action='store', type='string', metavar='color', help='mark the specified colour (#RRGGBB) as transparent')
   2113     parser.add_option('-b', '--background', action='store', type='string', metavar='color', help='save the specified background colour')
   2114     parser.add_option('-a', '--alpha', action='store', type='string', metavar='pgmfile', help='alpha channel transparency (RGBA)')
   2115     parser.add_option('-g', '--gamma', action='store', type='float', metavar='value', help='save the specified gamma value')
   2116     parser.add_option('-c', '--compression', action='store', type='int', metavar='level', help='zlib compression level (0-9)')
   2117     parser.add_option('-T', '--test', default=False, action='store_true', help='create a test image (a named PngSuite image if an argument is supplied)')
   2118     parser.add_option('-L', '--list', default=False, action='store_true', help='print list of named test images')
   2119     parser.add_option('-R', '--test-red', action='store', type='string', metavar='pattern', help='test pattern for the red image layer')
   2120     parser.add_option('-G', '--test-green', action='store', type='string', metavar='pattern', help='test pattern for the green image layer')
   2121     parser.add_option('-B', '--test-blue', action='store', type='string', metavar='pattern', help='test pattern for the blue image layer')
   2122     parser.add_option('-A', '--test-alpha', action='store', type='string', metavar='pattern', help='test pattern for the alpha image layer')
   2123     parser.add_option('-K', '--test-black', action='store', type='string', metavar='pattern', help='test pattern for greyscale image')
   2124     parser.add_option('-d', '--test-depth', default=8, action='store', type='int', metavar='NBITS', help='create test PNGs that are NBITS bits per channel')
   2125     parser.add_option('-S', '--test-size', action='store', type='int', metavar='size', help='width and height of the test image')
   2126     options, args = parser.parse_args(args=argv[1:])
   2127     if options.transparent is not None:
   2128         options.transparent = color_triple(options.transparent)
   2129     if options.background is not None:
   2130         options.background = color_triple(options.background)
   2131     if options.list:
   2132         names = list(_pngsuite)
   2133         names.sort()
   2134         for name in names:
   2135             print name
   2136 
   2137         return
   2138     if options.test:
   2139         return test_suite(options, args)
   2140     if len(args) == 0:
   2141         infilename = '-'
   2142         infile = sys.stdin
   2143     elif len(args) == 1:
   2144         infilename = args[0]
   2145         infile = open(infilename, 'rb')
   2146     else:
   2147         parser.error('more than one input file')
   2148     outfile = sys.stdout
   2149     if options.read_png:
   2150         png = Reader(file=infile)
   2151         width, height, pixels, meta = png.asDirect()
   2152         write_pnm(outfile, width, height, pixels, meta)
   2153     else:
   2154         format, width, height, depth, maxval = read_pnm_header(infile, ('P5', 'P6', 'P7'))
   2155         greyscale = depth <= 2
   2156         pamalpha = depth in (2, 4)
   2157         supported = map(lambda x: 2 ** x - 1, range(1, 17))
   2158         try:
   2159             mi = supported.index(maxval)
   2160         except ValueError:
   2161             raise NotImplementedError('your maxval (%s) not in supported list %s' % (maxval, str(supported)))
   2162 
   2163         bitdepth = mi + 1
   2164         writer = Writer(width, height, greyscale=greyscale, bitdepth=bitdepth, interlace=options.interlace, transparent=options.transparent, background=options.background, alpha=bool(pamalpha or options.alpha), gamma=options.gamma, compression=options.compression)
   2165         if options.alpha:
   2166             pgmfile = open(options.alpha, 'rb')
   2167             format, awidth, aheight, adepth, amaxval = read_pnm_header(pgmfile, 'P5')
   2168             if amaxval != '255':
   2169                 raise NotImplementedError('maxval %s not supported for alpha channel' % amaxval)
   2170             if (awidth, aheight) != (width, height):
   2171                 raise ValueError('alpha channel image size mismatch (%s has %sx%s but %s has %sx%s)' % (infilename,
   2172                  width,
   2173                  height,
   2174                  options.alpha,
   2175                  awidth,
   2176                  aheight))
   2177             writer.convert_ppm_and_pgm(infile, pgmfile, outfile)
   2178         else:
   2179             writer.convert_pnm(infile, outfile)
   2180 
   2181 
   2182 def crop(tl, br, inFile, outFile):
   2183     r = Reader(file=inFile)
   2184     x, y, pixels, meta = r.asDirect()
   2185     if not 0 <= tl[0] < br[0] <= x:
   2186         raise NotImplementedError()
   2187     if not 0 <= tl[1] < br[1] <= y:
   2188         raise NotImplementedError()
   2189     l = tl[0] * meta['planes']
   2190     r = br[0] * meta['planes']
   2191 
   2192     def itercrop():
   2193         for i, row in enumerate(pixels):
   2194             if i < tl[1]:
   2195                 continue
   2196             if i >= br[1]:
   2197                 return
   2198             yield row[l:r]
   2199 
   2200     meta['size'] = (br[0] - tl[0], br[1] - tl[1])
   2201     w = Writer(**meta)
   2202     w.write(outFile, itercrop())
   2203 
   2204 
   2205 if __name__ == '__main__':
   2206     try:
   2207         _main(sys.argv)
   2208     except Error as e:
   2209         print >> sys.stderr, e