
    0-Ph\{                        d Z ddlZddlZddlZddlmZmZ ddlm	Z	m
Z
  ej        e          ZdZ G d de          Z G d	 d
e          Z G d de          Z G d de          Zd Zd Zd ZddZddZddlmZmZ dS )a   Read/Write images using pillow/PIL (legacy).

Backend Library: `Pillow <https://pillow.readthedocs.io/en/stable/>`_

Pillow is a friendly fork of PIL (Python Image Library) and supports
reading and writing of common formats (jpg, png, gif, tiff, ...). While
these docs provide an overview of some of its features, pillow is
constantly improving. Hence, the complete list of features can be found
in pillows official docs (see the Backend Library link).

Parameters for Reading
----------------------
pilmode : str
    (Available for all formats except GIF-PIL)
    From the Pillow documentation:

    * 'L' (8-bit pixels, grayscale)
    * 'P' (8-bit pixels, mapped to any other mode using a color palette)
    * 'RGB' (3x8-bit pixels, true color)
    * 'RGBA' (4x8-bit pixels, true color with transparency mask)
    * 'CMYK' (4x8-bit pixels, color separation)
    * 'YCbCr' (3x8-bit pixels, color video format)
    * 'I' (32-bit signed integer pixels)
    * 'F' (32-bit floating point pixels)

    PIL also provides limited support for a few special modes, including
    'LA' ('L' with alpha), 'RGBX' (true color with padding) and 'RGBa'
    (true color with premultiplied alpha).

    When translating a color image to grayscale (mode 'L', 'I' or 'F'),
    the library uses the ITU-R 601-2 luma transform::

        L = R * 299/1000 + G * 587/1000 + B * 114/1000
as_gray : bool
    (Available for all formats except GIF-PIL)
    If True, the image is converted using mode 'F'. When `mode` is
    not None and `as_gray` is True, the image is first converted
    according to `mode`, and the result is then "flattened" using
    mode 'F'.
ignoregamma : bool
    (Only available in PNG-PIL)
    Avoid gamma correction. Default True.
exifrotate : bool
    (Only available in JPEG-PIL)
    Automatically rotate the image according to exif flag. Default True.


Parameters for saving
---------------------
optimize : bool
    (Only available in PNG-PIL)
    If present and true, instructs the PNG writer to make the output file
    as small as possible. This includes extra processing in order to find
    optimal encoder settings.
transparency:
    (Only available in PNG-PIL)
    This option controls what color image to mark as transparent.
dpi: tuple of two scalars
    (Only available in PNG-PIL)
    The desired dpi in each direction.
pnginfo: PIL.PngImagePlugin.PngInfo
    (Only available in PNG-PIL)
    Object containing text tags.
compress_level: int
    (Only available in PNG-PIL)
    ZLIB compression level, a number between 0 and 9: 1 gives best speed,
    9 gives best compression, 0 gives no compression at all. Default is 9.
    When ``optimize`` option is True ``compress_level`` has no effect
    (it is set to 9 regardless of a value passed).
compression: int
    (Only available in PNG-PIL)
    Compatibility with the freeimage PNG format. If given, it overrides
    compress_level.
icc_profile:
    (Only available in PNG-PIL)
    The ICC Profile to include in the saved file.
bits (experimental): int
    (Only available in PNG-PIL)
    This option controls how many bits to store. If omitted,
    the PNG writer uses 8 bits (256 colors).
quantize:
    (Only available in PNG-PIL)
    Compatibility with the freeimage PNG format. If given, it overrides
    bits. In this case, given as a number between 1-256.
dictionary (experimental): dict
    (Only available in PNG-PIL)
    Set the ZLIB encoder dictionary.
prefer_uint8: bool
    (Only available in PNG-PIL)
    Let the PNG writer truncate uint16 image arrays to uint8 if their values fall
    within the range [0, 255]. Defaults to true for legacy compatibility, however
    it is recommended to set this to false to avoid unexpected behavior when
    saving e.g. weakly saturated images.

quality : scalar
    (Only available in JPEG-PIL)
    The compression factor of the saved image (1..100), higher
    numbers result in higher quality but larger file size. Default 75.
progressive : bool
    (Only available in JPEG-PIL)
    Save as a progressive JPEG file (e.g. for images on the web).
    Default False.
optimize : bool
    (Only available in JPEG-PIL)
    On saving, compute optimal Huffman coding tables (can reduce a few
    percent of file size). Default False.
dpi : tuple of int
    (Only available in JPEG-PIL)
    The pixel density, ``(x,y)``.
icc_profile : object
    (Only available in JPEG-PIL)
    If present and true, the image is stored with the provided ICC profile.
    If this parameter is not provided, the image will be saved with no
    profile attached.
exif : dict
    (Only available in JPEG-PIL)
    If present, the image will be stored with the provided raw EXIF data.
subsampling : str
    (Only available in JPEG-PIL)
    Sets the subsampling for the encoder. See Pillow docs for details.
qtables : object
    (Only available in JPEG-PIL)
    Set the qtables for the encoder. See Pillow docs for details.
quality_mode : str
    (Only available in JPEG2000-PIL)
    Either `"rates"` or `"dB"` depending on the units you want to use to
    specify image quality.
quality : float
    (Only available in JPEG2000-PIL)
    Approximate size reduction (if quality mode is `rates`) or a signal to noise ratio
    in decibels (if quality mode is `dB`).
loop : int
    (Only available in GIF-PIL)
    The number of iterations. Default 0 (meaning loop indefinitely).
duration : {float, list}
    (Only available in GIF-PIL)
    The duration (in milliseconds) of each frame. Either specify one value
    that is used for all frames, or one value for each frame.
fps : float
    (Only available in GIF-PIL)
    The number of frames per second. If duration is not given, the
    duration for each frame is set to 1/fps. Default 10.
palettesize : int
    (Only available in GIF-PIL)
    The number of colors to quantize the image to. Is rounded to
    the nearest power of two. Default 256.
subrectangles : bool
    (Only available in GIF-PIL)
    If True, will try and optimize the GIF by storing only the
    rectangular parts of each frame that change with respect to the
    previous. Default False.

Notes
-----
To enable JPEG 2000 support, you need to build and install the OpenJPEG library,
version 2.0.0 or higher, before building the Python Imaging Library. Windows
users can install the OpenJPEG binaries available on the OpenJPEG website, but
must add them to their PATH in order to use PIL (if you fail to do this, you
will get errors about not being able to load the ``_imaging`` DLL).

GIF images read with this plugin are always RGBA. The alpha channel is ignored
when saving RGB images.
    N   )Formatimage_as_uint)URI_FILE	URI_BYTESa  
    Parameters for reading
    ----------------------

    pilmode : str
        From the Pillow documentation:

        * 'L' (8-bit pixels, grayscale)
        * 'P' (8-bit pixels, mapped to any other mode using a color palette)
        * 'RGB' (3x8-bit pixels, true color)
        * 'RGBA' (4x8-bit pixels, true color with transparency mask)
        * 'CMYK' (4x8-bit pixels, color separation)
        * 'YCbCr' (3x8-bit pixels, color video format)
        * 'I' (32-bit signed integer pixels)
        * 'F' (32-bit floating point pixels)

        PIL also provides limited support for a few special modes, including
        'LA' ('L' with alpha), 'RGBX' (true color with padding) and 'RGBa'
        (true color with premultiplied alpha).

        When translating a color image to grayscale (mode 'L', 'I' or 'F'),
        the library uses the ITU-R 601-2 luma transform::

            L = R * 299/1000 + G * 587/1000 + B * 114/1000
    as_gray : bool
        If True, the image is converted using mode 'F'. When `mode` is
        not None and `as_gray` is True, the image is first converted
        according to `mode`, and the result is then "flattened" using
        mode 'F'.
c                        e Zd ZdZdZdZdZdZdddef fdZ	e
d	             Zd
 Zd Zd Z G d dej                  Z G d dej                  Z xZS )PillowFormatz/
    Base format class for Pillow formats.
    FNi )	plugin_idr   c                     t          t          |           j        |i | t          j                    | _        || _        d S N)superr	   __init__	threadingRLock_lock
_plugin_id)selfr   argskwargs	__class__s       ]/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/imageio/plugins/pillow_legacy.pyr   zPillowFormat.__init__   s?    *lD!!*D;F;;;_&&
#    c                     | j         S )zThe PIL plugin id.)r   r   s    r   r   zPillowFormat.plugin_id   s     r   c                 `   | j         5  | j        s8d| _        dd l}t          |d          st	          d          ddlm} || _        n| j        t          d          | j        }d d d            n# 1 swxY w Y   | j        dv r|	                                 n|
                                 |S )NTr   __version__z/Imageio Pillow plugin requires Pillow, not PIL!Imagez*Imageio Pillow plugin requires Pillow lib.)PNGJPEGBMPGIFPPM)r   _pillow_importedPILhasattrImportErrorr    _ImageRuntimeErrorr   preinitinit)r   r'   r    s      r   _init_pillowzPillowFormat._init_pillow   s   Z 	  	 ( T(,%


sM22 %L   &%%%%%#$"#RSSSKE	  	  	  	  	  	  	  	  	  	  	  	  	  	  	   >AAAMMOOOOJJLLLs   AA11A58A5c                     |                                  }| j        |j        v r0|j        | j                 \  }}|r|j        r ||j                  rdS d S d S d S d S NT)r.   r   OPEN
firstbytes)r   requestr    factoryaccepts        r   	_can_readzPillowFormat._can_read  s    !!##>UZ''#j8OGV  %  &&1C*D*D  4	 ('          r   c                     |                                  }|j        | j        v s|j        t          t
          fv r| j        |j        v rdS d S d S r0   )r.   	extension
extensions	_uri_typer   r   r   SAVE)r   r3   r    s      r   
_can_writezPillowFormat._can_write  sf    !!##//73DI
 4
 4
 ~++t ,+	4
 4
r   c                   :    e Zd Zd
dZd Zd Zd Zd Zd Zd	 Z	dS )PillowFormat.ReaderNFc                    | j                                         }	 |j        | j         j                 \  }}n*# t          $ r t          d| j         j        z            w xY w|                                 | _         || j        d          | _	        t          |d          r|                    | j	        j                   | j	        j        r1| j	        j        j        r | j	        j        j        | j	        j        _        t#          | j	                   t%          |t'          | j	                            | _        |
|| j        d<   d| _        t          | j	        d          r| j	        j        | _        d S d S )NzFormat %s cannot read images.r   _decompression_bomb_check)as_grayis_graymode   n_frames)formatr.   r1   r   KeyErrorr+   name	_get_file_fp_imr(   r@   sizepalettedirtyrawmoderawmode_savedpil_try_readdict_palette_is_grayscale_kwargs_lengthrE   )r   pilmoderA   r    r4   r5   s         r   _openzPillowFormat.Reader._open  so   K,,..EW"'*T[-B"C W W W"#BT[EU#UVVVW~~''DHwtx,,DHu9:: ?//>>> x JDH$4$: J151A1I .""")>tx)H)H  DL "'.V$DLtx,, 1#x01 1s	   6 'Ac                 B    d| _         | j                                        S NF)
_we_own_fpr3   get_filer   s    r   rI   zPillowFormat.Reader._get_file4  s    #DO<((***r   c                 r    t          | j                   | j        r| j                                         d S d S r   )save_pillow_closerK   rZ   rJ   closer   s    r   _closezPillowFormat.Reader._close8  s>    dh''' !     ! !r   c                     | j         S r   )rU   r   s    r   _get_lengthzPillowFormat.Reader._get_length>  s
    <r   c                 |    	 | j                             |           d S # t          $ r t          d|z            w xY w)NzCould not seek to index %i)rK   seekEOFError
IndexErrorr   indexs     r   _seekzPillowFormat.Reader._seekA  sU    Ge$$$$$ G G G !=!EFFFGs    ;c                    || j         k    rt          d|| j         fz            | j                                        }||k    r|                     |           n&||k     r |dz  }|                     |           ||k      | j        j        r1| j        j        j        r | j        j        j        | j        j        _        | j        	                                d          t          | j        fi | j        }|| j        j        fS )NzImage index %i > %irD   r   )rU   re   rK   tellrh   rM   rN   rO   rP   getdatapil_get_framerT   info)r   rg   r
   ims       r   	_get_datazPillowFormat.Reader._get_dataG  s    $$ !6%9N!NOOOA5yy

5!!!!%iiFAJJqMMM %ii x JDH$4$: J151A1I .Hq!!tx884<88Btx}$$r   c                 F    ||dk    st                      | j        j        S )Nr   )re   rK   rm   rf   s     r   _get_meta_dataz"PillowFormat.Reader._get_meta_dataW  s#    MUaZZ ll"8= r   rY   )
__name__
__module____qualname__rW   rI   r_   ra   rh   ro   rq    r   r   Readerr>     s        	1 	1 	1 	1<	+ 	+ 	+	! 	! 	!	  	  	 	G 	G 	G	% 	% 	% 	! 	! 	! 	! 	!r   rv   c                   &    e Zd Zd Zd Zd Zd ZdS )PillowFormat.Writerc                     | j                                         }	 |j        | j         j                 | _        n*# t
          $ r t          d| j         j        z            w xY w| j        	                                | _
        i | _        d| _        d S )NzFormat %s cannot write images.F)rF   r.   r;   r   
_save_funcrG   r+   rH   r3   r[   rJ   _meta_written)r   r    s     r   rW   zPillowFormat.Writer._open]  s    K,,..EX"'*T[-B"C X X X"#CdkFV#VWWWX|,,..DHDJ!DMMMs	   8 'Ac                     d S r   ru   r   s    r   r_   zPillowFormat.Writer._closeg  s    Dr   c                    | j         rt          d| j        j        z            |j        dk    r |j        d         dk    r|d d d d df         }d| _         | j                            |           t          || j        j	        | j        
                    dd                    }d| j        v r|                                } |j        | j        fd	| j        j	        i| j         t          |           d S )
Nz&Format %s only supports single images.   rD   r   Tprefer_uint8bitsrF   )r|   r+   rF   rH   ndimshaper{   updatendarray_to_pilr   popquantizesaverJ   r]   )r   rn   metaimgs       r   _append_dataz PillowFormat.Writer._append_dataj  s    } "<t{?OO   w!|| 1 1111a[ DMJd### DK)4:>>.$+O+O C ##llnnCHTXJJdk&;JtzJJJc"""""r   c                 :    | j                             |           d S r   )r{   r   )r   r   s     r   set_meta_dataz!PillowFormat.Writer.set_meta_data|  s    Jd#####r   N)rr   rs   rt   rW   r_   r   r   ru   r   r   Writerrx   \  sP        	" 	" 	"	 	 		# 	# 	#$	$ 	$ 	$ 	$ 	$r   r   )rr   rs   rt   __doc__r&   r*   _modes_descriptionstrr   propertyr   r.   r6   r<   r   rv   r   __classcell__)r   s   @r   r	   r	      s         FFL/3 $ $ $ $ $ $ $ $ $   X  .       E! E! E! E! E! E! E! E!N!$ !$ !$ !$ !$ !$ !$ !$ !$ !$ !$ !$r   r	   c                   ^    e Zd ZdZ G d dej                  Z G d dej                  ZdS )	PNGFormat(See :mod:`imageio.plugins.pillow_legacy`c                       e Zd ZddZd ZdS )PNGFormat.ReaderNFTc                 F    t           j                            | ||          S N)rV   rA   r	   rv   rW   )r   rV   rA   ignoregammas       r   rW   zPNGFormat.Reader._open       &,,T7G,TTTr   c                 h   t           j                            | |          \  }}| j        j                            dd          sl	 t          |d                   }t          |j        t          j	        k    rdnd          }d}||z  |z  |z  |z  dz   |d d <   n# t          t          f$ r Y nw xY w||fS )Nr   Tgammai      g      ?g<Nё\?)r	   rv   ro   r3   r   getfloatdtypenpuint16rG   
ValueError)r   rg   rn   rm   r   scalegains          r   ro   zPNGFormat.Reader._get_data  s    #*44T5AAHB<&**=$?? L
L!$w-00E "28ry+@+@%%cJJED 5jU2e;dBVKBqqqEE !*-   D t8Os   B B-,B-NFT)rr   rs   rt   rW   ro   ru   r   r   rv   r     s;        	U 	U 	U 	U	 	 	 	 	r   rv   c                       e Zd ZddZd ZdS )PNGFormat.WriterNFc                    |                     dd          |d<   |#|dk     s|dk    rt          d|z            ||d<   |5t          dd          D ]}d|z  |k    r nt          d|z            ||d<   |rt                              d	           d
}|D ]}||vrt          d|z            t          j                            |            | j	        
                    |           d S )Ncompress_level	   r   z!Invalid PNG compression level: %rrD   r   z)PNG quantize must be power of two, not %rr   z0PIL PNG writer cannot produce interlaced images.)	optimizetransparencydpipnginfor   r   icc_profile
dictionaryr   zInvalid arg for PNG writer: %r)r   r   rangeloggerwarning	TypeErrorr	   r   rW   r{   r   )r   compressionr   
interlacedr   r   ok_keyskeys           r   rW   zPNGFormat.Writer._open  s>   '-zz2BA'F'FF#$&??kAoo$%H;%VWWW+6'(#!!QKK  D$w(** + %FQ   "&v SQRRR
G  L Lg%%#$Ds$JKKK & %%d+++Jf%%%%%r   c                     t          |j                  dk    r.|j        dk    s|j        d         dk    rt	          |d          }nt	          |d          }t
          j                            | ||           d S )Nr   r   r   rD      bitdepth   )r   r   r   r   r   r	   r   r   r   rn   r   s      r   r   zPNGFormat.Writer._append_data  sv    28}}((bgllbhrla>O>O"2333"2222,,T2t<<<<<r   )NNFrr   rs   rt   rW   r   ru   r   r   r   r     s8        $	& $	& $	& $	&L	= 	= 	= 	= 	=r   r   Nrr   rs   rt   r   r	   rv   r   ru   r   r   r   r     st        22    $   .,= ,= ,= ,= ,=$ ,= ,= ,= ,= ,=r   r   c                   ^    e Zd ZdZ G d dej                  Z G d dej                  ZdS )
JPEGFormatr   c                   (    e Zd ZddZd Zd Zd ZdS )	JPEGFormat.ReaderNFTc                 F    t           j                            | ||          S r   r   )r   rV   rA   
exifrotates       r   rW   zJPEGFormat.Reader._open  r   r   c                     | j         j                            d          s"d| j         j                            dd          v r.d| _        t          | j                                         d          S d| _        | j                                         S N)zhttp://zhttps://z.zip/\/TrbFr3   filename
startswithreplacerZ   openget_local_filenamer[   r   s    r   rI   zJPEGFormat.Reader._get_file      |$//'  /DL199$DDDD"&DL;;==tDDD"'|,,...r   c                 >   t           j                            | |          \  }}d|v r]ddlm} i |d<   | j                                                                        D ]&\  }}|                    ||          }||d         |<   '| 	                    ||          }||fS Nexifr   )TAGS	EXIF_MAIN
r	   rv   ro   PIL.ExifTagsr   rK   _getexifitemsr   _rotater   rg   rn   rm   r   tagvaluedecodeds           r   ro   zJPEGFormat.Reader._get_data      #*44T5AAHB ~~------$&[!"&("3"3"5"5";";"="= 7 7JC"hhsC00G16D%g..b$''Bt8Or   c                 T   | j         j                            dd          r	 |d         d         }|dv r	 |dv rt          j        |d          }|dv rt          j        |d	          }|d
v rt          j        |          }|dv rt          j        |          }n# t          $ r Y nw xY w|S zUse Orientation information from EXIF meta data to
            orient the image correctly. Similar code as in FreeImage plugin.
            r   Tr   Orientation)rD   r   r      r   )      r   )   r   )r   r   r   r   r3   r   r   r   rot90fliplrrG   r   rn   r   oris       r   r   zJPEGFormat.Reader._rotate       |"&&|T:: ++{+M:C
 f}}f}}Xb!__f}}Xb!__f}}Xb\\l**Yr]]     D I   B 
B%$B%r   rr   rs   rt   rW   rI   ro   r   ru   r   r   rv   r     Y        	U 	U 	U 	U		/ 		/ 		/	 	 		 	 	 	 	r   rv   c                       e Zd ZddZd ZdS )JPEGFormat.WriterK   Fc                    t          |          }|dk     s|dk    rt          d          ||d<   t          |          |d<   t          |          |d<   t          j                            |            | j                            |           d S )Nr   d   z)JPEG quality should be between 0 and 100.qualityprogressiver   )intr   boolr	   r   rW   r{   r   )r   r   r   r   r   s        r   rW   zJPEGFormat.Writer._open  s    'llG{{gmm !LMMM 'F9$($5$5F=!!%k!2!2F:%%d+++Jf%%%%%r   c                     |j         dk    r |j        d         dk    rt          d          t          |d          }t          j                            | ||           d S )Nr   r   r   z$JPEG does not support alpha channel.r   r   r   r   IOErrorr   r	   r   r   r   s      r   r   zJPEGFormat.Writer._append_data  s^    w!|| 1 1DEEErA...B,,T2t<<<Fr   N)r   FFr   ru   r   r   r   r     s7        	& 	& 	& 	&	 	 	 	 	r   r   Nr   ru   r   r   r   r     su        223 3 3 3 3$ 3 3 3n    $     r   r   c                   ^    e Zd ZdZ G d dej                  Z G d dej                  ZdS )JPEG2000Formatr   c                   (    e Zd ZddZd Zd Zd ZdS )JPEG2000Format.ReaderNFc                 F    t           j                            | ||          S r   r   )r   rV   rA   s      r   rW   zJPEG2000Format.Reader._open  r   r   c                     | j         j                            d          s"d| j         j                            dd          v r.d| _        t          | j                                         d          S d| _        | j                                         S r   r   r   s    r   rI   zJPEG2000Format.Reader._get_file   r   r   c                 >   t           j                            | |          \  }}d|v r]ddlm} i |d<   | j                                                                        D ]&\  }}|                    ||          }||d         |<   '| 	                    ||          }||fS r   r   r   s           r   ro   zJPEG2000Format.Reader._get_data+  r   r   c                 T   | j         j                            dd          r	 |d         d         }|dv r	 |dv rt          j        |d          }|dv rt          j        |d	          }|d
v rt          j        |          }|dv rt          j        |          }n# t          $ r Y nw xY w|S r   r   r   s       r   r   zJPEG2000Format.Reader._rotate:  r   r   rY   r   ru   r   r   rv   r    r   r   rv   c                       e Zd ZddZd ZdS )JPEG2000Format.Writerratesr   c                    |dvrt          d          t          |          }|dk    r.|dk     s|dk    r"t          d                    |                    |dk    r.|dk     s|d	k    r"t          d
                    |                    ||d<   |g|d<   t          j                            |            | j                            |           d S )N>   dBr  z-Quality mode should be either 'rates' or 'dB'r  rD   i  z1The quality value {} seems to be an invalid rate!r     r   z1The quality value {} seems to be an invalid PSNR!quality_modequality_layers)r   r   rF   r	   r   rW   r{   r   )r   r  r   r   s       r   rW   zJPEG2000Format.Writer._openT  s    ?22 !PQQQGnnGw&&GaKK7T>> GNNwWW   %%7R<<7S== GNNwWW   &2F>"(/yF#$%%d+++Jf%%%%%r   c                     |j         dk    r |j        d         dk    rt          d          t          |d          }t          j                            | ||           d S )Nr   r   r   zGThe current implementation of JPEG 2000 does not support alpha channel.r   r   r  r   s      r   r   z"JPEG2000Format.Writer._append_dataj  sf    w!|| 1 1]   rA...B,,T2t<<<Fr   N)r  r   r   ru   r   r   r   r  S  s7        	& 	& 	& 	&,	 	 	 	 	r   r   Nr   ru   r   r   r  r    su        223 3 3 3 3$ 3 3 3n    $     r   r  c                     t          | d          r5t          t          | dd           d          r|                                  d S d S d S )Nr^   fp)r(   getattrr^   )rn   s    r   r]   r]   t  sW    r7 72tT**G44 	HHJJJJJ 	 	r   c                     	 |                                  d          d S # t          $ r:}d}|dz  }t          |          }d| j        d|d|}t	          |          d }~ww xY w)Nr   z8http://pillow.readthedocs.io/en/latest/installation.htmlz#external-librarieszCould not load "z" 
Reason: "z"
Please see documentation at: )rk   r  r   r   r   )rn   esitepillow_error_messageerror_messages        r   rQ   rQ     s    (


Q 
( 
( 
(I%%"1vv
 {{{000$$8 	 '''
(s    
A"5AA"c                 ^   | j         dk    rdS | j                            dd           rdS t          j        |                                                               d          }|                                 \  }}|||dz            }t          j        t          j	        |          d          S )NPFr   )r   r   rD   r   )
rC   rm   r   r   asarray
getpalettereshape
getextremaallclosediff)	pil_imagerM   startstopvalid_palettes        r   rS   rS     s    ~u			ND	1	1 u j--//0088AAG&&((KE4ED1H,-M ;rw}--q111r   c                    |t          |           }| }|"|| j        k    r|                     |          }n|rn| j        dk    r|r|                     d          }nx| j        dk    r| j                            dd          |                     d          }n:| j        j        dv rt          j        | j                                        d         t          j	                  }t          | j        d          r| j        j        | j        _        | j        j        r| j        j        n| j        j        }t          |          }d	|f|_        |j        d         d
k    s|j        d         dk    rT|d	         dk    rHt          j        |dddd
f         dt          j        |j        d         |j                  z  f          }|                    d          r-|j        d         d
k    r|ddg df         n|ddg df         }t          j        | t          j	                  }	 ||         }n# t(          $ r |                     d          }Y nw xY w	 |                     d          }nkd| j        v r|                     d          }nL| j        dk    r|                     d          }n+| j        dk    r | j        dk    r|                     d          }|r|                    d          }n:t-          |t          j                  s |j        dk    r|                    d          }| j                            d          r| j        }	| j                            d          rdnd}d| j        v r|                    dd          }t          j        |                                |                                          }|	ddd	         |_        n0| j        d k    r| j        d!k    r|d"}t          j        ||#          }|S )$z
    is_gray: Whether the image *is* gray (by inspecting its palette).
    as_gray: Whether the resulting image must be converted to gaey.
    mode: The mode to convert to.
    Nr  Lr   RGBA)RGBr,  rD   rP   r   r   r   Xr   r   BGR)r   rD   r   )r   rD   r   r   Tr-  ACMYKr$   F1I;16Bz>u2z<u2Sur
   r!   Ir   )r   )rS   rC   convertrm   r   rM   r   
frombufferrk   uint8r(   rP   rO   lenr   column_stackonesr   r   array	ExceptionrF   
isinstancendarrayrL   endswithr   tobytescopy)
rn   rB   rA   rC   r   framep	nchannelsframe_palettedr   s
             r   rl   rl     s    '++E 27??JJt$$E	 7#	CG 

3	C 7;;~t,,8JJv&&EEZ_// bj002215rx@@Arz?33 >%'Z%=
")+);P2:%%DD		I)mAGwqzQ171:??tBx3OQqqq"1"uXsRWQWQZ5Q5Q/Q$RSSu%% O'(wqzQAaaalOOAaaao<NXb"(33N+.) + + + 

6**	+*

6** 


6""	F		

5!!	e		5 0 0 

6""  	#c""rz** #uzS/@/@ c"" 
w&!! -))#..9E"'>>MM#s++Eemmoou55::<<DDbDk 9"'S..U]Ee,,,Ls   (H1 1IITc                    ddl m} | j        dk    r(t          | d          } ddd| j        d	                  }n|d
v rd}d}| j        j        dk    rt          |           } n}|rT|                                 dk     r<|                                 dk    r$| 	                    t          j                  } dx}}n't          | d          } nt          | d          } d}d}|dk    rt          t          |dd                              d          d                   dk     r|                                 }| j        d	k    r8|                    || j        j                  }|                    |d|           n1| j        d         | j        d         f}|                    |||          }|S |                    | |          S )Nr   r   r   r   r   r-  r,  r   r   )pngr!   r4  r8  f   r+  r   r   0.r   rawrD   )r'   r    r   r   r   r   kindmaxminastyper   r;  r   r  splitrD  newT	frombytes	fromarray)	arr
format_strr   r    rC   	mode_basearray_bufferrn   image_shapes	            r   r   r     s   
x1}}C!,,,V$$SYq\2	~	%	%	9>S  $$CC 	2cggii#oo#''))q..**RX&&C""D99  b111CC C!,,,	v~~#ge]C@@FFsKKANOORSSS {{}}8q==9cek22BLLud33339Q<16K{LAAB	sD)))r   rD   )	GIFFormat
TIFFFormat)NNNNr0   )r   loggingr   numpyr   corer   r   core.requestr   r   	getLoggerrr   r   GENERIC_DOCSr	   r   r   r  r]   rQ   rS   rl   r   pillowmultir_  r`  ru   r   r   <module>rh     s  b bH          ( ( ( ( ( ( ( ( . . . . . . . . 
	8	$	$@f$ f$ f$ f$ f$6 f$ f$ f$RF= F= F= F= F= F= F= F=RM M M M M M M M`X X X X X\ X X Xv  ( ( ("2 2 2 e e e eP'* '* '* '*V / . . . . . . . . .r   