o
    e                     @  s  d Z ddlmZ ddlmZmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZmZmZmZmZmZmZ dd
lmZ ddlmZ ddlmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z. edZ/G dd de0Z1G dd de0Z2G dd de2Z3G dd de0Z4d8ddZ5d9d!d"Z6d:d+d,Z7G d-d. d.eZ8G d/d0 d0eZ9G d1d2 d2e9Z:G d3d4 d4e:Z;G d5d6 d6e9Z<d7S );zExtract images embedded in PDF.    )annotations)ABCabstractmethod)Decimal)BytesIO)zip_longest)Path)copyfileobj)AnyBinaryIOCallable
NamedTupleSequenceTypeVarcast)Image)ImageCmsProfile)
Array
DictionaryNameObjectPdfPdfErrorStreamStreamDecodeLevelStringjbig2)DependencyError)Buffer)__version__)_transcodingTc                   @     e Zd ZdZdS )UnsupportedImageTypeErrorz<This image is formatted in a way pikepdf does not supported.N__name__
__module____qualname____doc__ r)   r)   DD:\Projects\ConvertPro\env\Lib\site-packages\pikepdf/models/image.pyr#   '       r#   c                   @  r"   )NotExtractableErrorz5Indicates that an image cannot be directly extracted.Nr$   r)   r)   r)   r*   r,   +   r+   r,   c                   @  r"   )"HifiPrintImageNotTranscodableErrorzJImage contains high fidelity printing information and cannot be extracted.Nr$   r)   r)   r)   r*   r-   /   r+   r-   c                   @  r"   )InvalidPdfImageErrorz?This image is not valid according to the PDF 1.7 specification.Nr$   r)   r)   r)   r*   r.   3   r+   r.   valueObject | str | listc                   s*    fdd  }t |ts|g}|S )zOSimplify pikepdf objects to array of str. Keep Streams and dictionaries intact.c                   sf   t | ttfr fdd| D S t | ttttfr| S t | ttfr&t| S t | t	r/t| S t
)Nc                   s   g | ]} |qS r)   r)   ).0subitem)_convertr)   r*   
<listcomp><       z0_array_str.<locals>._convert.<locals>.<listcomp>)
isinstancelistr   r   r   bytesintr   strr   NotImplementedError)itemr3   r/   r)   r*   r3   :   s   
z_array_str.<locals>._convert)r6   r7   )r/   resultr)   r=   r*   
_array_str7   s
   
r?   !list[Object] | Dictionary | Arrayreturnlist[Object]c                 C  s   t | tr| S t|   S )zEnsure value is a list of pikepdf.Object, if it was not already.

    To support DecodeParms which can be present as either an array of dicts or a single
    dict. It's easier to convert to an array of one dict.
    )r6   r7   Zwrap_in_arrayas_list)r/   r)   r)   r*   _ensure_listK   s   
rD   objDictionary | Streamnamer:   type_Callable[[Any], T]defaultT | Nonec                 C  sD   t | ||}z||W S  ty   |du rY dS Y nw td| )zRRetrieve metadata from a dictionary or stream, and ensure it is the expected type.NzMetadata access for )getattr	TypeErrorr;   )rE   rG   rH   rJ   valr)   r)   r*   _metadata_from_objV   s   
rO   c                   @  s"   e Zd ZU dZded< ded< dS )PaletteDataa5  Returns the color space and binary representation of the palette.

    ``base_colorspace`` is typically ``"RGB"`` or ``"L"`` (for grayscale).

    ``palette`` is typically 256 or 256*3=768 bytes, for grayscale and RGB color
    respectively, with each unit/triplet being the grayscale/RGB triplet values.
    r:   Zbase_colorspacer8   paletteN)r%   r&   r'   r(   __annotations__r)   r)   r)   r*   rP   c   s   
 rP   c                   @  sP  e Zd ZdZh dZeh dB ZddhZedFddZe	dGddZ
e	dGddZe	dHddZe	dIddZe	dd Ze	dd Ze	dd Ze	dJd!d"Ze	dGd#d$Ze	edKd&d'Ze	dHd(d)Zd*d+ Ze	dHd,d-Ze	dHd.d/Ze	dLd1d2Zd3d4 Ze	dMd5d6Ze	d7d8 Ze	dNd:d;ZedOd=d>ZedPdCdDZdES )QPdfImageBasezAbstract base class for images.>   z/CalGrayz/CalRGB
/DeviceRGB/DeviceGray>   	/ICCBasedz/CalCMYK/DeviceCMYK/Separation/DeviceNrG   r:   rH   rI   rJ   r!   rA   c                 C     dS )z!Get metadata for this image type.Nr)   selfrG   rH   rJ   r)   r)   r*   	_metadataw       zPdfImageBase._metadatar9   c                 C     |  dtdS )z"Width of the image data in pixels.Widthr   r]   r9   r\   r)   r)   r*   width{      zPdfImageBase.widthc                 C  r_   )z#Height of the image data in pixels.Heightr   ra   rb   r)   r)   r*   height   rd   zPdfImageBase.heightboolc                 C  r_   )z)Return ``True`` if this is an image mask.Z	ImageMaskF)r]   rg   rb   r)   r)   r*   
image_mask   rd   zPdfImageBase.image_mask
int | Nonec                 C  r_   )z.Bits per component for this image (low-level).BitsPerComponentr   ra   rb   r)   r)   r*   _bpc   rd   zPdfImageBase._bpcc                 C     |  dtg S )zColorspace (low-level).
ColorSpacer]   r?   rb   r)   r)   r*   _colorspaces   rd   zPdfImageBase._colorspacesc                 C  rl   )zBList of names of the filters that we applied to encode this image.Filterrn   rb   r)   r)   r*   filters   rd   zPdfImageBase.filtersc                 C  rl   )z/List of the /DecodeParms, arguments to filters.ZDecodeParms)r]   rD   rb   r)   r)   r*   decode_parms   rd   zPdfImageBase.decode_parms
str | Nonec                 C  s   | j rdS | jrE| jd | jv r| jd S | jd dkr<| jd }t|tr-|| jv r-|S t|tr<|d dv r<|d S | jd dkrEdS tdt| j )z:PDF name of the colorspace that best describes this image.Nr   /Indexed   )rV   rY   rY   z not sure how to get colorspace: )rh   ro   MAIN_COLORSPACESr6   r:   r7   r;   repr)r\   Zsubspacer)   r)   r*   
colorspace   s    

zPdfImageBase.colorspacec                 C  s(   | j du s
| j dkr| jrdS dS | j S )z!Bits per component of this image.Nr   ru      )rk   rh   rb   r)   r)   r*   bits_per_component   s   zPdfImageBase.bits_per_componentImageCmsProfile | Nonec                 C  rZ   )z4Return ICC profile for this image if one is defined.Nr)   rb   r)   r)   r*   icc   r^   zPdfImageBase.iccc                 C  s
   d| j v S )z/Check if the image has a defined color palette.rt   )ro   rb   r)   r)   r*   indexed      
zPdfImageBase.indexedc              
   C  s\   z | j }|d dkr|d d |krW dS |d |krW dS W dS  tttfy-   Y dS w )Nr   rt   ru   TF)ro   
IndexErrorAttributeErrorKeyError)r\   rG   csr)   r)   r*   _colorspace_has_name   s   z!PdfImageBase._colorspace_has_namec                 C  
   |  dS )<Check if image has a /DeviceN (complex printing) colorspace.rY   r   rb   r)   r)   r*   is_device_n   r~   zPdfImageBase.is_device_nc                 C  r   )r   rX   r   rb   r)   r)   r*   is_separation   r~   zPdfImageBase.is_separationtuple[int, int]c                 C  s   | j | jfS )z!Size of image as (width, height).)rc   rf   rb   r)   r)   r*   size      zPdfImageBase.sizec                 C  sX   | j r| jd d }n| jd }t|d }|dkrdS ddd}| jjj}||dS )Nru   z/NLRGBCMYK)zRGB r    )r}   ro   r9   r|   Zprofilexcolor_spaceget)r\   icc_profileZicc_profile_nchannelsZmode_from_xcolor_spacer   r)   r)   r*   _approx_mode_from_icc   s   


z"PdfImageBase._approx_mode_from_iccc              
   C  s   d}| j rd}nU| jrd}nO| jrd}nI| jdkr!| jdkr!d}n<| jdkr.| jdkr.d}n/| jd	kr6d
}n'| jdkr>d}n| jdkr]z|  }W n ttfy\ } ztd|d}~ww |dkrftdd|S )z``PIL.Image.mode`` equivalent for this image, where possible.

        If an ICC profile is attached to the image, we still attempt to resolve a Pillow
        mode.
        r   DeviceN
SeparationPrU   ru   1r   rT   r   rW   r   rV   z-Not sure how to handle PDF image of this typeN)	r   r   r}   rx   rz   r   
ValueErrorrM   r;   )r\   mer)   r)   r*   mode   sB   


zPdfImageBase.modec                 C  s   t t| j| ji dS )a  Return normalized the Filter and DecodeParms data.

        PDF has a lot of possible data structures concerning /Filter and
        /DecodeParms. /Filter can be absent or a name or an array, /DecodeParms
        can be absent or a dictionary (if /Filter is a name) or an array (if
        /Filter is an array). When both are arrays the lengths match.

        Normalize this into:
        [(/FilterName, {/DecodeParmName: Value, ...}), ...]

        The order of /Filter matters as indicates the encoding/decoding sequence.
        )	fillvalue)r7   r   rq   rr   rb   r)   r)   r*   filter_decodeparms  s   zPdfImageBase.filter_decodeparmsPaletteData | Nonec              
   C  s   | j sdS z	| j\}}}}W n ty } ztd|d}~ww | js)| js)| jr0t|d }nt|}t|}|| jvrI|| j	vrIt
d| |dkrPd}n$|dkrWd}n|d	kr^d
}n|dkred}n|dkrld}n|dkrt|  }t||S )z8Retrieve the color palette for this image if applicable.Nz&Not sure how to interpret this paletter   z(not sure how to interpret this palette: rT   r   rU   r   rW   r   rY   r   rX   r   rV   )r}   ro   r   r|   r   r   r:   r8   rv   PRINT_COLORSPACESr;   r   rP   )r\   Z_idxbaseZ_hivallookupr   r)   r)   r*   rQ   #  s6   

zPdfImageBase.paletteImage.Imagec                 C  rZ   )z6Convert this PDF image to a Python PIL (Pillow) image.Nr)   rb   r)   r)   r*   as_pil_imageA  r^   zPdfImageBase.as_pil_imagerE   r   rq   Sequence[str]c                   s   h d  fddt |D }|r4t|dkr#td| j d| d|d|d	  }||d	 d }n|}g }|s@|  |fS | j}ztd
d |D | _| tj	}W || _||fS || _w )zRemove simple lossless compression where it appears.

        Args:
            obj: the compressed object
            filters: all files on the data
        >   /CCITTFaxDecode
/DCTDecode
/JPXDecodez/JBIG2Decodec                   s   g | ]
\}}| v r|qS r)   r)   )r1   nr<   ZCOMPLEX_FILTERSr)   r*   r4   T  s    z7PdfImageBase._remove_simple_filters.<locals>.<listcomp>ru   zObject z has compound complex filters: z. We cannot decompress this.Nr   c                 S  s   g | ]}t |qS r)   )r   )r1   sr)   r)   r*   r4   f  r5   )
	enumeratelenr;   ZobjgenZread_raw_bytesrp   r   
read_bytesr   specialized)rE   rq   idxZsimple_filtersZcomplex_filtersZoriginal_filtersdatar)   r   r*   _remove_simple_filtersE  s(   z#PdfImageBase._remove_simple_filtersN)rG   r:   rH   rI   rJ   r!   rA   r!   rA   r9   rA   rg   )rA   ri   )rA   rs   rA   r{   )rA   r   )rA   r:   )rA   r   rA   r   )rE   r   rq   r   ) r%   r&   r'   r(   ZSIMPLE_COLORSPACESrv   r   r   r]   propertyrc   rf   rh   rk   ro   rq   rr   rx   rz   r|   r}   r   r   r   r   r   r   r   rQ   r   staticmethodr   r)   r)   r)   r*   rS   p   s`    


"
rS   c                      s  e Zd ZU dZded< ded<  fddZd?dd	Zd
d Zedd Z	dd Z
edd Zed@ddZdAddZdBddZdBddZdBdd ZdAd!d"Zd#d$d%dCd(d)ZejfdDd-d.ZejfdEd0d1ZdBd2d3ZdFdGd7d8Zd9d: Zd;d< ZdHd=d>Z  ZS )IPdfImagea  Support class to provide a consistent API for manipulating PDF images.

    The data structure for images inside PDFs is irregular and complex,
    making it difficult to use without introducing errors for less
    typical cases. This class addresses these difficulties by providing a
    regular, Pythonic API similar in spirit (and convertible to) the Python
    Pillow imaging library.
    r   rE   r{   _iccc                   s:   t  | }|| d|jv rt  t}|| |S )zGConstruct a PdfImage... or a PdfJpxImage if that is what we really are.r   )super__new____init__rq   PdfJpxImage)clsrE   instance	__class__r)   r*   r   {  s   


zPdfImage.__new__c                 C  s2   t |tr|jddkrtd|| _d| _dS )zConstruct a PDF image from a Image XObject inside a PDF.

        ``pim = PdfImage(page.Resources.XObject['/ImageNN'])``

        Args:
            obj: an Image XObject
        z/Subtype/Imagez'can't construct PdfImage from non-imageN)r6   r   Zstream_dictr   rM   rE   r   r\   rE   r)   r)   r*   r     s   
zPdfImage.__init__c                 C  s   t |tstS | j|jkS N)r6   rS   NotImplementedrE   r\   otherr)   r)   r*   __eq__  s   
zPdfImage.__eq__c                C  s   |  }t||}td|_td|_|jdkrtd|_n
|jdv r(td|_|jdkr/dnd	|_|j|_	|j
|_||jj|< | |S )
a@  Insert a PIL image into a PDF (rudimentary).

        Args:
            pdf (pikepdf.Pdf): the PDF to attach the image to
            page (pikepdf.Object): the page to attach the image to
            name (str or pikepdf.Name): the name to set the image
            image (PIL.Image.Image): the image to insert
        z/XObjectr   r   rT   )r   r   rU   r   ru   ry   )tobytesr   r   TypeZSubtyper   rm   rj   rc   r`   rf   re   Z	ResourcesZXObject)r   ZpdfpagerG   imager   Zimstreamr)   r)   r*   _from_pil_image  s   






zPdfImage._from_pil_imagec                 C     t | j|||S r   rO   rE   r[   r)   r)   r*   r]        zPdfImage._metadatac                 C  sD   | j dkr| js| jd S t| jd tsJ | jd d S td)NrV   ru   z+Don't know how to find ICC stream for image)rx   r}   ro   r6   r7   r;   rb   r)   r)   r*   
_iccstream  s   

zPdfImage._iccstreamrA   c              
   C  s   | j dvrdS | js>| j}| }t|}z	t|| _W | jS  ty= } zt|dkr1td|W Y d}~| jS d}~ww | jS )zIf an ICC profile is attached, return a Pillow object that describe it.

        Most of the information may be found in ``icc.profile``.
        )rV   rt   Nzcannot open profile from stringz#ICC profile corrupt or not readable)	rx   r   r   get_stream_bufferr   r   OSErrorr:   r#   )r\   Z	iccstreamZ	iccbufferZ
iccbytesior   r)   r)   r*   r|     s*   

zPdfImage.iccstreamr   r:   c                  s   d fdd}d fdd}   j j\}}|dgkr; jdkr( j }nd	}| j||d
 || dS |dgkrR jdksK| sK| rR|| dS t	 )aS  Attempt to extract the image directly to a usable image file.

        If there is no way to extract the image without decompressing or
        transcoding then raise an exception. The type and format of image
        generated will vary.

        Args:
            stream: Writable file stream to write data to, e.g. an open file
        rA   rg   c                    s,   d}  j d d d| } jdko|| kS )Nru   r   /ColorTransformr   r   r   r   )ZDEFAULT_CT_RGBctrb   r)   r*   normal_dct_rgb  s   z0PdfImage._extract_direct.<locals>.normal_dct_rgbc                    s,   d}  j d d d| } jdko|| kS )Nr   ru   r   r   r   )ZDEFAULT_CT_CMYKr   rb   r)   r*   normal_dct_cmyk  s   z1PdfImage._extract_direct.<locals>.normal_dct_cmykr   rV   N)r|   z.tifr   r   z.jpgr   )
r   rE   rq   rx   r   r   write_generate_ccitt_headerr   r,   )r\   r   r   r   r   rq   r|   r)   rb   r*   _extract_direct  s   





zPdfImage._extract_directr   c                 C  s   d}| j dkr	dnd}| jdv rt|  | j| j|\}}n| jdkr,tt|  }nt	d| j dkrK| j
durK| j
\}}t|| j|||}|S t|| j|}|S )	zAExtract an image when there are 1/2/4/8 bits packed in byte data.r   r   ru   )      ry   z*BitsPerComponent must be 1, 2, 4, 8, or 16r   N)r   rz   r    Zunpack_subbyte_pixelsr   r   r   
memoryviewr   r.   rQ   Zimage_from_buffer_and_paletteZimage_from_byte_buffer)r\   Zstridescalebuffer	base_moderQ   imr)   r)   r*   _extract_transcoded_1248bits  s*   



	z%PdfImage._extract_transcoded_1248bitsc              
   C  s   | j dv r	tdz|  }W n  ttfy/ } zdt|v r*t  s*t	dd  d }~ww t
d| j|}| jd urI| j\}}t|||}|S )N)r   r   z$1-bit RGB and CMYK are not supportedz(read_bytes called on unfilterable streamzRjbig2dec - not installed or installed version is too old (older than version 0.15)r   )r   r#   r   RuntimeErrorr   r:   r   Zget_decoder	availabler   r   	frombytesr   rQ   r    Zfix_1bit_palette_image)r\   r   r   r   r   rQ   r)   r)   r*   _extract_transcoded_1bit  s*   



z!PdfImage._extract_transcoded_1bitc              	   C  s   | j dv rt | j dkr!| jdkr!td| j|  dddd}n?| j dkr:| jdkr:td| j|  dddd}n&| jdkrD|  }n| j dv rS| jdkrS| 	 }nt
t| d	 t| j | jd
krr| jd urr| j |jd< |S )N>   r   r   r   ry   rawr   ru   r   )r   r   z, rV   r   )r   r-   rz   r   Z
frombufferr   r   r   r   r   r#   rw   rE   rx   r|   r   info)r\   r   r)   r)   r*   _extract_transcoded3  s$   



zPdfImage._extract_transcodedc             
   C  s   z| j |dW S  ty   Y nw d}zWz4|  }|jdkr2|j|ddd W W |r0|  dS dS |rG|j|dd	 W W |rE|  d
S d
S W n tyb } zdt|v r]tt	| | d}~ww W |rj|  n|rr|  w w tt	| )a  Extract the image to a stream.

        If possible, the compressed data is extracted and inserted into
        a compressed image file format without transcoding the compressed
        content. If this is not possible, the data will be decompressed
        and extracted to an appropriate format.

        Args:
            stream: Writable stream to write data to

        Returns:
            The file format extension.
        r   Nr   ZtiffZtiff_adobe_deflate)formatcompressionz.tiffZpng)r   z.pngzcalled on unfilterable stream)
r   r,   r   r   savecloser   r:   r#   rw   )r\   r   r   r   r)   r)   r*   _extract_to_streamN  sF   
	
zPdfImage._extract_to_streamNr   r   
fileprefixBinaryIO | Noner   c                C  s   t |t |krtd|r| j|dS t }| j|d}|d ttt|| }|d}t|| W d   t|S 1 sDw   Y  t|S )a  Extract the image directly to a usable image file.

        If possible, the compressed data is extracted and inserted into
        a compressed image file format without transcoding the compressed
        content. If this is not possible, the data will be decompressed
        and extracted to an appropriate format.

        Because it is not known until attempted what image format will be
        extracted, users should not assume what format they are getting back.
        When saving the image to a file, use a temporary filename, and then
        rename the file to its final name based on the returned file extension.

        Images might be saved as any of .png, .jpg, or .tiff.

        Examples:
            >>> im.extract_to(stream=bytes_io)
            '.png'

            >>> im.extract_to(fileprefix='/tmp/image00')
            '/tmp/image00.jpg'

        Args:
            stream: Writable stream to write data to.
            fileprefix (str or Path): The path to write the extracted image to,
                without the file extension.

        Returns:
            If *fileprefix* was provided, then the fileprefix with the
            appropriate extension. If no *fileprefix*, then an extension
            indicating the file type.
        z%Cannot set both stream and fileprefixr   r   wbN)	rg   r   r   r   seekr   r:   openr	   )r\   r   r   bio	extensionfilepathtargetr)   r)   r*   
extract_tot  s   "

zPdfImage.extract_todecode_levelr   r8   c                 C     | j j|dS )z7Decompress this image and return it as unencoded bytes.r   )rE   r   r\   r   r)   r)   r*   r        zPdfImage.read_bytesr   c                 C  r   )z+Access this image with the buffer protocol.r   )rE   r   r   r)   r)   r*   r     r  zPdfImage.get_stream_bufferc                 C  sX   zt  }| j|d |d t|W S  ty   Y nw |  }|s*tt| |S )zuExtract the image as a Pillow Image, using decompression as necessary.

        Caller must close the image.
        r   r   )	r   r   r   r   r   r,   r   r#   rw   )r\   r   r   r)   r)   r*   r     s   
zPdfImage.as_pil_imager   r|   bytes | Nonec                 C  s   | j std| j d ddrtd| j d dd}|dk r$d}n	|dkr+d}nd	}| j d d
d}d}t|}|du rBd}t| j||||S )z8Construct a CCITT G3 or G4 header from the PDF metadata.z$/CCITTFaxDecode without /DecodeParmsr   z/EncodedByteAlignFz+/CCITTFaxDecode with /EncodedByteAlign truez/Kr      r   z	/BlackIs1N    )rr   r   r   r#   r   r    Zgenerate_ccitt_headerr   )r\   r   r|   kZccitt_groupZ_black_is_oneZ
photometryZimg_sizer)   r)   r*   r     s(   zPdfImage._generate_ccitt_headerc                 C  s   |     dS )z$Show the image however PIL wants to.N)r   showrb   r)   r)   r*   r    s   zPdfImage.showc              
   C  ,   d| j  d| j d| j dtt|  d	S )Nz<pikepdf.PdfImage image mode= size=x at >r   rc   rf   hexidrb   r)   r)   r*   __repr__     

zPdfImage.__repr__c                 C  sF   t  }|  }||d | W  d   S 1 sw   Y  dS )z!Display hook for IPython/Jupyter.ZPNGN)r   r   r   getvalue)r\   br   r)   r)   r*   
_repr_png_  s
   
$zPdfImage._repr_png_)rE   r   r   )r   r   rA   r:   r   )r   r   r   r:   rA   r:   )r   r   rA   r8   )r   r   rA   r   r   )r   r8   r|   r  rA   r8   rA   r8   )r%   r&   r'   r(   rR   r   r   r   classmethodr   r]   r   r   r|   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  __classcell__r)   r)   r   r*   r   n  s<   
 	
	



.


'0
(r   c                      sf   e Zd ZdZ fddZdd Zddd	Ze fd
dZedddZ	edddZ
dd Z  ZS )r   zSupport class for JPEG 2000 images. Implements the same API as :class:`PdfImage`.

    If you call PdfImage(object_that_is_actually_jpeg2000_image), pikepdf will return
    this class instead, due to the check in PdfImage.__new__.
    c                   s   t  | |  | _dS )zInitialize a JPEG 2000 image.N)r   r   r   _jpxpilr   r   r)   r*   r     s   zPdfJpxImage.__init__c                 C  s0   t |tstS | j|jkot |to| j|jkS r   )r6   rS   r   rE   r   r  r   r)   r)   r*   r     s   

zPdfJpxImage.__eq__r   r   c                C  s6   |  | j| j\}}|dgkrt| j|| dS )Nr   z.jp2)r   rE   rq   r#   r   )r\   r   r   rq   r)   r)   r*   r     s
   


zPdfJpxImage._extract_directc                   s<   t  j}|r|S | jjdkrdgS | jjdkrdgS td)zReturn the effective colorspace of a JPEG 2000 image.

        If the ColorSpace dictionary is present, the colorspace embedded in the
        JPEG 2000 data will be ignored, as required by the specification.
        r   rU   r   rT   zComplex JP2 colorspace)r   ro   r  r   r;   )r\   Zsuper_colorspacesr   r)   r*   ro     s   	zPdfJpxImage._colorspacesrA   r9   c                 C  rZ   )z=Return 8, since bpc is not meaningful for JPEG 2000 encoding.ry   r)   rb   r)   r)   r*   rk   *  s   zPdfJpxImage._bpcrg   c                 C  rZ   )z4Return False, since JPEG 2000 should not be indexed.Fr)   rb   r)   r)   r*   r}   3  s   zPdfJpxImage.indexedc              
   C  r  )Nz)<pikepdf.PdfJpxImage JPEG2000 image mode=r  r	  r
  r  r  rb   r)   r)   r*   r  ;  r  zPdfJpxImage.__repr__)r   r   r   r   )r%   r&   r'   r(   r   r   r   r   ro   rk   r}   r  r  r)   r)   r   r*   r     s    
	r   c                   @  s  e Zd ZU dZi dddddddd	d
dddddddddddddddddddddd d!d"d#Zd$d% e D Zd&ed'< d(ed)< dOd-d.Zd/d0 Z	e
d1d2 Zd3d4 ZdPd7d8Zed9d: Zd;d< Zd=d> ZdQd@dAZdBdCdDdRdIdJZdKdL ZdMdN ZdBS )SPdfInlineImagezRSupport class for PDF inline images. Implements the same API as :class:`PdfImage`.s   /Ws   /Widths   /Hs   /Heights   /BPCs   /BitsPerComponents   /IMs
   /ImageMasks   /CSs   /ColorSpaces   /Fs   /Filters   /DPs   /DecodeParmss   /Gs   /DeviceGrays   /RGBs
   /DeviceRGBs   /CMYKs   /DeviceCMYKs   /Is   /Indexeds   /AHxs   /ASCIIHexDecodes   /A85s   /ASCII85Decodes   /LZWs
   /LZWDecodes   /RLs   /RunLengthDecodes   /CCFs   /CCITTFaxDecodes   /DCTs
   /DCTDecodec                 C  s   i | ]\}}||qS r)   r)   )r1   r  vr)   r)   r*   
<dictcomp>Y  s    zPdfInlineImage.<dictcomp>r   _dataztuple[Object, ...]_image_object
image_dataimage_objecttuplec             
     sr   | _ | _d fdd|D }ztd| d }W n ty3 } z
td|d |d}~ww | _dS )	zConstruct wrapper for inline image.

        Args:
            image_data: data stream for image, extracted from content stream
            image_object: the metadata for image, also from content stream
            c                 3  s     | ]} j | jd V  qdS )remap_namesN)_unparse_objABBREVS)r1   rE   rb   r)   r*   	<genexpr>m  s    
z*PdfInlineImage.__init__.<locals>.<genexpr>s   << s    >>zparsing inline unicode_escapeN)r  r  joinr   parser   decoderE   )r\   r  r  ZreparseZreparsed_objr   r)   rb   r*   r   ^  s   
zPdfInlineImage.__init__c                 C  s8   t |tstS | j|jkot |to| j |j kS r   )r6   rS   r   rE   r  r  _inline_image_raw_bytesr   r)   r)   r*   r   v  s   
zPdfInlineImage.__eq__c                 C  s   t |tr#t |tr|jdd}t |tsJ |||S |jddS t |tr.|r,dS dS t |ttt	fr=t
|dS tt|)NT)resolveds   trues   falseascii)r6   r   r   unparser8   r   rg   r9   r   floatr:   encoder;   rw   )r   rE   r"  rG   r)   r)   r*   r#    s   


zPdfInlineImage._unparse_objc                 C  r   r   r   r[   r)   r)   r*   r]     r   zPdfInlineImage._metadatarA   r8   c                   s&   fdd  fdd}d | S )zACreate the content stream bytes that reproduce this inline image.c                  3  s6     j D ]}  j|  jd}t|tsJ |V  qd S )Nr!  )r  r#  REVERSE_ABBREVSr6   r8   )Zmetadata_objZunparsedrb   r)   r*   metadata_tokens  s   
z/PdfInlineImage.unparse.<locals>.metadata_tokensc                   3  s<    dV  d dd   D V  dV  j V  dV  d S )Ns   BI
r   c                 s      | ]}|V  qd S r   r)   )r1   r   r)   r)   r*   r%        zFPdfInlineImage.unparse.<locals>.inline_image_tokens.<locals>.<genexpr>s   
ID
s   EI)r'  r  r*  r)   r1  r\   r)   r*   inline_image_tokens  s   
z3PdfInlineImage.unparse.<locals>.inline_image_tokensr  )r'  )r\   r5  r)   r4  r*   r-    s   zPdfInlineImage.unparsec                 C  s   t d)zIRaise an exception since ICC profiles are not supported on inline images.zJInline images with ICC profiles are not supported in the PDF specification)r.   rb   r)   r)   r*   r|     s   zPdfInlineImage.iccc              
   C  sL   z| j }W n ty   d}Y nw d| d| j d| j dtt|  d	S )N?z#<pikepdf.PdfInlineImage image mode=r  r	  r
  r  )r   r;   rc   rf   r  r  )r\   r   r)   r)   r*   r    s   

zPdfInlineImage.__repr__c                 C  s   t  }|j| j| jfd |jd j| j d| j dddd |jd |   |jd 	  t
dd	 |jd j D }t|}|S )
N)Z	page_sizer   z 0 0 z 0 0 cmr,  T)prependc                 s  r2  r   r)   )r1   r   r)   r)   r*   r%    r3  z6PdfInlineImage._convert_to_pdfimage.<locals>.<genexpr>)r   newZadd_blank_pagerc   rf   ZpagesZcontents_addr/  r-  Zexternalize_inline_imagesnextZimagesvaluesr   )r\   ZtmppdfZraw_imgZimgr)   r)   r*   _convert_to_pdfimage  s   
z#PdfInlineImage._convert_to_pdfimager   c                 C     |    S )z&Return inline image as a Pillow Image.)r;  r   rb   r)   r)   r*   r     s   zPdfInlineImage.as_pil_imageNr   r   r   r   r   r:   c                C  s   |   j||dS )zxExtract the inline image directly to a usable image file.

        See:
            :meth:`PdfImage.extract_to`
        r   )r;  r   )r\   r   r   r)   r)   r*   r     s   zPdfInlineImage.extract_toc                 C  r<  )z Return decompressed image bytes.)r;  r   rb   r)   r)   r*   r     r   zPdfInlineImage.read_bytesc                 C  r<  )z"Return decompressed stream buffer.)r;  r   rb   r)   r)   r*   r     r   z PdfInlineImage.get_stream_buffer)r  r   r  r  r  r   )r   r   r   r:   )r%   r&   r'   r(   r$  itemsr0  rR   r   r   r  r#  r]   r-  r   r|   r  r;  r   r   r   r   r)   r)   r)   r*   r  B  sl   
 	







r  N)r/   r0   )r/   r@   rA   rB   )
rE   rF   rG   r:   rH   rI   rJ   r!   rA   rK   )=r(   
__future__r   abcr   r   decimalr   ior   	itertoolsr   pathlibr   shutilr	   typingr
   r   r   r   r   r   r   ZPILr   ZPIL.ImageCmsr   Zpikepdfr   r   r   r   r   r   r   r   r   r   Zpikepdf._exceptionsr   Zpikepdf._qpdfr   Zpikepdf._versionr   Zpikepdf.modelsr    r!   	Exceptionr#   r,   r-   r.   r?   rD   rO   rP   rS   r   r   r  r)   r)   r)   r*   <module>   sB   $0


    F