o
    f=4                     @   s   d Z ddlZddlZddlZddlmZ ddlmZ ddl	m
Z ddlmZ eeZzddlZW n ey<   dZY nw zddlZW n eyN   dZY nw G dd dejZdd Zed	d
ZdS ))	PdfBitmapPdfBitmapInfo    N)
namedtuple)PdfiumErrorc                       s   e Zd ZdZ fddZedd Zdd Zedd
dZ	edddZ
edddZedddZdd Zdd Zdd ZedddZ  ZS )r   a  
    Bitmap helper class.
    
    Hint:
        This class provides built-in converters (e. g. :meth:`.to_pil`, :meth:`.to_numpy`) that may be used to create a different representation of the bitmap.
        Converters can be applied on :class:`.PdfBitmap` objects either as bound method (``bitmap.to_*()``), or as function (``PdfBitmap.to_*(bitmap)``)
        The second pattern is useful for API methods that need to apply a caller-provided converter (e. g. :meth:`.PdfDocument.render`)
    
    .. _PIL Modes: https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes
    
    Note:
        All attributes of :class:`.PdfBitmapInfo` are available in this class as well.
    
    Warning:
        ``bitmap.close()``, which frees the buffer of foreign bitmaps, is not validated for safety.
        A bitmap must not be closed when other objects still depend on its buffer!
    
    Attributes:
        raw (FPDF_BITMAP):
            The underlying PDFium bitmap handle.
        buffer (~ctypes.c_ubyte):
            A ctypes array representation of the pixel data (each item is an unsigned byte, i. e. a number ranging from 0 to 255).
    c	           	         st   ||||f\| _ | _| _| _|||| _| _| _tj| j | _	| jr&tj
ntj| j | _t jtj|| jd d S )N)
needs_freeobj)rawbufferwidthheightstrideformatrev_byteorderpdfium_iBitmapTypeToNChannels
n_channelsBitmapTypeToStrReverseBitmapTypeToStrmodesuper__init__pdfium_cFPDFBitmap_Destroy)	selfr   r	   r
   r   r   r   r   r   	__class__ R/home/ubuntu/webapp/venv/lib/python3.10/site-packages/pypdfium2/_helpers/bitmap.pyr   4   s
   zPdfBitmap.__init__c                 C   s   d S )Nr   r   r   r   r   parent<   s   zPdfBitmap.parentc              	   C   s$   t | j| j| j| j| j| j| jdS )zY
        Returns:
            PdfBitmapInfo: A namedtuple describing the bitmap.
        )r
   r   r   r   r   r   r   )r   r
   r   r   r   r   r   r   r   r   r   r   get_infoA   s   zPdfBitmap.get_infoFNc              
   C   s   t |}t |}t |}t |}|du r7d}t |}	|	du r'tdt|	t	tj
||  j}
nd}|}
| ||
||||||dS )a  
        Construct a :class:`.PdfBitmap` wrapper around a raw PDFium bitmap handle.
        
        Parameters:
            raw (FPDF_BITMAP):
                PDFium bitmap handle.
            rev_byteorder (bool):
                Whether the bitmap uses reverse byte order.
            ex_buffer (~ctypes.c_ubyte | None):
                If the bitmap was created from a buffer allocated by Python/ctypes, pass in the ctypes array to keep it referenced.
        NTz3Failed to get bitmap buffer (null pointer returned)F)r   r	   r
   r   r   r   r   r   )r   FPDFBitmap_GetWidthFPDFBitmap_GetHeightFPDFBitmap_GetFormatFPDFBitmap_GetStrideFPDFBitmap_GetBufferr   ctypescastPOINTERc_ubytecontents)clsr   r   	ex_bufferr
   r   r   r   r   
buffer_ptrr	   r   r   r   from_rawL   s    




 
zPdfBitmap.from_rawc                 C   sF   |t j|  }|du rtj||   }t|||||}| |||S )z
        Create a new bitmap using :func:`FPDFBitmap_CreateEx`, with a buffer allocated by Python/ctypes.
        Bitmaps created by this function are always packed (no unused bytes at line end).
        N)r   r   r&   r)   r   FPDFBitmap_CreateExr.   )r+   r
   r   r   r   r	   r   r   r   r   r   
new_nativep   s
   zPdfBitmap.new_nativec                 C   s4   |r	|t j|  nd}t|||d|}| ||S )z
        Create a new bitmap using :func:`FPDFBitmap_CreateEx`, with a buffer allocated by PDFium.
        
        Using this method is discouraged. Prefer :meth:`.new_native` instead.
        r   N)r   r   r   r/   r.   )r+   r
   r   r   r   force_packedr   r   r   r   r   new_foreign   s   zPdfBitmap.new_foreignc                 C   s   t |||}| ||S )a$  
        Create a new bitmap using :func:`FPDFBitmap_Create`. The buffer is allocated by PDFium.
        The resulting bitmap is supposed to be packed (i. e. no gap of unused bytes between lines).
        
        Using this method is discouraged. Prefer :meth:`.new_native` instead.
        )r   FPDFBitmap_Creater.   )r+   r
   r   	use_alphar   r   r   r   r   new_foreign_simple   s   zPdfBitmap.new_foreign_simplec                 C   s&   t || j}t| ||||| dS )a  
        Fill a rectangle on the bitmap with the given color.
        The coordinate system starts at the top left corner of the image.
        
        Note:
            This function replaces the color values in the given rectangle. It does not perform alpha compositing.
        
        Parameters:
            color (tuple[int, int, int, int]):
                RGBA fill color (a tuple of 4 integers ranging from 0 to 255).
        N)r   color_tohexr   r   FPDFBitmap_FillRect)r   lefttopr
   r   colorc_colorr   r   r   	fill_rect   s   zPdfBitmap.fill_rectc                 C   s0   t j| j| j| jftj| j| j| jdfd}|S )a*  
        Convert the bitmap to a :mod:`numpy` array.
        
        The array contains as many rows as the bitmap is high.
        Each row contains as many pixels as the bitmap is wide.
        The length of each pixel corresponds to the number of channels.
        
        The resulting array is supposed to share memory with the original bitmap buffer,
        so changes to the buffer should be reflected in the array, and vice versa.
        
        Returns:
            numpy.ndarray: NumPy array (representation of the bitmap buffer).
           )shapedtyper	   strides)	numpyndarrayr   r
   r   r&   r)   r	   r   )r   arrayr   r   r   to_numpy   s   	zPdfBitmap.to_numpyc              	   C   s<   t j| j }tj|| j| jf| jd| j	| j
d}d|_|S )a[  
        Convert the bitmap to a :mod:`PIL` image, using :func:`PIL.Image.frombuffer`.
        
        For ``RGBA``, ``RGBX`` and ``L`` buffers, PIL is supposed to share memory with
        the original bitmap buffer, so changes to the buffer should be reflected in the image, and vice versa.
        Otherwise, PIL will make a copy of the data.
        
        Returns:
            PIL.Image.Image: PIL image (representation or copy of the bitmap buffer).
        
        .. versionchanged:: 4.16 Set ``image.readonly = False`` so that changes to the image are also reflected in the buffer.
        r   r=   F)r   r   r   PILImage
frombufferr
   r   r	   r   r   readonly)r   	dest_modeimager   r   r   to_pil   s   
	zPdfBitmap.to_pilc                 C   sr   |j tjv rtj|j  }n
t|}tj|j  }| }|r(tjt| 	|}n|}|j
\}}| j|||d|dS )al  
        Convert a :mod:`PIL` image to a PDFium bitmap.
        Due to the restricted number of color formats and bit depths supported by PDFium's
        bitmap implementation, this may be a lossy operation.
        
        Bitmaps returned by this function should be treated as immutable (i.e. don't call :meth:`.fill_rect`).
        
        Parameters:
            pil_image (PIL.Image.Image):
                The image.
        Returns:
            PdfBitmap: PDFium bitmap (with a copy of the PIL image's data).
        
        .. deprecated:: 4.25
           The *recopy* parameter has been deprecated.
        F)r   r	   )r   r   BitmapStrToConst_pil_convert_for_pdfiumBitmapStrReverseToConsttobytesr&   r)   lenfrom_buffer_copysizer0   )r+   	pil_imagerecopyr   	py_bufferr	   whr   r   r   from_pil   s   
zPdfBitmap.from_pil)FN)FF)F)__name__
__module____qualname____doc__r   propertyr   r    classmethodr.   r0   r2   r5   r<   rD   rK   rX   __classcell__r   r   r   r   r      s&    
# r   c                 C   s   | j dkr| d} n| j drnd| j v r| d} n| d} | j dkr:|  \}}}tjd|||f} | S | j dkrT|  \}}}}tjd||||f} | S | j dkrl|  \}}}}tjd||||f} | S )N1LRGBARGBARGBX)r   convert
startswithsplitrE   rF   merge)rS   rgbaxr   r   r   rM     s&   



	

rM   r   z8width height stride format rev_byteorder n_channels mode)__all__r&   loggingweakrefcollectionsr   pypdfium2.rawr   r   pypdfium2.internalinternalr   pypdfium2._helpers.miscr   	getLoggerrY   logger	PIL.ImagerE   ImportErrorrA   AutoCloseabler   rM   r   r   r   r   r   <module>   s0   
 
