
    6Dh;                    ^   S r SrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKrSSKJr  / SQr\R                  " SSSS	S
SSSS5	      rSrS r\R$                  " SS5      rS rS rS rS rS r " S S\5      r " S S\5      r " S S\5      r " S S\5      r " S S 5      r " S! S"5      rS>S# jr S$ r!S% r"S& r#S' r$S( r%S) r&\RN                  " S*\RP                  S+9r)S0 4S, jr*\*r+ " S- S.5      r, " S/ S05      r-S1 r.S2 r/S3 r0S4 r1S5 r2S6 r3S7 r4S8 r5S9 r6S: r7S; r8S< r9S= r:g)?a  
The ``png`` module can read and write PNG files.

Installation and Overview
-------------------------

``pip install pypng``

For help, type ``import png; help(png)`` in your python interpreter.

A good place to start is the :class:`Reader` and :class:`Writer` classes.

Coverage of PNG formats is fairly complete;
all allowable bit depths (1/2/4/8/16/24/32/48/64 bits per pixel) and
colour combinations are supported:

- greyscale (1/2/4/8/16 bit);
- RGB, RGBA, LA (greyscale with alpha) with 8/16 bits per channel;
- colour mapped images (1/2/4/8 bit).

Interlaced images,
which support a progressive display when downloading,
are supported for both reading and writing.

A number of optional chunks can be specified (when writing)
and understood (when reading): ``tRNS``, ``bKGD``, ``gAMA``.

The ``sBIT`` chunk can be used to specify precision for
non-native bit depths.

Requires Python 3.5 or higher.
Installation is trivial,
but see the ``README.txt`` file (with the source distribution) for details.

Full use of all features will need some reading of the PNG specification
http://www.w3.org/TR/2003/REC-PNG-20031110/.

The package also comes with command line utilities.

- ``pripamtopng`` converts
  `Netpbm <http://netpbm.sourceforge.net/>`_ PAM/PNM files to PNG;
- ``pripngtopam`` converts PNG to file PAM/PNM.

There are a few more for simple PNG manipulations.

Spelling and Terminology
------------------------

Generally British English spelling is used in the documentation.
So that's "greyscale" and "colour".
This not only matches the author's native language,
it's also used by the PNG specification.

Colour Models
-------------

The major colour models supported by PNG (and hence by PyPNG) are:

- greyscale;
- greyscale--alpha;
- RGB;
- RGB--alpha.

Also referred to using the abbreviations: L, LA, RGB, RGBA.
Each letter codes a single channel:
*L* is for Luminance or Luma or Lightness (greyscale images);
*A* stands for Alpha, the opacity channel
(used for transparency effects, but higher values are more opaque,
so it makes sense to call it opacity);
*R*, *G*, *B* stand for Red, Green, Blue (colour image).

Lists, arrays, sequences, and so on
-----------------------------------

When getting pixel data out of this module (reading) and
presenting data to this module (writing) there are
a number of ways the data could be represented as a Python value.

The preferred format is a sequence of *rows*,
which each row being a sequence of *values*.
In this format, the values are in pixel order,
with all the values from all the pixels in a row
being concatenated into a single sequence for that row.

Consider an image that is 3 pixels wide by 2 pixels high, and each pixel
has RGB components:

Sequence of rows::

  list([R,G,B, R,G,B, R,G,B],
       [R,G,B, R,G,B, R,G,B])

Each row appears as its own list,
but the pixels are flattened so that three values for one pixel
simply follow the three values for the previous pixel.

This is the preferred because
it provides a good compromise between space and convenience.
PyPNG regards itself as at liberty to replace any sequence type with
any sufficiently compatible other sequence type;
in practice each row is an array (``bytearray`` or ``array.array``).

To allow streaming the outer list is sometimes
an iterator rather than an explicit list.

An alternative format is a single array holding all the values.

Array of values::

  [R,G,B, R,G,B, R,G,B,
   R,G,B, R,G,B, R,G,B]

The entire image is one single giant sequence of colour values.
Generally an array will be used (to save space), not a list.

The top row comes first,
and within each row the pixels are ordered from left-to-right.
Within a pixel the values appear in the order R-G-B-A
(or L-A for greyscale--alpha).

There is another format, which should only be used with caution.
It is mentioned because it is used internally,
is close to what lies inside a PNG file itself,
and has some support from the public API.
This format is called *packed*.
When packed, each row is a sequence of bytes (integers from 0 to 255),
just as it is before PNG scanline filtering is applied.
When the bit depth is 8 this is the same as a sequence of rows;
when the bit depth is less than 8 (1, 2 and 4),
several pixels are packed into each byte;
when the bit depth is 16 each pixel value is decomposed into 2 bytes
(and `packed` is a misnomer).
This format is used by the :meth:`Writer.write_packed` method.
It isn't usually a convenient format,
but may be just right if the source data for
the PNG image comes from something that uses a similar format
(for example, 1-bit BMPs, or another PNG file).
z0.0.20    Narray)ImageReaderWriterwrite_chunks
from_array8B   P   N   G      
      ))r   r      r   )   r   r   r   )r   r   r   r   )   r   r   r   )r   r   r   r   )   r   r   r   )r   r   r   r   c              #   v   ^^#    [          H)  u  mnmnTU :  a  M  UU4S j[        X!U5       5       v   M+     g7f)aU  
Generate the coordinates for the reduced scanlines
of an Adam7 interlaced image
of size `width` by `height` pixels.

Yields a generator for each pass,
and each pass generator yields a series of (x, y, xstep) triples,
each one identifying a reduced scanline consisting of
pixels starting at (x, y) and taking every xstep pixel to the right.
c              3   .   >#    U  H
  nTUT4v   M     g 7fN ).0yxstartxsteps     C/var/www/html/env/lib/python3.13/site-packages/_plotly_utils/png.py	<genexpr>!adam7_generate.<locals>.<genexpr>   s     H+Ga5!+Gs   N)adam7range)widthheightystartystepr   r   s       @@r   adam7_generater'      s7      ).$uU?H5+GHH ).s   59_Resolutionzx y unit_is_meterc                 >    [        [        [        U 5      /U-  6 5      $ r   )listzipiter)sns     r   groupr/      s    d1gY]#$$    c                 "    [        U [        5      $ r   )
isinstancer   )xs    r   isarrayr4      s    ar0   c                    U c  g[        U 5      nS[        U5      s=:  a  S::  d  O  [        S5      eSn[        U5       H  u  p4[        U5      S;  a  [        SU-  5      e[        U5      S:X  a  S	nU(       a  [        U5      S
:X  a  [        SU-  5      eU H/  n[	        U5      U:w  d  SUs=::  a  S::  a  M!  O  [        SU-  5      e   M     U$ )z
Check a palette argument (to the :class:`Writer` class) for validity.
Returns the palette as a list if okay;
raises an exception otherwise.
Nr      zTa palette must have between 1 and 256 entries, see https://www.w3.org/TR/PNG/#11PLTEF)   r   z1palette entry %d: entries must be 3- or 4-tuples.r7   Tr   z8palette entry %d: all 4-tuples must precede all 3-tuples   z7palette entry %d: values must be integer: 0 <= x <= 255)r*   lenProtocolError	enumerateint)palettepseen_tripleitr3   s         r   check_paletterB      s     WAA#5
 	
 K!q6 SVW WXXq6Q;K3q6Q;JQN  A1v{1=S=#PSTT    Hr0   c                     U (       d  X4$ [        U 5      S:w  a  [        S5      eUb  XS   :w  a  [        SU S   < SU< S35      eUb  X S   :w  a  [        SU S   < S	U< S35      eU $ )
zY
Check that these arguments, if supplied, are consistent.
Return a (width, height) pair.
r   z.size argument should be a pair (width, height)r   z	size[0] (z) and width (z") should match when both are used.r   z	size[1] (z) and height ()r9   r:   )sizer#   r$   s      r   check_sizesrE     s     }
4yA~LMMU1g-Aw
 	
 fQ/Aw 
 	
 Kr0   c                    U c  U $ U(       aM   [        U 5        [        U 5      S:w  a  [        SU-  5      e[        U S   5      (       d  [        SU-  5      e U $ [        U 5      S:X  a9  [        U S   5      (       a&  [        U S   5      (       a  [        U S   5      (       d  [        SU-  5      eU $ ! [         a    U 4n  Nf = f)z
Checks that a colour argument for transparent or background options
is the right form.
Returns the colour
(which, if it's a bare integer, is "corrected" to a 1-tuple).
r   z %s for greyscale must be 1-tupler   z'%s colour for greyscale must be integerr7   r   z&%s colour must be a triple of integers)r9   	TypeErrorr:   
is_natural)c	greyscalewhichs      r   check_colorrL   -  s     	y	F q6Q; BU JKK!A$ IE QRR   H FaKJqt,,AaD1A1AjQRSTQUFVFV H5 PQQH  	A	s   B2 2CCc                       \ rS rSrS rSrg)ErroriH  c                 l    U R                   R                  S-   SR                  U R                  5      -   $ )Nz:  )	__class____name__joinargsselfs    r   __str__Error.__str__I  s)    ~~&&-0CCCr0   r   N)rR   
__module____qualname____firstlineno__rW   __static_attributes__r   r0   r   rN   rN   H  s    Dr0   rN   c                       \ rS rSrSrSrg)FormatErroriM  z|
Problem with input file format.
In other words, PNG file does not conform to
the specification in some way and is invalid.
r   NrR   rY   rZ   r[   __doc__r\   r   r0   r   r^   r^   M  s    r0   r^   c                       \ rS rSrSrSrg)r:   iU  z\
Problem with the way the programming interface has been used,
or the data presented to it.
r   Nr_   r   r0   r   r:   r:   U  s    r0   r:   c                       \ rS rSrSrg)
ChunkErrori\  r   N)rR   rY   rZ   r[   r\   r   r0   r   rc   rc   \  s    r0   rc   c                       \ rS rSrSrSrg)Defaulti`  z'The default for the greyscale paramter.r   Nr_   r   r0   r   re   re   `  s    1r0   re   c                   r    \ rS rSrSrSSS\SSSSSSSSSSSSSSS4S jrS rS	 rS
 r	S r
S rS rS rSrg)r   id  z
PNG encoder in pure Python.
NFr   i   c                 .   [        X1U5      u  pA[        U5      (       a  [        U5      (       d  [        S5      eUS::  d  US::  a  [        S5      eUS:  d  US:  a  [        S5      eU(       a  Ub  [        S5      e [        U5        U HA  n[        U5      =(       a    SUs=:*  =(       a    S	:*  Os  nU(       a  M3  [        S
U< S35      e   [        U5      n[        U5      n[        U5      nU[        L a	  U(       a  Sn[        U5      nU(       a  SnSnO
SU   nUU-   n[        U5      S:X  a  Xm-  n[        XvXU5      u  o`l	        US:  a  U(       d	  U(       d   eU(       a   eUS:  a	  U(       a   e[        XS5      n[        XS5      n	Xl        X l        Xl        Xl        Xl        X@l        XPl        Xl        ['        U5      U l        Xl        UU l        [        U5      U l        Xpl        UU l        UU l        [        U5      U l        SU R"                  -  SU(       + -  -   SU R$                  -  -   U l        U R8                  S;   d   eUU l        Xl        U R(                  S-  U R<                  -  U l        g! [         a    U4n GN	f = f)a  
Create a PNG encoder object.

Arguments:

width, height
  Image size in pixels, as two separate arguments.
size
  Image size (w,h) in pixels, as single argument.
greyscale
  Pixels are greyscale, not RGB.
alpha
  Input data has alpha channel (RGBA or LA).
bitdepth
  Bit depth: from 1 to 16 (for each channel).
palette
  Create a palette for a colour mapped image (colour type 3).
transparent
  Specify a transparent colour (create a ``tRNS`` chunk).
background
  Specify a default background colour (create a ``bKGD`` chunk).
gamma
  Specify a gamma value (create a ``gAMA`` chunk).
compression
  zlib compression level: 0 (none) to 9 (more compressed);
  default: -1 or None.
interlace
  Create an interlaced image.
chunk_limit
  Write multiple ``IDAT`` chunks to save memory.
x_pixels_per_unit
  Number of pixels a unit along the x axis (write a
  `pHYs` chunk).
y_pixels_per_unit
  Number of pixels a unit along the y axis (write a
  `pHYs` chunk). Along with `x_pixel_unit`, this gives
  the pixel size ratio.
unit_is_meter
  `True` to indicate that the unit (for the `pHYs`
  chunk) is metre.

The image size (in pixels) can be specified either by using the
`width` and `height` arguments, or with the single `size`
argument.
If `size` is used it should be a pair (*width*, *height*).

The `greyscale` argument indicates whether input pixels
are greyscale (when true), or colour (when false).
The default is true unless `palette=` is used.

The `alpha` argument (a boolean) specifies
whether input pixels have an alpha channel (or not).

`bitdepth` specifies the bit depth of the source pixel values.
Each channel may have a different bit depth.
Each source pixel must have values that are
an integer between 0 and ``2**bitdepth-1``, where
`bitdepth` is the bit depth for the corresponding channel.
For example, 8-bit images have values between 0 and 255.
PNG only stores images with bit depths of
1,2,4,8, or 16 (the same for all channels).
When `bitdepth` is not one of these values or where
channels have different bit depths,
the next highest valid bit depth is selected,
and an ``sBIT`` (significant bits) chunk is generated
that specifies the original precision of the source image.
In this case the supplied pixel values will be rescaled to
fit the range of the selected bit depth.

The PNG file format supports many bit depth / colour model
combinations, but not all.
The details are somewhat arcane
(refer to the PNG specification for full details).
Briefly:
Bit depths < 8 (1,2,4) are only allowed with greyscale and
colour mapped images;
colour mapped images cannot have bit depth 16.

For colour mapped images
(in other words, when the `palette` argument is specified)
the `bitdepth` argument must match one of
the valid PNG bit depths: 1, 2, 4, or 8.
(It is valid to have a PNG image with a palette and
an ``sBIT`` chunk, but the meaning is slightly different;
it would be awkward to use the `bitdepth` argument for this.)

The `palette` option, when specified,
causes a colour mapped image to be created:
the PNG colour type is set to 3;
`greyscale` must not be true; `alpha` must not be true;
`transparent` must not be set.
The bit depth must be 1,2,4, or 8.
When a colour mapped image is created,
the pixel values are palette indexes and
the `bitdepth` argument specifies the size of these indexes
(not the size of the colour values in the palette).

The palette argument value should be a sequence of 3- or
4-tuples.
3-tuples specify RGB palette entries;
4-tuples specify RGBA palette entries.
All the 4-tuples (if present) must come before all the 3-tuples.
A ``PLTE`` chunk is created;
if there are 4-tuples then a ``tRNS`` chunk is created as well.
The ``PLTE`` chunk will contain all the RGB triples in the same
sequence;
the ``tRNS`` chunk will contain the alpha channel for
all the 4-tuples, in the same sequence.
Palette entries are always 8-bit.

If specified, the `transparent` and `background` parameters must be
a tuple with one element for each channel in the image.
Either a 3-tuple of integer (RGB) values for a colour image, or
a 1-tuple of a single integer for a greyscale image.

If specified, the `gamma` parameter must be a positive number
(generally, a `float`).
A ``gAMA`` chunk will be created.
Note that this will not change the values of the pixels as
they appear in the PNG file,
they are assumed to have already
been converted appropriately for the gamma specified.

The `compression` argument specifies the compression level to
be used by the ``zlib`` module.
Values from 1 to 9 (highest) specify compression.
0 means no compression.
-1 and ``None`` both mean that the ``zlib`` module uses
the default level of compession (which is generally acceptable).

If `interlace` is true then an interlaced image is created
(using PNG's so far only interace method, *Adam7*).
This does not affect how the pixels should be passed in,
rather it changes how they are arranged into the PNG file.
On slow connexions interlaced images can be
partially decoded by the browser to give
a rough view of the image that is
successively refined as more image data appears.

.. note ::

  Enabling the `interlace` option requires the entire image
  to be processed in working memory.

`chunk_limit` is used to limit the amount of memory used whilst
compressing the image.
In order to avoid using large amounts of memory,
multiple ``IDAT`` chunks may be created.
z!width and height must be integersr   z*width and height must be greater than zeroz&width and height cannot exceed 2**31-1Nz1transparent colour not allowed with alpha channelr      zeach bitdepth z! must be a positive integer <= 16Fr7   r   r   transparent
backgroundr   r   r   r   r7   r      ) rE   rH   r:   r9   rG   rB   boolre   check_bitdepth_rescalerescalerL   r#   r$   rk   rl   gammarJ   alphacolormapr<   bitdepthcompressionchunk_limit	interlacer=   x_pixels_per_unity_pixels_per_unitunit_is_meter
color_typecolor_planesplanespsize)rV   r#   r$   rD   rJ   rs   ru   r=   rk   rl   rr   rv   rx   r~   rt   maxvalrw   ry   rz   r{   bvalidr}   s                          r   __init__Writer.__init__i  sv   d $D8%  
6(:(: CDDA:1 LMM9 2 HII[, STT	#M AqM2a1lllE5#KSU    (U=GIO	LF!),L!E)Fx=AH!7{9"
, a<''9a<;!+-H E

 
&$
"
 H&&i!2!2!-0djj.1I+>>T]]ARR/111(mma'4;;6
G  	# {H	#s   ?J JJc                 p  ^ U R                   U R                  -  mU4S jnU R                  (       aF  SU R                  S:     n[	        U[
        R                  " U" U5      6 5      nU R                  X5      $ U R                  X" U5      5      nX`R                  :w  a  [        SX`R                  4-  5      eg)a  
Write a PNG image to the output file.
`rows` should be an iterable that yields each row
(each row is a sequence of values).
The rows should be the rows of the original image,
so there should be ``self.height`` rows of
``self.width * self.planes`` values.
If `interlace` is specified (when creating the instance),
then an interlaced PNG file will be written.
Supply the rows in the normal image order;
the interlacing is carried out internally.

.. note ::

  Interlacing requires the entire image to be in working memory.
c              3      >#    [        U 5       H9  u  p [        U5      T:g  nU(       a  [        ST[        U5      U4-  5      eUv   M;     g! [         a    Sn N8f = f7f)zG
Yield each row in rows,
but check each row first (for correct width).
Fz/Expected %d values but got %d values, in row %dN)r;   r9   rG   r:   )rowsr@   rowwrong_lengthvprs       r   
check_rows Writer.write.<locals>.check_rows  sp     
 $D/)#&s8s?L  'IC!,-  	 * ! ) $)L	)s'   AA*AAAAABHr   z-rows supplied (%d) does not match height (%d)N)r#   r~   rx   ru   r   	itertoolschainwrite_arraywrite_passesr$   r:   )rV   outfiler   r   fmtanrowsr   s          @r   writeWriter.writer  s    & jj4;;&	* >>t}}q()Cc9??Jt,<=>A##G//!!':d+;<KK?5++BVV   r0   c                     U R                   (       a  [        X R                   5      nU R                  S:  a  [        X R                  5      nOU R                  S:X  a  [	        U5      nU R                  X5      $ )a  
Write a PNG image to the output file.

Most users are expected to find the :meth:`write` or
:meth:`write_array` method more convenient.

The rows should be given to this method in the order that
they appear in the output file.
For straightlaced images, this is the usual top to bottom ordering.
For interlaced images the rows should have been interlaced before
passing them to this function.

`rows` should be an iterable that yields each row
(each row being a sequence of values).
r   ri   )rq   rescale_rowsru   	pack_rowsunpack_rowswrite_packed)rV   r   r   s      r   r   Writer.write_passes  sZ    ( <<ll3D==1T==1D]]b t$D  //r0   c                    U R                  U5        U R                  b!  [        R                  " U R                  5      nO[        R                  " 5       n[	        5       n[        U5       Hz  u  pVUR                  S5        UR                  U5        [        U5      U R                  :  d  MB  UR                  U5      n[        U5      (       a  [        USU5        [	        5       nM|     UR                  [        U5      5      nUR                  5       n[        U5      (       d  [        U5      (       a  [        USXx-   5        [        US5        WS-   $ )a%  
Write PNG file to `outfile`.
`rows` should be an iterator that yields each packed row;
a packed row being a sequence of packed bytes.

The rows have a filter byte prefixed and
are then compressed into one or more IDAT chunks.
They are not processed any further,
so if bitdepth is other than 1, 2, 4, 8, 16,
the pixel values should have been scaled
before passing them to this method.

This method does work for interlaced images but it is best avoided.
For interlaced images, the rows should be
presented in the order that they appear in the file.
r      IDAT   IENDr   )write_preamblerv   zlibcompressobj	bytearrayr;   appendextendr9   rw   compresswrite_chunkbytesflush)	rV   r   r   
compressordatar@   r   
compressedflusheds	            r   r   Writer.write_packed  s   $ 	G$ '))$*:*:;J))+J {oFA KKNKK4y4+++'006
z??*= { &   ((t5
""$z??c'll**>?GW%1ur0   c                    UR                  [        5        [        US[        R                  " SU R
                  U R                  U R                  U R                  SSU R                  5      5        U R                  bA  [        US[        R                  " S[        [        U R                  S-  5      5      5      5        U R                  (       aL  [        US[        R                  " SU R                  -  /U R                   Vs/ s H  o"S   PM	     snQ76 5        U R                  (       a8  [!        U R                  5      u  p4[        US	U5        U(       a  [        US
U5        U R"                  bB  U R$                  (       a  SnOSn[        US
[        R                  " U/U R"                  Q76 5        U R&                  bB  U R$                  (       a  SnOSn[        US[        R                  " U/U R&                  Q76 5        U R(                  b]  U R*                  bO  U R(                  U R*                  [        U R,                  5      4n[        US[        R                  " S/UQ76 5        g g g s  snf )Ns   IHDR!2I5Br   s   gAMA!L     j@s   sBIT%dBs   PLTEs   tRNSz!1Hz!3Hs   bKGDs   pHYs!LLB)r   	signaturer   structpackr#   r$   ru   r|   rx   rr   r<   roundrq   r~   r=   make_palette_chunksrk   rJ   rl   ry   rz   r{   )rV   r   r-   r>   rA   r   tups          r   r   Writer.write_preamble  s   i  	KK

		
" ::!&++dCdjj3>N8O4P"Q <<EDKK/O2NAQ42NO <<&t||4DA!, GWa0 '~~&++c*MD<L<L*MN ??&~~&++c*LDOO*LM !!-$2H2H2T&&&&D&&'C
 &++f*Cs*CD 3U-C 3Os   I-c                    U R                   (       aQ  [        U5      [        :w  a  SU R                  S:     n[        X25      nU R	                  XR                  U5      5        gU R	                  XR                  U5      5        g)zq
Write an array that holds all the image values
as a PNG file on the output file.
See also :meth:`write` method.
r   r   N)rx   typer   ru   r   array_scanlines_interlacearray_scanlines)rV   r   pixelsr   s       r   r   Writer.write_arrayE  sf     >>F|u$4==1,-s+g'E'Ef'MNg';';F'CDr0   c              #      #    U R                   U R                  -  nSn[        U R                  5       H  nUnXR-   nXU v   M     g7f)zK
Generates rows (each a sequence of values) from
a single array of values.
r   N)r#   r~   r"   r$   )rV   r   r   stopr   starts         r   r   Writer.array_scanlinesU  sH      jj4;;&t{{#AE;Dt$$ $s   AAc           
   #   ~  #    SU R                   S:     nU R                  U R                  -  n[        U R                  U R                  5       H  nU H  u  pVn[        [        R                  " U R                  U-
  [        U5      -  5      5      nXR                  -  n	US:X  a  Xc-  n
XX-    v   M`  [        U5      nUR                  USU	 5        Xc-  XPR                  -  -   n
US-   U-  nU R                  U-  n[        U R                  5       H  nXU-   X2   XSU R                  2'   M     Uv   M     M     g7f)z
Generator for interlaced scanlines from an array.
`pixels` is the full source image as a single array of values.
The generator yields each scanline of the reduced passes in turn,
each scanline being a sequence of values.
r   r   r   r   N)ru   r#   r~   r'   r$   r<   mathceilfloatr   r   r"   )rV   r   r   r   linesr3   r   r   pprreduced_row_lenoffsetr   
end_offsetskipr@   s                  r   r    Writer.array_scanlines_interlacec  s&     4==1$%jj4;;& $DJJ<E$e$))TZZ!^uU|$CDE"%"3A:WF &,77 Cj

6!O451{{?2!es]
{{U*t{{+A,2A:
3Q,RC(T[[() ,	+  % =s   D;D=)rs   rl   ru   rw   r}   r|   rt   rv   rr   rJ   r$   rx   r=   r~   r   rq   rk   r{   r#   ry   rz   )rR   rY   rZ   r[   r`   re   r   r   r   r   r   r   r   r   r\   r   r0   r   r   r   d  sr     )G7R3j0<4lHETE %&r0   r   c                 j   [        U5      nU R                  [        R                  " S[	        U5      5      5        U R                  U5        U R                  U5        [
        R                  " U5      n[
        R                  " X#5      nUS-  nU R                  [        R                  " SU5      5        g)zF
Write a PNG chunk to the output file, including length and
checksum.
!Il    N)r   r   r   r   r9   r   crc32)r   tagr   checksums       r   r   r     s|     ;DMM&++dCI./MM#MM$zz#Hzz$)H	HMM&++dH-.r0   c                 X    U R                  [        5        U H  n[        U /UQ76   M     g)z,Create a PNG file by writing out the chunks.N)r   r   r   )outchunkschunks      r   r   r     s'     IIiC %  r0   c           
   #     ^
^#    U Vs/ s H,  n[        SUS   -  S-
  5      [        SUS   -  S-
  5      -  PM.     snm
[        S U 5       5      n[        U5      S:X  d   eUu  nSUS:     n[        U5      nU  HR  n[        U[	        U5      5      n[        U5       H'  m[        UU
U4S jUTSU2    5       5      n	XTSU2'   M)     Uv   MT     gs  snf 7f)	z
Take each row in rows (an iterator) and yield
a fresh row with the pixels scaled according to
the rescale parameters in the list `rescale`.
Each element of `rescale` is a tuple of
(source_bitdepth, target_bitdepth),
with one element per channel.
r   r   r   c              3   *   #    U  H	  oS    v   M     g7f)r   Nr   )r   r-   s     r   r   rescale_rows.<locals>.<genexpr>  s     1AQ4s   r   r   c              3   X   >#    U  H  n[        [        TT   U-  5      5      v   M!     g 7fr   r<   r   )r   r3   fsr@   s     r   r   r     s&     &Vos5A+;'<'<os   '*N)r   setr9   r   r,   r"   )r   rq   r-   target_bitdepthstarget_bitdepthtypecoden_chansr   rescaled_rowchannelr   r@   s             @@r   r   r     s      @G	Gw!%QqT	A
qAaDy1}!5
5w	GB 111 A%%%)_Oa'(H 'lGXtCy1wAH&Vc!*W*o&VWG'.G$     
Hs   C3CBCc              #   j  ^^#    TS:  d   eST-  S:X  d   e[        ST-  5      nU4S jmU  H  n[        U5      n[        [        U5      5      n[        R
                  " XR-  5      U-  U-
  nUR                  S/[        U5      -  5        [        XB5      n[        U4S jU 5       5      v   M     g7f)zbYield packed rows that are a byte array.
Each byte is packed with the values from several pixels.
r   r   c                 .   > SnU  H  nUT-  U-   nM     U$ )zGTake a block of (2, 4, or 8) values,
and pack them into a single byte.
r   r   )blockresvru   s      r   	make_bytepack_rows.<locals>.make_byte  s'    
 A(?a'C 
r0   c              3   4   >#    U  H  nT" U5      v   M     g 7fr   r   )r   r   r   s     r   r   pack_rows.<locals>.<genexpr>  s     =fU	%((fs   N)r<   r   r   r9   r   r   r   r/   )	r   ru   spbr   r   r.   extrablocksr   s	    `      @r   r   r     s     
 a<<x<1 a(l
C cN #a&M		!'"S(1,	!s5z!" q=f=== s   B/B3c              #   ~   #    U  H3  nS[        U5      -  n[        [        R                  " U/UQ76 5      v   M5     g7f)zLUnpack each row from being 16-bits per value,
to being a sequence of bytes.
!%dHN)r9   r   r   r   )r   r   r   s      r   r   r     s8      s3xC.#.// s   ;=c                     [        5       n[        5       nU  H<  nUR                  USS 5        [        U5      S:  d  M(  UR                  US   5        M>     U(       a  X4$ US4$ )z
Create the byte sequences for a ``PLTE`` and
if necessary a ``tRNS`` chunk.
Returned as a pair (*p*, *t*).
*t* will be ``None`` if no ``tRNS`` chunk is necessary.
r   r7   N)r   r   r9   r   )r=   r>   rA   r3   s       r   r   r     s]     	AA	1Qq6A:HHQqTN  	td7Nr0   c                    U (       ae  [        U5      S:w  a  [        S5      eUu  nUS;  a  [        S5      eUb  [        S5      eU(       a  [        S5      eU(       a  [        S5      eUS4$ U(       a7  U(       d0  Uu  nUS	;   a  US4$ US
:  a  SnOUS:X  a  SnO
US;   d   eS
nXQU4/4$ U(       d	  U(       a   e[        [        U5      5      nUS;   a  Uu  nUS4$ S[	        U5      S
:     nXQ Vs/ s H  owU4PM     sn4$ s  snf )z#
Returns (bitdepth, rescale) pair.
r   z0with palette, only a single bitdepth may be used)r   r   r   r   z,with palette, bitdepth must be 1, 2, 4, or 8Nz&transparent and palette not compatiblez alpha and palette not compatiblez$greyscale and palette not compatibler   r   r   r   ri   r   ri   r7   r   )   rn      ))r   )ri   )r   ri   )r9   r:   tupler   max)r=   ru   rk   rs   rJ   targetbitdepth	depth_setr   s           r   rp   rp     s6   
 x=A RSS<' NOO" HII BCC FGG~ ''T>!a<N]Ny(((N> :;;;	!!c(m$IM!~S]Q./NBA/BBBBs   2Dz(LA?|RGBA?);?([0-9]*))flagsc                    [        U5      n[        R                  U5      nU(       d  [        S5      eUR	                  5       u  pU(       a  [        U5      nSU;   a   [        US   5      SU;   :w  a  [        S5      eSU;   US'   SU;   nSU;   a  [        US   5      U:w  a  [        S5      eXRS'   U(       a4  UR                  S5      (       a  XBS   :w  a  [        S	XBS   4-  5      eXBS'   [        UR                  S
5      UR                  S5      UR                  S5      5      u  pgU(       a  XbS'   U(       a  XrS'   SU;  a   [        U 5      US'   [        U5      nSU;   a  US   U:w  a  [        S5      e[        R                  " U 5      u  p	[        U	5      n
A	U
nSU;  a  [        U
5      U-  nXbS'   SU;  a4   UR                  nUR                   S:X  a  SnOSUR"                  -  n XBS'   S H
  nX;   a  M
   e   ['        X5      $ ! [         a    [        S5      ef = f! [$         a&     SUR"                  -  n NT! [$         a    Sn  Ncf = ff = f)a   
Create a PNG :class:`Image` object from a 2-dimensional array.
One application of this function is easy PIL-style saving:
``png.from_array(pixels, 'L').save('foo.png')``.

Unless they are specified using the *info* parameter,
the PNG's height and width are taken from the array size.
The first axis is the height; the second axis is the
ravelled width and channel index.
The array is treated is a sequence of rows,
each row being a sequence of values (``width*channels`` in number).
So an RGB image that is 16 pixels high and 8 wide will
occupy a 2-dimensional array that is 16x24
(each row will be 8*3 = 24 sample values).

*mode* is a string that specifies the image colour format in a
PIL-style mode.  It can be:

``'L'``
  greyscale (1 channel)
``'LA'``
  greyscale with alpha (2 channel)
``'RGB'``
  colour image (3 channel)
``'RGBA'``
  colour image with alpha (4 channel)

The mode string can also specify the bit depth
(overriding how this function normally derives the bit depth,
see below).
Appending ``';16'`` to the mode will cause the PNG to be
16 bits per channel;
any decimal from 1 to 16 can be used to specify the bit depth.

When a 2-dimensional array is used *mode* determines how many
channels the image has, and so allows the width to be derived from
the second array dimension.

The array is expected to be a ``numpy`` array,
but it can be any suitable Python sequence.
For example, a list of lists can be used:
``png.from_array([[0, 255, 0], [255, 0, 255]], 'L')``.
The exact rules are: ``len(a)`` gives the first dimension, height;
``len(a[0])`` gives the second dimension.
It's slightly more complicated than that because
an iterator of rows can be used, and it all still works.
Using an iterator allows data to be streamed efficiently.

The bit depth of the PNG is normally taken from
the array element's datatype
(but if *mode* specifies a bitdepth then that is used instead).
The array element's datatype is determined in a way which
is supposed to work both for ``numpy`` arrays and for Python
``array.array`` objects.
A 1 byte datatype will give a bit depth of 8,
a 2 byte datatype will give a bit depth of 16.
If the datatype does not have an implicit size,
like the above example where it is a plain Python list of lists,
then a default of 8 is used.

The *info* parameter is a dictionary that can
be used to specify metadata (in the same style as
the arguments to the :class:`png.Writer` class).
For this function the keys that are useful are:

height
  overrides the height derived from the array dimensions and
  allows *a* to be an iterable.
width
  overrides the width derived from the array dimensions.
bitdepth
  overrides the bit depth derived from the element datatype
  (but must match *mode* if that also specifies a bit depth).

Generally anything specified in the *info* dictionary will
override any implicit choices that this function would otherwise make,
but must match any explicit ones.
For example, if the *info* dictionary has a ``greyscale`` key then
this must be true when mode is ``'L'`` or ``'LA'`` and
false when mode is ``'RGB'`` or ``'RGBA'``.
z1mode string should be 'RGB' or 'L;16' or similar.rJ   Lz$info['greyscale'] should match mode.Ars   z info['alpha'] should match mode.ru   z1bitdepth (%d) should match bitdepth of info (%d).rD   r#   r$   z4len(a) does not work, supply info['height'] instead.r~   z!info['planes'] should match mode.r   r   r   )r#   r$   ru   rJ   rs   )dictRegexModeDecodematchrN   groupsr<   ro   r:   getrE   r9   rG   r   teenextdtypekinditemsizeAttributeErrorr   )r   modeinfor  ru   rs   r#   r$   r~   rA   r   testelementr
  things                 r   r	   r	   5  s   j :D !!$'EGHH\\^NDx= d[!"sd{3 FGGtD4KE$W%' BCCM 88JHZ0@$@C*-./  $Z   0$((72CTXXhEWXMEWXt	X VDN YF4>V#;<<
 ==DA
q'C	KdCF"W	.%%E zzS u~~-#ZF}} G >Y  	X VWW	X0  	{333!  		s6   H =H$ H!$
I/I  IIIIc                   *    \ rS rSrSrS rS rS rSrg)r   i  zA PNG image.  You can create an :class:`Image` object from
an array of pixels by calling :meth:`png.from_array`.  It can be
saved to disk with the :meth:`save` method.
c                     Xl         X l        g)zF
.. note ::

  The constructor is not public.  Please do not call it.
N)r   r  )rV   r   r  s      r   r   Image.__init__  s     		r0   c                     [        S0 U R                  D6n[        US5       nUR                  X0R                  5        SSS5        g! , (       d  f       g= f)a  Save the image to the named *file*.

See `.write()` if you already have an open file object.

In general, you can only call this method once;
after it has been called the first time the PNG image is written,
the source data will have been streamed, and
cannot be streamed again.
wbNr   )r   r  openr   r   )rV   filewfds       r   save
Image.save  s=     TYY$GGB		" s   A
Ac                 d    [        S0 U R                  D6nUR                  XR                  5        g)a
  Write the image to the open file object.

See `.save()` if you have a filename.

In general, you can only call this method once;
after it has been called the first time the PNG image is written,
the source data will have been streamed, and
cannot be streamed again.
Nr   )r   r  r   r   )rV   r  r  s      r   r   Image.write  s%     TYY	ii r0   )r  r   N)	rR   rY   rZ   r[   r`   r   r  r   r\   r   r0   r   r   r     s    
# !r0   r   c                       \ rS rSrSrS!S jrS"S jrS rS rS r	S	 r
S#S
 jrS rS rS"S jrS rS"S jrS rS rS rS rS rS rS rS"S jrS rS$S jrS rS rS rS rS rS r S r!g)%r   i  z)
Pure Python PNG decoder in pure Python.
Nc                    USLUSL-   USL-   USL-   nUS:w  a  [        S5      eSU l        SU l        SU l        Ub>  [	        U5      (       a  UnO+[        U[        5      (       a  UnO[        US5      (       a  UnUb  [        R                  " U5      U l
        gUb  [        US5      U l
        gUb  X0l
        g[        S5      e)aH  
The constructor expects exactly one keyword argument.
If you supply a positional argument instead,
it will guess the input type.
Choose from the following keyword arguments:

filename
  Name of input file (a PNG file).
file
  A file-like object (object with a read() method).
bytes
  ``bytes`` or ``bytearray`` with PNG data.

Nr   z!Reader() takes exactly 1 argumentreadrbz'expecting filename, file or bytes array)rG   r   rk   atchunkr4   r2   strhasattrioBytesIOr  r  r:   )rV   _guessfilenamer  r   keywords_supplieds         r   r   Reader.__init__  s      4t#%4! D " 	 !?@@ 
 vFC((!((

5)DI!Xt,DII IJJr0   c                 :   U R                  5         U R                  (       d  U R                  5       U l        U R                  (       d  [        S5      eU R                  u  p#SU l        U R                  R                  U5      n[        U5      U:w  a  [        SX24-  5      eU R                  R                  S5      n[        U5      S:w  a  [        SU-  5      e[        R                  " U5      n[        R                  " XF5      n[        R                  " SU5      nXV:w  ay  [        R                  " SU5      u  n[        R                  " SU5      u  nSUR                  S5      UU4-  n	U(       a  [        R                  " U	[        5        X44$ [        U	5      eX44$ )	aQ  
Read the next PNG chunk from the input file;
returns a (*type*, *data*) tuple.
*type* is the chunk's type as a byte string
(all PNG chunk types are 4 bytes long).
*data* is the chunk's data content, as a byte string.

If the optional `lenient` argument evaluates to `True`,
checksum failures will raise warnings rather than exceptions.
zNo more chunks.Nz*Chunk %s too short for required %i octets.r   z Chunk %s too short for checksum.r   z-Checksum error in %s chunk: 0x%08X != 0x%08X.ascii)validate_signaturer#  _chunk_len_typerc   r  r!  r9   r   r   r   r   unpackdecodewarningswarnRuntimeWarning)
rV   lenientlengthr   r   r   verifyr   r   messages
             r   r   Reader.chunkN  s^    	! ||//1DL||.//||yy~~f%t9<~M  99>>!$x=A?$FGGD!D)T6*==x0DQ==v.DQEG$I G
 g~6 z !))zr0   c              #   L   #     U R                  5       u  pX4v   US:X  a  gM   7f)zRReturn an iterator that will yield each chunk as a
(*chunktype*, *content*) pair.
r   N)r   )rV   rA   r   s      r   r   Reader.chunks}  s-     
 ::<DA$JG|	 s   "$c                     UnUS:X  a  U$ US;  a  [        S5      e[        SU R                  5      nU(       d  [        S/[	        U5      -  5      nS[
        [        [        [        4U   nU" XRX45        U$ )a  
Undo the filter for a scanline.
`scanline` is a sequence of bytes that
does not include the initial filter type byte.
`previous` is decoded previous scanline
(for straightlaced images this is the previous pixel row,
but for interlaced images, it is
the previous scanline in the reduced image,
which in general is not the previous pixel row in the final image).
When there is no previous scanline
(the first row of a straightlaced image,
or the first row in one of the passes in an interlaced image),
then this argument should be ``None``.

The scanline will have the effects of filtering removed;
the result will be returned as a fresh sequence of bytes.
r   )r   r   r7   r   zTInvalid PNG Filter Type.  See http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters .r   N)	r^   r   r   r   r9   undo_filter_subundo_filter_upundo_filter_averageundo_filter_paeth)rV   filter_typescanlinepreviousresultfufns          r   undo_filterReader.undo_filter  s    ( !Ml*M  DJJ  !s8}!45H
 
  	2*r0   c           
      R   U R                   U R                  -  nX R                  -  nU R                  S:  a  [	        SS/U-  5      nO[        S/U-  5      nSn[        U R                   U R                  5       GH(  nSnU GH  u  pn
[        [        R                  " U R                   U-
  [        U
5      -  5      5      n[        [        R                  " U R                  U-  5      5      nX   nUS-  nXX\-    nX\-  nU R                  XU5      nU R                  X{S9nU
S:X  a  US:X  d   eX-  nXUUU-   & M  X-  XR                  -  -   nU	S-   U-  nU R                  U
-  n[        U R                  5       H  nUUSU R                  2   UUU-   UU2'   M      GM     GM+     U$ )z_
Read raw pixel data, undo filters, deinterlace, and flatten.
Return a single array of values.
r   Hr   Nr   )r#   )r#   r~   r$   ru   r   r   r'   r<   r   r   r   r   rG  _bytes_to_valuesr"   )rV   rawr   vpir   source_offsetr   reconr3   r   r   r   row_sizerA  rB  flatr   r   r   r@   s                       r   _deinterlaceReader._deinterlace  s    jj4;;& KK ==1cA39%A1#)$A#DJJ<E E$e$))TZZ!^uU|$CDEtyyc)9:;!0"}/GH)((F,,U,>A:6M6WF/3fv|,Wq;;6F"#a%3J;;.D"4;;/<@AQdkkAQ<R&1*zD89 0+  % =: r0   c              #   D   #    U H  nU R                  U5      v   M     g7f)z
Iterator that yields each scanline;
each scanline being a sequence of values.
`byte_rows` should be an iterator that yields
the bytes of each row in turn.
N)rK  )rV   	byte_rowsr   s      r   _iter_bytes_to_valuesReader._iter_bytes_to_values  s"      C'',, s    c           	      >   U R                   S:X  a  [        U5      $ U R                   S:X  a0  [        S[        R                  " S[        U5      S-  -  U5      5      $ U R                   S:  d   eUc  U R                  nSU R                   -  n[        5       nSU R                   -  S-
  n[        [        [        U5      5      5       Vs/ s H  o`R                   U-  PM     nnU H)  nUR                  U Vs/ s H	  oeX-	  -  PM     sn5        M+     USU $ s  snf s  snf )z}Convert a packed row of bytes into a row of values.
Result will be a freshly allocated object,
not shared with the argument.
r   ri   rJ  r   r   Nr   )ru   r   r   r   r0  r9   r#   reversedr*   r"   r   )	rV   bsr#   r   r   maskr@   shiftsos	            r   rK  Reader._bytes_to_values  s     ==AR= ==BfmmFc"gl,CRHII}}q   =JJE4== k$--!#-5d5:6F-GH-G--!#-GHAJJ8A89 6E{ I8s   D5D
c              #   l  #    U R                   n[        5       nSnU Hg  nUR                  U5        [        U5      US-   :  d  M(  US   nUSUS-    nUSUS-   2	 U R	                  XgU5      nUv   [        U5      US-   :  a  M?  Mi     [        U5      S:w  a  [        S5      e[        U5      S:X  d   eg7f)zIterator that undoes the effect of filtering;
yields each row as a sequence of packed bytes.
Assumes input is straightlaced.
`byte_blocks` should be an iterable that yields the raw bytes
in blocks of arbitrary size.
Nr   r   z'Wrong size for decompressed IDAT chunk.)	row_bytesr   r   r9   rG  r^   )rV   byte_blocksr"  r   rO  
some_bytesrA  rB  s           r   _iter_straight_packedReader._iter_straight_packed  s      ^^K %JHHZ a&BF"dQa=hQhK((F a&BF" & q6Q; GHH1v{{s   ?B4=B40B4c                     U R                   (       a  gU R                  R                  S5      U l         U R                   [         :w  a  [        S5      eg)zZ
If signature (header) has not been read then read and
validate it; otherwise do nothing.
Nr   zPNG file has invalid signature.)r   r  r!  r^   rU   s    r   r.  Reader.validate_signature2  s?     >>*>>Y&?@@ 'r0   c                     U R                  5          U R                  (       d-  U R                  5       U l        U R                  c  [        S5      eU R                  S   S:X  a  gU R	                  US9  Mc  )aN  
Extract the image metadata by reading
the initial part of the PNG file up to
the start of the ``IDAT`` chunk.
All the chunks that precede the ``IDAT`` chunk are
read and either processed for metadata or discarded.

If the optional `lenient` argument evaluates to `True`,
checksum failures will raise warnings rather than exceptions.
Nz!This PNG file has no IDAT chunks.r   r   r5  )r.  r#  r/  r^   process_chunk)rV   r5  s     r   preambleReader.preamble>  si     	!<<#335<<'%&IJJ||A')w/ r0   c                    U R                   R                  S5      nU(       d  g[        U5      S:w  a  [        S5      e[        R
                  " SU5      u  p#US:  a  [        SX24-  5      e[        [        U5      5      nU[        [        SS5      5      [        [        S	S
5      5      -  ::  d  [        S[        U5      -  5      eX#4$ )z
Reads just enough of the input to
determine the next chunk's length and type;
return a (*length*, *type*) pair where *type* is a byte sequence.
If there are no more chunks, ``None`` is returned.
r   Nz1End of file whilst reading chunk length and type.z!I4srh   zChunk %s is too large: %d.A   [   a   {   z Chunk %r has invalid Chunk Type.)
r  r!  r9   r^   r   r0  r   r   r"   r*   )rV   r3   r6  r   
type_bytess        r   r/  Reader._chunk_len_typeU  s     IINN1q6Q;QRR}}VQ/I:d^KLL 4)
c%B-03uR~3FFF@4:MNN|r0   c                     U R                  US9u  p#SUR                  S5      -   n[        XS5      nU(       a	  U" U5        gg)a5  
Process the next chunk and its data.
This only processes the following chunk types:
``IHDR``, ``PLTE``, ``bKGD``, ``tRNS``, ``gAMA``, ``sBIT``, ``pHYs``.
All other chunk types are ignored.

If the optional `lenient` argument evaluates to `True`,
checksum failures will raise warnings rather than exceptions.
rh  	_process_r-  N)r   r1  getattr)rV   r5  r   r   methodms         r   ri  Reader.process_chunkl  sD     ZZZ0
t{{733D$'dG r0   c                 @   [        U5      S:w  a  [        S5      e[        R                  " SU5      u  U l        U l        U l        U l        U l        U l	        U l
        [        U R                  U R                  5        U R                  S:w  a  [        SU R                  -  5      eU R                  S:w  a  [        SU R                  -  5      eU R                  S;  a  [        SU R                  -  5      e[        U R                  S	-  5      nU R                  S
-  (       + n[        U R                  S-  5      nSU=(       d    U   nXT-   nX l        X0l        X@l        XPl        X`l        [%        U R                  5      [%        S5      -  U-  U l        [)        U R&                  5      U R&                  :X  a  [)        U R&                  5      U l        [)        [*        R,                  " U R                  U R&                  -  5      5      U l        S U l        S U l        S U l        g )Nr   z IHDR chunk has incorrect length.r   r   zUnknown compression method %dzTUnknown filter method %d, see http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters .)r   r   z`Unknown interlace method %d, see http://www.w3.org/TR/2003/REC-PNG-20031110/#8InterlaceMethods .r   r   r   rj   r   )r9   r^   r   r0  r#   r$   ru   r|   rv   filterrx   check_bitdepth_colortypero   rt   rJ   rs   r}   r~   r   r   r<   r   r   r`  pltetrnssbit)rV   r   rt   rJ   rs   r}   r~   s          r   _process_IHDRReader._process_IHDR}  s   t9?@AA MM'4(	
JKMOKN 	!@q =@P@PPQQ;;!N++ 
 >>'~~&  !+,1,-	T__q()i384% "
(4==)E!H4v=
tzz?djj(TZZDJTYYtzzDJJ'>?@ 	 		r0   c                     U R                   (       a  [        R                  " S5        Xl         [        U5      S-  S:w  a  [	        S5      e[        U5      SU R
                  -  S-  :  a  [	        S5      e[        U5      S:X  a  [	        S5      eg )NzMultiple PLTE chunks present.r7   r   z.PLTE chunk's length should be a multiple of 3.r   zPLTE chunk is too long.zEmpty PLTE is not allowed.)r|  r2  r3  r9   r^   ru   rV   r   s     r   _process_PLTEReader._process_PLTE  sy    99MM9:	t9q=ANOOt94==(A--788t9>:;; r0   c                 H    U R                   (       aD  U R                  (       d  [        R                  " S5        [        R
                  " SU5      U l        g [        R
                  " SU R                  -  U5      U l        g ! [        R                   a    [        S5      ef = f)Nz)PLTE chunk is required before bKGD chunk.Br   z bKGD chunk has incorrect length.)
rt   r|  r2  r3  r   r0  rl   r}   errorr^   r  s     r   _process_bKGDReader._process_bKGD  ss    	B}}yyMM"MN"(--T":"(--9J9J0JD"Q|| 	B@AA	Bs   AB )B  B!c                    Xl         U R                  (       aY  U R                  (       d  [        R                  " S5        g [        U5      [        U R                  5      S-  :  a  [        S5      eg U R                  (       a  [        SU R                  -  5      e [        R                  " SU R                  -  U5      U l        g ! [        R                   a    [        S5      ef = f)Nz)PLTE chunk is required before tRNS chunk.r7   ztRNS chunk is too long.z,tRNS chunk is not valid with colour type %d.r   z tRNS chunk has incorrect length.)r}  rt   r|  r2  r3  r9   r^   rs   r|   r   r0  r}   rk   r  r  s     r   _process_tRNSReader._process_tRNS  s    	==99IJt9s499~11 &&?@@ 2
 zz!BT__T F#)==$:K:K1KT#R << F!"DEEFs   )C  C%c                      [         R                  " SU5      S   S-  U l        g ! [         R                   a    [	        S5      ef = f)Nr   r   r   z gAMA chunk has incorrect length.)r   r0  rr   r  r^   r  s     r   _process_gAMAReader._process_gAMA  sE    	BtT215@DJ|| 	B@AA	Bs	   "%  Ac                     Xl         U R                  (       a  [        U5      S:w  d*  U R                  (       d%  [        U5      U R                  :w  a  [	        S5      eg g )Nr7   z sBIT chunk has incorrect length.)r~  rt   r9   r~   r^   r  s     r   _process_sBITReader._process_sBIT  sF    	MMD	Q==D	T[[(@AA ) !r0   c                     Xl         Sn[        U5      [        R                  " U5      :w  a  [	        S5      e[        R
                  " X!5      u  U l        U l        n[        U5      U l	        g )Nr   z pHYs chunk has incorrect length.)
physr9   r   calcsizer^   r0  ry   rz   ro   r{   )rV   r   r   units       r   _process_pHYsReader._process_pHYs  sT    	t9,,@AA?E}}S?W< 6!$Zr0   c                   ^ ^^ UU 4S jnT R                  TS9  [        U" 5       5      mT R                  (       a  UU 4S jnU" 5       nO T R                  T R	                  T5      5      n[        5       nSR                  5        H  n[        T U5      XV'   M     T R                  T R                  4US'   SR                  5        H  n[        T US5      nUc  M  XuU'   M     [        T SS5      (       a.  [        T R                  T R                  T R                  5      US	'   T R                  (       a  T R                  5       US
'   T R                  T R                  XE4$ )a   
Read the PNG file and decode it.
Returns (`width`, `height`, `rows`, `info`).

May use excessive memory.

`rows` is a sequence of rows;
each row is a sequence of values.

If the optional `lenient` argument evaluates to True,
checksum failures will raise warnings rather than exceptions.
c               3      >#     TR                  TS9u  pU S:X  a  gU S:w  a  M!  TR                  (       a'  TR                  (       d  [        R                  " S5        Uv   M^  7f)z8Iterator that yields all the ``IDAT`` chunks as strings.rh  r   r   z(PLTE chunk is required before IDAT chunkN)r   rt   r|  r2  r3  )r   r   r5  rV   s     r   iteridatReader.read.<locals>.iteridat	  sU     !ZZZ8
7?7? ==MM"LM
 s   A A#rh  c               3      >#    [        [        R                  " T6 5      n STR                  S:     nTR	                  U 5      nTR
                  TR                  -  n[        S[        U5      U5       H  n[        XXDU-    5      nUv   M     g7f)z&Yield each row from an interlaced PNG.r   r   r   N)
r   r   r   ru   rR  r#   r~   r"   r9   r   )rZ  	arraycodevaluesr   r@   r   rL  rV   s         r   rows_from_interlace(Reader.read.<locals>.rows_from_interlace  s      y45 !23	 **2.jj4;;.q#f+s3A	!#g+>?CI 4s   BBz)greyscale alpha planes bitdepth interlacerD   zgamma transparent backgroundNry   physicalr=   )rj  
decompressrx   rV  rc  r  splitru  r#   r$   
Resolutionry   rz   r{   r|  r=   )	rV   r5  r  r  r   r  attrr   rL  s	   ``      @r   r!  Reader.read  s(   	 	g&$>> '(D--d.H.H.MNDv?EEGD t,DJ H

DKK0V288:DdD)A}T
 ; 4,d33)&&(>(>@R@R D 99"llnDOzz4;;22r0   c                     U R                  5       u  pp4SUS   S:     n[        U[        R                  " U6 5      nXX44$ )a  
Read a PNG file and decode it into a single array of values.
Returns (*width*, *height*, *values*, *info*).

May use excessive memory.

`values` is a single array.

The :meth:`read` method is more stream-friendly than this,
because it returns a sequence of rows.
r   ru   r   )r!  r   r   r   )rV   r3   r   pixelr  r  s         r   	read_flatReader.read_flat>  sH     !IIKej)A-.	i%!89U  r0   c           
         U R                   (       d  [        S5      e[        [        SU R                   5      S5      nU R                  (       d  US:X  aw  [        SU R                  =(       d    / 5      nUR                  S/[        U5      [        U5      -
  -  5        [        [        [        R                  U[        US5      5      5      nU$ )a%  
Returns a palette that is a sequence of 3-tuples or 4-tuples,
synthesizing it from the ``PLTE`` and ``tRNS`` chunks.
These chunks should have already been processed (for example,
by calling the :meth:`preamble` method).
All the tuples are the same size:
3-tuples if there is no ``tRNS`` chunk,
4-tuples when there is a ``tRNS`` chunk.

Assumes that the image is colour type
3 and therefore a ``PLTE`` chunk is required.

If the `alpha` argument is ``'force'`` then an alpha channel is
always added, forcing the result to be a sequence of 4-tuples.
z6Required PLTE chunk is missing in colour type 3 image.r  r7   forcer8   r   )r|  r^   r/   r   r}  r   r9   r*   mapoperatoradd)rV   rs   r|  r}  s       r   r=   Reader.paletteP  s    " yyVWWU3		*A.99(diio2.DKKTSY!678HLL$dA?@Dr0   c                   ^
^^^^^ U R                  5         U R                  (       d2  U R                  (       d!  U R                  (       d  U R	                  5       $ U R	                  5       u  pp4U R                  (       a\  SUS'   [        U R                  5      US'   SUS'   S[        U R                  5      -   US'   U R                  5       mU4S jnU" U5      nO[U R                  (       aJ  U R                  m
S	US   -  S
-
  mUS   mSUS'   US==   S
-  ss'   SUS   S:     mU
UUU4S jnU" U5      nSnU R                  (       a  [        R                  " S[        U R                  5      -  U R                  5      n[        U5      nXtS   :  a  [        SXR                  4-  5      e[        U5      S::  a  [        SU-  5      eU(       a  US   U-
  mXtS'   U4S jn	U	" U5      nXX44$ )aK  
Returns the image data as a direct representation of
an ``x * y * planes`` array.
This removes the need for callers to deal with
palettes and transparency themselves.
Images with a palette (colour type 3) are converted to RGB or RGBA;
images with transparency (a ``tRNS`` chunk) are converted to
LA or RGBA as appropriate.
When returned in this format the pixel values represent
the colour value directly without needing to refer
to palettes or transparency information.

Like the :meth:`read` method this method returns a 4-tuple:

(*width*, *height*, *rows*, *info*)

This method normally returns pixel values with
the bit depth they have in the source image, but
when the source PNG has an ``sBIT`` chunk it is inspected and
can reduce the bit depth of the result pixels;
pixel values will be reduced according to the bit depth
specified in the ``sBIT`` chunk.
PNG nerds should note a single result bit depth is
used for all channels:
the maximum of the ones specified in the ``sBIT`` chunk.
An RGB565 image will be rescaled to 6-bit RGB666.

The *info* dictionary that is returned reflects
the `direct` format and not the original source image.
For example, an RGB source image with a ``tRNS`` chunk
to represent a transparent colour,
will start with ``planes=3`` and ``alpha=False`` for the
source image,
but the *info* dictionary returned by this method
will have ``planes=4`` and ``alpha=True`` because
an alpha channel is synthesized and added.

*rows* is a sequence of rows;
each row being a sequence of values
(like the :meth:`read` method).

All the other aspects of the image data are not changed.
Frt   rs   r   ru   r7   r~   c              3      >#    U  H7  nU Vs/ s H  nTU   PM
     nn[        S[        R                  " U6 5      v   M9     g s  snf 7f)Nr  )r   r   r   )r   r   r3   r|  s      r   iterpal Reader.asDirect.<locals>.iterpal  sA     !C,/0Cq47CC0Y__c%:;; "0s   
AA+Ar   r   Tr   c              3   &  >#    U  H  n[        UT5      n[        TR                  U5      n[        TR                  U5      n[	        [        U5      5      n[        T[        R                  " [        [        R                  X5      6 5      v   M     g 7fr   )r/   r  __ne____mul__r*   r+   r   r   r   r  r  )r   r   opaitr   r~   r   s      r   itertrns!Reader.asDirect.<locals>.itertrns  sl     !C  V,Cbii-Cfnnc2Cs3x.C)//3x||S;V*WXX "s   BBNr   z!sBIT chunk %r exceeds bitdepth %dr   zsBIT chunk %r has a 0-entryc              3   X   >#    U  H  nU Vs/ s H  o"T-	  PM	     snv   M     g s  snf 7fr   r   )r   r   r>   shifts      r   	itershift"Reader.asDirect.<locals>.itershift  s*     !C/23s!:s33 "3s   
*%*)rj  rt   r}  r~  r!  ro   r=   rk   r   r0  r9   r   rN   ru   min)rV   r3   r   r   r  r  r  r   r~  r  r  r   r~   r|  r  r   s             @@@@@@r   asDirectReader.asDirectj  s   Z 	 }}TYYtyy99;!YY[f==$D ODM Ddii0DN<<>D<
 V_FYY !!B$z**Q.F(^F DMNaND,q01HY Y f%F99==TYY!7CD YNZ 00?4BWWXX4yA~9D@AA$~5E-4 v&FV!!r0   c                    ^	^
 U" 5       u  p4m
nSUS   -  S-
  nSU-  S-
  n[        U5      [        U5      -  m	X%S'   U	U
4S jnXg:X  a  X4T
U4$ X4U" 5       U4$ )z2Helper used by :meth:`asRGB8` and :meth:`asRGBA8`.r   ru   r   c            
   3   ~   >#    T H-  n U  Vs/ s H  n[        [        UT-  5      5      PM     snv   M/     g s  snf 7fr   r   )r   r3   factorr   s     r   	iterscale%Reader._as_rescale.<locals>.iterscale  s6     7:;s!s5V,-s;; ;s   
=!8=)r   )rV   r  r   r#   r$   r  r   targetmaxvalr  r  r   s            @@r   _as_rescaleReader._as_rescale  sz     '*e#vtd:&&*.(1,|$uV}4)Z	< !&$..)+t33r0   c                 :    U R                  U R                  S5      $ )a  
Return the image data as an RGB pixels with 8-bits per sample.
This is like the :meth:`asRGB` method except that
this method additionally rescales the values so that
they are all between 0 and 255 (8-bit).
In the case where the source image has a bit depth < 8
the transformation preserves all the information;
where the source image has bit depth > 8, then
rescaling to 8-bit values loses precision.
No dithering is performed.
Like :meth:`asRGB`,
an alpha channel in the source image will raise an exception.

This function returns a 4-tuple:
(*width*, *height*, *rows*, *info*).
*width*, *height*, *info* are as per the :meth:`read` method.

*rows* is the pixel data as a sequence of rows.
r   )r  asRGBrU   s    r   asRGB8Reader.asRGB8  s    * 

A..r0   c                 :    U R                  U R                  S5      $ )a!  
Return the image data as RGBA pixels with 8-bits per sample.
This method is similar to :meth:`asRGB8` and :meth:`asRGBA`:
The result pixels have an alpha channel, *and*
values are rescaled to the range 0 to 255.
The alpha channel is synthesized if necessary
(with a small speed penalty).
r   )r  asRGBArU   s    r   asRGBA8Reader.asRGBA8  s     Q//r0   c                    ^^^ U R                  5       u  mnmnUS   (       a  [        S5      eUS   (       d  TUTU4$ SUS'   SUS'   US   S:  a  S	 mOS
 mUUU4S jnTX" 5       U4$ )a  
Return image as RGB pixels.
RGB colour images are passed through unchanged;
greyscales are expanded into RGB triplets
(there is a small speed overhead for doing this).

An alpha channel in the source image will raise an exception.

The return values are as for the :meth:`read` method except that
the *info* reflect the returned pixels, not the source image.
In particular,
for this method ``info['greyscale']`` will be ``False``.
rs   z0will not convert image with alpha channel to RGBrJ   Fr7   r~   ru   r   c                      [        SS/5      $ )NrJ  r   r   r   r0   r   newarrayReader.asRGB.<locals>.newarray*  s    S1#&r0   c                      [        S/5      $ )Nr   r   r   r0   r   r  r  /  s     !~%r0   c               3   t   >#    T H-  n T" 5       S-  T-  n[        S5       H
  nXUS S2'   M     Uv   M/     g 7f)Nr7   r"   )r   r   r@   r  r   r#   s      r   iterrgbReader.asRGB.<locals>.iterrgb2  s@     JNU*qA!addG "	 s   58)r  rN   )rV   r$   r  r  r  r   r#   s       @@@r   r  Reader.asRGB  s     '+mmo#vvt=JKKK &&$..![X
a'
&	 fgi--r0   c                   ^^^	 U R                  5       u  pm	nUS   (       a  US   (       d  XT	U4$ SUS   S:     nSUS   -  S-
  n[        R                  " SU-   U5      S	-  U-  mUS   S:  a  U4S
 jmOU4S jmUS   (       a  US   (       a  UU	4S jnO/US   (       a  UU	4S jnOUS   (       d
  US   (       a   eUU	4S jnSUS'   SUS'   S	US'   XU" 5       U4$ )af  
Return image as RGBA pixels.
Greyscales are expanded into RGB triplets;
an alpha channel is synthesized if necessary.
The return values are as for the :meth:`read` method except that
the *info* reflect the returned pixels, not the source image.
In particular, for this method
``info['greyscale']`` will be ``False``, and
``info['alpha']`` will be ``True``.
rs   rJ   r   ru   r   r   r   =r   c                     > [        ST 5      $ )NrJ  r   	maxbuffers   r   r  Reader.asRGBA.<locals>.newarrayP  s    S),,r0   c                     > [        T 5      $ r   r  r  s   r   r  r  U  s     ++r0   c               3   L   >#    T H  n T" 5       n[        X5        Uv   M     g 7fr   )convert_la_to_rgbar   r   r  r   s     r   convertReader.asRGBA.<locals>.convertZ  s&     !C !
A&s.G "   !$c               3   L   >#    T H  n T" 5       n[        X5        Uv   M     g 7fr   )convert_l_to_rgbar  s     r   r  r  e  s$     !C 
A%c-G "r  c               3   L   >#    T H  n T" 5       n[        X5        Uv   M     g 7fr   )convert_rgb_to_rgbar  s     r   r  r  o  s$     !C 
A'/G "r  TFr~   )r  r   r   )
rV   r#   r$   r  r   r   r  r  r  r   s
          @@@r   r  Reader.asRGBA;  s     '+mmo#vt=k!2&$..Z(1,-d:&&*KKh7!;eC	
a-
, =T+. + G}T+->>> W![Xgi--r0   )rs   r#  rl   ru   r}   r|   rt   rv   r  rz  rr   rJ   r$   rx   r  r~   r|  r   r`  r~  r   rk   r}  r{   r#   ry   rz   )NNNN)Fr   )natural)"rR   rY   rZ   r[   r`   r   r   r   rG  rR  rV  rK  rc  r.  rj  r/  ri  r  r  r  r  r  r  r  r!  r  r=   r  r  r  r  r  r  r\   r   r0   r   r   r     s    0Kd-^	6p1f	-.:
A0.."7r
<	BF*BB(A3F!$4p"d4$/.
0(.T=.r0   r   c              #      #    [         R                  " 5       nU  H  n[        UR                  U5      5      v   M!     [        UR	                  5       5      v   g7f)z
`data_blocks` should be an iterable that
yields the compressed data (from the ``IDAT`` chunks).
This yields decompressed byte strings.
N)r   decompressobjr   r  r   )data_blocksdr   s      r   r  r  {  sH      	A T*++  AGGI
s   AAc                     U S;  a  [        SU -  5      eUS;  a  [        SU-  5      eUS-  (       a  U S:  a  [        SX4-  5      eU S:  a  US;  a  [        S	X4-  5      eg
g
)z
Check that `bitdepth` and `colortype` are both valid,
and specified in a valid combination.
Returns (None) if valid, raise an Exception if not valid.
r   zinvalid bit depth %drm   zinvalid colour type %dr   r   zIndexed images (colour type %d) cannot have bitdepth > 8 (bit depth %d). See http://www.w3.org/TR/2003/REC-PNG-20031110/#table111 .)r   r7   zvIllegal combination of bit depth (%d) and colour type (%d). See http://www.w3.org/TR/2003/REC-PNG-20031110/#table111 .N)r^   )ru   	colortypes     r   r{  r{    s     ''08;<<'2Y>?? 1}AJ #$
 	
 !|	/J #$
 	
 0|r0   c                 h     [        U 5      U :H  nU=(       a    U S:  $ ! [        [        4 a     gf = f)zA non-negative integer.Fr   )r<   rG   
ValueError)r3   
is_integers     r   rH   rH     s>    Vq[
  !q&  z" s    11c                 l    Sn[        U [        U5      5       H  nX   nX4   nXg-   S-  X5'   US-  nM     g)zUndo sub filter.r   r8   r   Nr"   r9   )filter_unitrB  rC  rD  air@   r3   r   s           r   r=  r=    sD     
B ;F,KJUdN	
a	 -r0   c                 \    [        [        U5      5       H  nX   nX$   nXV-   S-  X4'   M     g)Undo up filter.r8   Nr  )r  rB  rC  rD  r@   r3   r   s          r   r>  r>    s2     3v;KKUdN	  r0   c                     U * n[        [        U5      5       H,  nX   nUS:  a  SnOX4   nX%   nXgU-   S-	  -   S-  X5'   US-  nM.     g)r   r   r   r8   Nr  )	r  rB  rC  rD  r  r@   r3   r   r   s	            r   r?  r?    s_     B3v;K6A
AKq5Q,'4/	
a  r0   c                    U * n[        [        U5      5       Hp  nX   nUS:  a  S=pxOX4   nX$   nX%   n	Xy-   U-
  n
[        X-
  5      n[        X-
  5      n[        X-
  5      nX::  a  X::  a  UnO
X::  a  U	nOUnXn-   S-  X5'   US-  nMr     g)zUndo Paeth filter.r   r8   r   N)r"   r9   abs)r  rB  rC  rD  r  r@   r3   r   rI   r   r>   papbpcprs                  r   r@  r@    s     B3v;K6IA
AAKEAIZZZ8BXBBVtO	
a'  r0   c                 ^    [        S5       H  nU SS S2   XS S2'   M     U SS S2   USS S2'   g )Nr7   r   r   r   r   r  r   rD  r@   s      r   r  r    s@    1X14a4yt!t qt!t9F14a4Lr0   c                 6    [        S5       H
  nXUSS2'   M     g)zv
Convert a grayscale image to RGBA.
This method assumes the alpha channel in result is
already correctly initialized.
r7   Nr   r  r	  s      r   r  r    s     1Xqt!t r0   c                 @    [        S5       H  nXSS2   XSS2'   M     g)zq
Convert an RGB image to RGBA.
This method assumes the alpha channel in result is
already correctly initialized.
r7   Nr   r  r	  s      r   r  r  	  s'     1X4a4yt!t r0   c                  6    [         R                  R                  $ )z!
A sys.stdin that returns bytes.
)sysstdinbufferr   r0   r   binary_stdinr  	  s    
 99r0   c                      [         R                  R                  n [         R                  S:X  a@  SSKnSSKnUR                  [         R                  R                  5       UR                  5        U $ )z"
A sys.stdout that accepts bytes.
win32r   N)	r  stdoutr  platformmsvcrtossetmodefilenoO_BINARY)r  r  r  s      r   binary_stdoutr  	  sK    
 ZZF ||wszz((*BKK8Mr0   c                 :    U S:X  a
  [        5       $ [        U S5      $ )N-r"  )r  r  )paths    r   cli_openr  +	  s    s{~dr0   )r0   );r`   __version__collectionsr&  r   r   r  rer   r  r2  r   r   __all__r   r   r!   r'   
namedtupler  r/   r4   rB   rE   rL   	ExceptionrN   r^   r:   rc   re   r   r   r   r   r   r   r   rp   compile
IGNORECASEr  r	   	fromarrayr   r   r  r{  rH   r=  r>  r?  r@  r  r  r  r  r  r  r   r0   r   <module>r(     s  DIV   	    	  
    F
 KKc2r2r2r2>		I& ##M3FG
%  F06DI D
% E 	 	2 2e eP/"!<>D0(,C` **4BMMJ " l` 	,! ,!^a. a.H&
<!#6!"r0   