
    )iC                         S r SSKrSSKrSSKJr  SSKJr  SSK	J
r
  SSKJr  SSKJr  \R                  " \5      r " S S\R$                  5      rS r " S	 S
5      rg))	PdfBitmap
PdfPosConv    N)PdfiumError)Lazy)PDFIUM_INFOc                      ^  \ rS rSrSrU 4S jr\S 5       r\S 5       r	\
SS j5       r\
SS j5       r\
SS j5       r\
SS	 j5       rS
 rS rS r\
S 5       rS rSrU =r$ )r      a  
Bitmap helper class.

.. _PIL Modes: https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes

Warning:
    ``bitmap.close()``, which frees the buffer of foreign bitmaps, is not validated for safety.
    A bitmap must not be closed while 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).
    width (int):
        Width of the bitmap (horizontal size).
    height (int):
        Height of the bitmap (vertical size).
    stride (int):
        Number of bytes per line in the bitmap buffer.
        Depending on how the bitmap was created, there may be a padding of unused bytes at the end of each line, so this value can be greater than ``width * n_channels``.
    format (int):
        PDFium bitmap format constant (:attr:`FPDFBitmap_*`)
    rev_byteorder (bool):
        Whether the bitmap is using reverse byte order.
    n_channels (int):
        Number of channels per pixel.
    mode (str):
        The bitmap format as string (see `PIL Modes`_).
c	                 ~  > Xl         X l        X0l        X@l        XPl        X`l        Xpl        [        R                  U R
                     U l	        U R                  (       a  [        R                  O[        R                  U R
                     U l        S U l        [        T	U ]=  [         R"                  XR                  S9  g )N)
needs_freeobj)rawbufferwidthheightstrideformatrev_byteorderpdfium_iBitmapTypeToNChannels
n_channelsBitmapTypeToStrReverseBitmapTypeToStrmode	_pos_argssuper__init__pdfium_cFPDFBitmap_Destroy)
selfr   r   r   r   r   r   r   r   	__class__s
            Y/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/pypdfium2/_helpers/bitmap.pyr   PdfBitmap.__init__1   s    
*"88E/3/A/AH++$$
++	 44Q\Q\]    c                     g N r   s    r!   parentPdfBitmap.parentF   s    r#   c                     [         R                  " U 5      nU(       d  [        S5      e[        R                  " U[        R
                  " [        R                  5      5      n[        R                  " X1U-  5      $ )Nz3Failed to get bitmap buffer (null pointer returned))	r   FPDFBitmap_GetBufferr   ctypescastPOINTERc_ubyter   
get_buffer)r   r   r   
buffer_ptrs       r!   _get_bufferPdfBitmap._get_bufferT   sS    2237
STT[[V^^FNN-KL
"":f}==r#   c           
          [         R                  " U5      n[         R                  " U5      n[         R                  " U5      n[         R                  " U5      nUc  SU R                  XU5      pOSUpU " XXEXgX(5      $ )a  
Construct a :class:`.PdfBitmap` wrapper around a raw PDFium bitmap handle.

Note:
    This method is primarily meant for bitmaps provided by pdfium (as in :meth:`.PdfImage.get_bitmap`). For bitmaps created by the caller, where the parameters are already known, it may be preferable to call the :class:`.PdfBitmap` constructor directly.

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.
TF)r   FPDFBitmap_GetWidthFPDFBitmap_GetHeightFPDFBitmap_GetStrideFPDFBitmap_GetFormatr2   )
clsr   r   	ex_bufferr   r   r   r   r   r   s
             r!   from_rawPdfBitmap.from_raw]   st    " ,,S1..s3..s3..s3!%ssF'K!&	3v}YYr#   c                     [         R                  U   nUc  X-  nO
XaU-  :  d   eUc  [        R                  Xb-  -  " 5       nO[	        U5      Xb-  :  d   e[
        R                  " XX5U5      nU " XXXcUSS9$ )a  
Create a new bitmap using :func:`FPDFBitmap_CreateEx`, with a buffer allocated by Python/ctypes, or provided by the caller.

* If buffer and stride are None, a packed buffer is created.
* If a custom buffer is given but no stride, the buffer is assumed to be packed.
* If a custom stride is given but no buffer, a stride-agnostic buffer is created.
* If both custom buffer and stride are given, they are used as-is.

Caller-provided buffer/stride are subject to a logical validation.
Fr   )r   r   r,   r/   lenr   FPDFBitmap_CreateEx)	r9   r   r   r   r   r   r   bpcr   s	            r!   
new_nativePdfBitmap.new_native{   s     ,,V4>[FS[(((>nn8;Fv;&/111**5&&Q3v}Y^__r#   c                     U(       a  U[         R                  U   -  OSn[        R                  " XUSU5      nU(       d  [        R                  " U5      nU R                  XvU5      nU " XxXXcUSS9$ )a  
Create a new bitmap using :func:`FPDFBitmap_CreateEx`, with a buffer allocated by PDFium.
There may be a padding of unused bytes at line end, unless *force_packed=True* is given.

Note, the recommended default bitmap creation strategy is :meth:`.new_native`.
r   NTr>   )r   r   r   r@   r7   r2   )	r9   r   r   r   r   force_packedr   r   r   s	            r!   new_foreignPdfBitmap.new_foreign   sm     DP77??UV**5&$O2237Ff53v}Y]^^r#   c                     [         R                  " XU5      nUS-  nU R                  XVU5      nU(       a  [         R                  O[         R                  nU " XWXXhUSS9$ )a?  
Create a new bitmap using :func:`FPDFBitmap_Create`. The buffer is allocated by PDFium. 

PDFium docs specify that each line uses width * 4 bytes, with no gap between adjacent lines, i.e. the resulting buffer should be packed.

Contrary to the other ``PdfBitmap.new_*()`` methods, this method does not take a format constant, but a *use_alpha* boolean. If True, the format will be :attr:`FPDFBitmap_BGRA`, :attr:`FPFBitmap_BGRx` otherwise. Other bitmap formats cannot be used with this method.

Note, the recommended default bitmap creation strategy is :meth:`.new_native`.
   Tr>   )r   FPDFBitmap_Creater2   FPDFBitmap_BGRAFPDFBitmap_BGRx)	r9   r   r   	use_alphar   r   r   r   r   s	            r!   new_foreign_simplePdfBitmap.new_foreign_simple   sX     ((	Bf5-6))H<T<T3v}Y]^^r#   c                     [         R                  " XR                  5      n[        R                  " XX4XV5      nU(       d   [
        R                  S:  a  [        S5      egg)ag  
Fill a rectangle on the bitmap with the given color.
The coordinate system's origin is 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).
i  z Failed to fill bitmap rectangle.N)r   color_tohexr   r   FPDFBitmap_FillRectr   buildr   )r   colorlefttopr   r   c_coloroks           r!   	fill_rectPdfBitmap.fill_rect   sQ     &&u.@.@A))$c&Rk''4/@AA 0rr#   c                 r   [         R                  R                  U R                  S:  a#  U R                  U R
                  U R                  4OU R                  U R
                  4[        R                  U R                  U R                  S:  a  U R                  U R                  S4OU R                  S4S9nU$ )a  
Get a :mod:`numpy` array view of the bitmap.

The array contains as many rows as the bitmap is high.
Each row contains as many pixels as the bitmap is wide.
Each pixel will be an array holding the channel values, or just a value if there is only one channel (see :attr:`.n_channels` and :attr:`.format`).

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)
r   numpyndarrayr   r   r   r,   r/   r   r   )r   arrays     r!   to_numpyPdfBitmap.to_numpy   s    " 

""BF//TUBUT[[$**doo>\`\g\gimisis[tNN[[;???Q;Nt{{DOOQ7UYU`U`bcTd # 
 r#   c           	          [         R                  U R                     n[        R                  R                  UU R                  U R                  4U R                  SU R                  U R                  S5      nSUl        U$ )a  
Get a :mod:`PIL` image of the bitmap, using :func:`PIL.Image.frombuffer`.

For ``RGBA``, ``RGBX`` and ``L`` bitmaps, PIL is supposed to share memory with
the original 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).
r   r\   F)r   r   r   r   	PIL_Image
frombufferr   r   r   r   r   readonly)r   	dest_modeimages      r!   to_pilPdfBitmap.to_pil   sh     33DKK@	))ZZ%KKIIKK
 r#   c                 &   UR                   [        R                  ;   a  [        R                  UR                      nO([        U5      n[        R                  UR                      nUR
                  u  p4U R                  X4USUR                  5       S9$ )a|  
Convert a :mod:`PIL` image to a PDFium bitmap.
Due to the limited number of color formats and bit depths supported by :attr:`FPDF_BITMAP`, this may be a lossy operation.

Bitmaps returned by this function should be treated as immutable.

Parameters:
    pil_image (PIL.Image.Image):
        The image.
Returns:
    PdfBitmap: PDFium bitmap (with a copy of the PIL image's data).
F)r   r   )r   r   BitmapStrToConst_pil_convert_for_pdfiumBitmapStrReverseToConstsizerB   tobytes)r9   	pil_imager   whs        r!   from_pilPdfBitmap.from_pil  ss    " >>X666..y~~>F/	:I55innEF~~~~aF%	HYHYH[~\\r#   c                     U(       d   S5       eU R                   (       a  U R                   S   " 5       ULa  [        S5      e[        XR                   SS 5      $ )a  
Acquire a :class:`.PdfPosConv` object to translate between coordinates on the bitmap and the page it was rendered from.

This method requires passing in the page explicitly, to avoid holding a strong reference, so that bitmap and page can be independently freed by finalizer.
zPage must be non-nullr   z.This bitmap does not belong to the given page.r\   N)r   RuntimeErrorr   )r   pages     r!   get_posconvPdfBitmap.get_posconv5  sN     ,,,t~~!2!4D!@OPP$qr 233r#   )
r   r   r   r   r   r   r   r   r   r   )FN)FNN)FF)F)__name__
__module____qualname____firstlineno____doc__r   propertyr(   staticmethodr2   classmethodr;   rB   rF   rN   rY   rc   rk   rv   r{   __static_attributes____classcell__)r    s   @r!   r   r      s    >^*   > > Z Z: ` `> _ _  _ _"B>:> ] ]64 4r#   r   c                    U R                   S:X  a  U R                  S5      n OTU R                   R                  S5      (       a  O3SU R                   ;   a  U R                  S5      n OU R                  S5      n U R                   S:X  a7  U R                  5       u  pn[        R
                  R                  SX2U45      n U $ U R                   S:X  a7  U R                  5       u  pp4[        R
                  R                  SX2X45      n U $ U R                   S:X  a5  U R                  5       u  pp5[        R
                  R                  SX2X45      n U $ )N1LRGBARGBARGBX)r   convert
startswithsplitr   rf   merge)rs   rgbaxs         r!   ro   ro   C  s    ~~%%c*			"	"5	)	)			%%f-	%%e,	 ~~//#aNN((q	:	  
6	!__&
aNN((!>	  
6	!__&
aNN((!>	r#   c                   0    \ rS rSrSrS rS rS rS rSr	g)	r   i]  aG  
Pdf coordinate translator.

Hint:
    You may want to use :meth:`.PdfBitmap.get_posconv` to obtain an instance of this class.

Parameters:
    page (PdfPage):
        Handle to the page.
    pos_args (tuple[int*5]):
        pdfium canvas args (start_x, start_y, size_x, size_y, rotate), as in ``FPDF_RenderPageBitmap()`` etc.
c                     Xl         X l        g r%   rz   pos_args)r   rz   r   s      r!   r   PdfPosConv.__init__m  s    	 r#   c                 \    [         R                   SU R                   SU R                   S3$ )N(z, ))r   r}   rz   r   r'   s    r!   __repr__PdfPosConv.__repr__q  s*    %%&a		{"T]]O1EEr#   c                    [         R                  " 5       [         R                  " 5       pC[        R                  " U R                  /U R
                  QUPUPUPUP76 nU(       d  [        S5      eUR                  UR                  4$ )z,
Translate coordinates from bitmap to page.
z(Failed to translate to page coordinates.)r,   c_doubler   FPDF_DeviceToPagerz   r   r   value)r   bitmap_xbitmap_ypage_xpage_yrX   s         r!   to_pagePdfPosConv.to_paget  sn      *FOO,=''		fDMMf8fXfW]f_efHIIfll++r#   c                    [         R                  " 5       [         R                  " 5       pC[        R                  " U R                  /U R
                  QUPUPUPUP76 nU(       d  [        S5      eUR                  UR                  4$ )z,
Translate coordinates from page to bitmap.
z*Failed to translate to bitmap coordinates.)r,   c_intr   FPDF_PageToDevicerz   r   r   r   )r   r   r   r   r   rX   s         r!   	to_bitmapPdfPosConv.to_bitmap~  sl     $\\^V\\^(''		fDMMf6f6fS[f]efJKK//r#   r   N)
r}   r~   r   r   r   r   r   r   r   r   r&   r#   r!   r   r   ]  s    !F,0r#   r   )__all__r,   loggingpypdfium2.rawr   r   pypdfium2.internalinternalr   pypdfium2._helpers.miscr   pypdfium2._lazyr   pypdfium2.versionr   	getLoggerr}   loggerAutoCloseabler   ro   r   r&   r#   r!   <module>r      sU    &     % /   )			8	$o4'' o4d	4)0 )0r#   