a :jg-:)@s&UddlmZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlmZmZmZmZddlmZddlmZddlmZmZmZmZmZmZddlmZm Z m!Z!m"Z"m#Z#m$Z$dd l%m&Z&m'Z'm(Z(dd l)m*Z*dd l+m,Z,m-Z-d e.d <zddl/m0Z0Wne1y>dZ0Yn0e2e3Z4Gddde5Z6Gddde7Z8dZ9de.d<e:dZ;de.d<zBddlme=ddkrde>e=ddde#Z?e1e?Wnte1y<Z@zZe,Ae1dZ=eBe@Cdre Dde5n eBe@Cd r&e DeBe@e5WYdZ@[@n dZ@[@00d!d"d#d$d%ZEGd&d'd'eZFGd(d)d)eZGGd*d+d+eZHeHjId,eHjJd-eHjKd-eHjLd.eHjMd/iZNGd0d1d1eZOGd2d3d3eZPGd4d5d5eZQe jRe3ZSeFeGeHeOePeQfD]"ZeD]ZTeUeSeTjVeTjWqqeXe=d6r8e=jYZYe=jZZZe=j[Z[e=j\Z\e=j]Z]erddl^Z^dd7l_m`Z`dd8lambZbdd9lmcZcmdZdmeZemfZfmgZgdd:lhmiZimjZjmkZkmlZlgZmd;e.d<<iZnd=e.d><iZod?e.d@<iZpdAe.dB<iZqdAe.dC<iZrd?e.dD<iZsdEe.dF<iZtdGe.dH<e judIkrdJndKZvdLdMdNdOdPZwgdQZxdRZydSdSdTdUdVZzdSdSdTdWdXZ{dSdYdTdZd[Z|dSd\dTd]d^Z}da~d_d`dadbZdd`dcddZddSdSd!dfdgdhdidjZddSdSd!dfdkdldmdnZGdodpdpZdqdrdsdtduZGdvdwdweZGdxdLdLZGdydzdzZGd{d|d|ZdLd`d}d~Zd!d_dddZddSdddLdddZAddSdddSd!dLdddZddSdddSd!dLdddZGdddeZddddLdddZdddNddZdddNddZdddddddddddddddddddddddddddddddddddddevdfddevdĝfdiZdd_dddDŽZdddddd̜dd΄ZdLdLdLdϜddфZdLdLddLdӜddՄZdLdLdLdLd֜dd؄ZdLddLdڜdd܄ZdSddLdޜddZddSddd_dddZdSdSd_dddZdSdd_dddZdSdd_dddZdSdSd_dddZdSd;d_dddZd?d`ddZdSdd_dddZdSdd_dddZdLd!d_dddZddd\dLdddZdddLdddZdSdLdTd d ZdSdLdTd d Zdd d_dddZeee=jeree:efZneZGdddeZdS() annotationsN)CallableIteratorMutableMappingSequence)IntEnum) ModuleType)IO TYPE_CHECKINGAnyLiteralProtocolcast)ExifTags ImageModeTiffTagsUnidentifiedImageError __version___plugins)i32leo32beo32le) deprecate) DeferredErroris_pathzModuleType | None ElementTree)rc@s eZdZdS)DecompressionBombWarningN__name__ __module__ __qualname__r"r"3/usr/local/lib/python3.9/site-packages/PIL/Image.pyrMsrc@s eZdZdS)DecompressionBombErrorNrr"r"r"r#r$Qsr$FboolWARN_POSSIBLE_FORMATSiUUU int | NoneMAX_IMAGE_PIXELS)_imagingZPILLOW_VERSIONzUThe _imaging extension was built for another version of Pillow or PIL: Core version: z Pillow version: z'The _imaging C module is not installed.zModule use of pythonz?The _imaging extension was built for another version of Python.zThe _imaging extensionr zTypeGuard[Image])treturncCstdddt|dS)z Checks if an object is an image object. .. warning:: This function is for internal use only. :param t: object to check if it's an image :returns: True if the object is an image zImage.isImageType(im) zisinstance(im, Image.Image)im)rhasattr)r*r"r"r# isImageType}s r/c@s(eZdZdZdZdZdZdZdZdZ dS) TransposerrN) rr r!ZFLIP_LEFT_RIGHTZFLIP_TOP_BOTTOM ROTATE_90 ROTATE_180 ROTATE_270Z TRANSPOSEZ TRANSVERSEr"r"r"r#r0sr0c@s eZdZdZdZdZdZdZdS) Transformrrr1r2r3N)rr r!AFFINEEXTENT PERSPECTIVEQUADMESHr"r"r"r#r9s r9c@s$eZdZdZdZdZdZdZdZdS) Resamplingrr3r1r4r2rN) rr r!NEARESTBOXBILINEARHAMMINGBICUBICLANCZOSr"r"r"r#r?s r???@g@c@seZdZdZdZdZdZdS)Ditherrrr1r2N)rr r!NONEZORDEREDZ RASTERIZEFLOYDSTEINBERGr"r"r"r#rIsrIc@seZdZdZdZdS)PaletterrN)rr r!WEBADAPTIVEr"r"r"r#rLsrLc@seZdZdZdZdZdZdS)Quantizerrr1r2N)rr r! MEDIANCUTZ MAXCOVERAGE FASTOCTREE LIBIMAGEQUANTr"r"r"r#rOsrODEFAULT_STRATEGY)Element) PrettyPrinter) ImageFile ImageFilter ImagePaletteImageQtTiffImagePlugin) CapsuleType NumpyArrayStrOrBytesPath TypeGuardz list[str]IDzodict[str, tuple[Callable[[IO[bytes], str | bytes], ImageFile.ImageFile], Callable[[bytes], bool | str] | None]]OPENzdict[str, str]MIMEz:dict[str, Callable[[Image, IO[bytes], str | bytes], None]]SAVESAVE_ALL EXTENSIONz$dict[str, type[ImageFile.PyDecoder]]DECODERSz$dict[str, type[ImageFile.PyEncoder]]ENCODERSlittle<>Imageztuple[tuple[int, ...], str]r-r+cCs>t|j}|j|jf}t|j}|dkr4||f7}||jfSNr)rgetmodemodeheightwidthlenbandstypestr)r-mshapeextrar"r"r#_conv_type_shapes     rw)1CMYKFZHSVII;16I;16BI;16LzI;16NLLALaLABPPARGBRGBARGBaRGBXZYCbCr)rrrrryr|r~r}str)rnr+cCs t|jS)a% Gets the "base" mode for given mode. This function returns "L" for images that contain grayscale data, and "RGB" for images that contain color data. :param mode: Input mode. :returns: "L" or "RGB". :exception KeyError: If the input mode was not a standard mode. )rrmZbasemodernr"r"r# getmodebases rcCs t|jS)a  Gets the storage type mode. Given a mode, this function returns a single-layer mode suitable for storing individual bands. :param mode: Input mode. :returns: "L", "I", or "F". :exception KeyError: If the input mode was not a standard mode. )rrmZbasetyperr"r"r# getmodetype,s rtuple[str, ...]cCs t|jS)a Gets a list of individual band names. Given a mode, this function returns a tuple containing the names of individual bands (use :py:method:`~PIL.Image.getmodetype` to get the mode used to store each individual band. :param mode: Input mode. :returns: A tuple containing band names. The length of the tuple gives the number of bands in an image of the given mode. :exception KeyError: If the input mode was not a standard mode. )rrmrrrr"r"r#getmodebandnames8s rintcCstt|jS)z Gets the number of individual bands for this mode. :param mode: Input mode. :returns: The number of bands in this mode. :exception KeyError: If the input mode was not a standard mode. )rqrrmrrrr"r"r# getmodebandsGsrNoner+cCstdkr dSzddlm}|s"JWnty6Yn0zddlm}|sNJWntybYn0zddlm}|szJWntyYn0zddlm}|sJWntyYn0zddlm}|sJWntyYn0dadS)z| Explicitly loads BMP, GIF, JPEG, PPM and PPM file format drivers. It is called when opening or saving images. rN)BmpImagePlugin)GifImagePlugin)JpegImagePlugin)PpmImagePlugin)PngImagePlugin) _initializedr ImportErrorrrrr)rrrrrr"r"r#preinitXs8               rc Cstdkr dStdd}tD]d}z,td|t|d|ttgWqt y}ztd||WYd}~qd}~00qt st rdadSdS) z Explicitly initializes the Python Imaging Library. This function loads all available file format drivers. It is called when opening or saving images if :py:meth:`~preinit()` is insufficient, and by :py:meth:`~PIL.features.pilinfo`. r1F.rz Importing %szImage: failed to import %s: %sNT) rr rpartitionrloggerdebug __import__globalslocalsrr`rb) parent_namepluginer"r"r#inits   &rr"ztuple[Any, ...]z)core.ImagingDecoder | ImageFile.PyDecoder)rn decoder_nameargsrvr+c Cs|durd}nt|ts|f}z t|}Wnty<Yn0||g||RSztt|d}Wn:ty}z"d|d}t||WYd}~n d}~00||g||RS)Nr"_decoderzdecoder  not available) isinstancetuplereKeyErrorgetattrcoreAttributeErrorOSError)rnrrrvdecoderrmsgr"r"r# _getdecoders     rz)core.ImagingEncoder | ImageFile.PyEncoder)rn encoder_namerrvr+c Cs|durd}nt|ts|f}z t|}Wnty<Yn0||g||RSztt|d}Wn:ty}z"d|d}t||WYd}~n d}~00||g||RS)Nr"_encoderzencoder r)rrrfrrrrr)rnrrrvencoderrrr"r"r# _getencoders     rc@seZdZdZddddddZdddd Zd dd d d ZeZd dd ddZd dd ddZ d dd ddZ e Z d dd ddZ dS)ImagePointTransformz Used with :py:meth:`~PIL.Image.Image.point` for single band images with more than 8 bits, this represents an affine transformation, where the value is multiplied by ``scale`` and ``offset`` is added. floatr)scaleoffsetr+cCs||_||_dSN)rr)selfrrr"r"r#__init__szImagePointTransform.__init__rcCst|j |j Sr)rrrrr"r"r#__neg__szImagePointTransform.__neg__zImagePointTransform | floatotherr+cCs6t|tr$t|j|j|j|jSt|j|j|Sr)rrrrrrr"r"r#__add__s  zImagePointTransform.__add__cCs || Srr"rr"r"r#__sub__szImagePointTransform.__sub__cCs || Srr"rr"r"r#__rsub__szImagePointTransform.__rsub__cCs$t|trtSt|j||j|SrrrNotImplementedrrrr"r"r#__mul__s zImagePointTransform.__mul__cCs$t|trtSt|j||j|Srrrr"r"r# __truediv__s zImagePointTransform.__truediv__N) rr r!__doc__rrr__radd__rrr__rmul__rr"r"r"r#rsrzd?Ze d@ddAdBZdCddDdEZdCddFdGdHZ d!dd)dJdKdLdMZ!d"ddJdOdPdQZ"d#dRdd)ddSdTdUZ#dVddWdXZ$dddYdZZ%ddde&j'd[fdd\d]d^ddd_d`daZ(d[ddbde)j*fddcddddeddfdgdhZ+dddidjZ,e,Z-d$dkddldmdnZ.d dod dpdqdrZ/ddsdtdudvdwZ0d%ddcddxdydzZ1d{dd|d}d~Z2ddddZ3ddd.ddddZ4d&dddddZ5d'dcd dddZ6ddddZ7ddddZ8ddddZ9ddddZ:ddddZ;ddddZ<d(dddddZ=e d.dddZ>ddddZ?dddddZ@ddddZAd)dddddddZBd*dddddddZCd+ddddddddZDd,dddddddZEd-ddddÜddńZFdddǜddɄZGd.ddddd͜ddτZHd/ddddќddӄZIdddd՜ddׄZJd0ddddٜddۄZKdddoddޜddZLd1ddcdkdddddZMd2ddddddZNeOjPddddfdddddsdddddZQd3ddd)ddddZRdddddZSd4dddddZTddddZUdddddZVddddZWeOjXdfdddddddZYdeOjPddfdd d ddddd d d ZZeOjPdfdddddd.ddddZ[dddddZ\dddddZ]ddddZ^ddddZ_dS(5rjaD This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` N str | Noneformatformat_descriptionTrrcCs.d|_d|_d|_d|_i|_d|_d|_dS)Nrrrr)_im_mode_sizepaletteinforeadonly_exifrr"r"r#r%szImage.__init__zcore.ImagingCorecCs(t|jtr|jj|jdus"J|jSr)rrrexrr"r"r#r-0s zImage.imrkcCs ||_dSr)rrr-r"r"r#r-7srcCs |jdSNrsizerr"r"r#rp;sz Image.widthcCs |jdSrlrrr"r"r#ro?sz Image.heighttuple[int, int]cCs|jSr)rrr"r"r#rCsz Image.sizercCs|jSr)rrr"r"r#rnGsz Image.modecCs`t}||_|j|_|j|_|jdvrP|jr:|j|_nddlm }| |_|j |_ |S)NrrrrX) rjr-rnrrrrcopyrrXr)rr-newrXr"r"r#_newKs    z Image._newcCs|Srr"rr"r"r# __enter__[szImage.__enter__cCsDt|ddr0|j|jkr"|jttd|_|jr@|jdS)N_fpFOperation on closed image)rrfpcloser ValueErrorrr"r"r# _close_fp^s    zImage._close_fpcGs(t|dr$t|ddr|d|_dS)Nr _exclusive_fpF)r.rrr)rrr"r"r#__exit__fs  zImage.__exit__c Csrt|drNz|d|_Wn0tyL}ztd|WYd}~n d}~00t|ddr`d|_tt d|_ dS)a Closes the file pointer, if possible. This operation will destroy the image core and release its memory. The image data will be unusable afterward. This function is required to close images that have multiple frames or have not had their file read and closed by the :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for more information. rNzError closing: %smapr) r.rr Exceptionrrrrrrr)rrr"r"r#rls  " z Image.closecCs||j|_d|_dSr)loadr-rrrr"r"r#_copys z Image._copycCs|jr|n|dSr)rrrrr"r"r#_ensure_mutables zImage._ensure_mutabler )fileroptionsr+cKsd}|rd|}|s0t|\}}t|n|}||sF||}||rZ|dkrh|j|n|j||fi||S)NrrZPPM) tempfilemkstemposrendswithrr-Zsave_ppmsave)rrrrsuffixffilenamer"r"r#_dumps    z Image._dumpobjectr%rcCsb|j|jurdSt|tsJ|j|jko`|j|jko`|j|jko`||ko`||kSNF) __class__rrjrnrr getpalettetobytesrr"r"r#__eq__s    z Image.__eq__cCs.d|jj|jj|j|jd|jdt|fS)Nz(<%s.%s image mode=%s size=%dx%d at 0x%X>rr)rr rrnridrr"r"r#__repr__szImage.__repr__rU)pcycler+c Cs2|d|jj|jj|j|jd|jdfdS)z"IPython plain text display supportz <%s.%s image mode=%s size=%dx%d>rrN)textrr rrnr)rr rr"r"r# _repr_pretty_szImage._repr_pretty_z bytes | None) image_formatkwargsr+cKs>t}z|j||fi|Wnty4YdS0|S)zHelper function for iPython display hook. :param image_format: Image format. :returns: image as bytes, saved into the given format. N)ioBytesIOrrgetvalue)rrrbr"r"r# _repr_images  zImage._repr_imagecCs|jdddS)zjiPython display hook support for PNG format. :returns: PNG version of the image as bytes ZPNGr)Zcompress_levelrrr"r"r# _repr_png_szImage._repr_png_cCs |dS)zliPython display hook support for JPEG format. :returns: JPEG version of the image as bytes ZJPEGrrr"r"r# _repr_jpeg_szImage._repr_jpeg_z.dict[str, str | bytes | int | tuple[int, ...]]cCsHddi}|jdkr$|dd|d<n ||d<t|\|d<|d<|S) Nversionr2rxrawrdatarurs)rnr rw)rrr"r"r#__array_interface__s   zImage.__array_interface__z list[Any]cCs |}|j|j|j||gSr)r rrnrr)rZim_datar"r"r# __getstate__szImage.__getstate__)stater+cCs\t||\}}}}}||_||_||_t|||_|dvrN|rN||| |dS)Nrrrr) rjrrrrrrr- putpalette frombytes)rr rrnrrrr"r"r# __setstate__s   zImage.__setstate__rbytes)rrr+c Gs|}t|dkr&t|dtr&|d}|dkr<|dkr<|j}||jdksX|jdkr\dSt|j||}||j t d|j dd}g}| |\}}} | | |rqq|dkrd|d } t| d|S) a! Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. A list of C encoders can be seen under codecs section of the function array in :file:`_imaging.c`. Python encoders are registered within the relevant plugins. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. rrrr"ir3zencoder error z in tobytes)rqrrrnrrprorsetimager-maxrencodeappend RuntimeErrorjoin) rrrZ encoder_argsrbufsizeoutputZbytes_consumederrcoderrr"r"r#r s(   z Image.tobytesimage)namer+cCs~||jdkrd}t||d}dd|d|jddd d|d |jd dd d |d d |dgS)a- Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" rxz not a bitmapZxbmr&z#define z_width r asciiz_height rz static char z _bits[] = { s};)rrnrr r,rr))rr1rrr"r"r#tobitmap<s   zImage.tobitmap*bytes | bytearray | SupportsArrayInterface)rrrr+cGs|jdks|jdkrdS|}t|dkr>t|dtr>|d}|dkrT|dkrT|j}t|j||}||j| |}|ddkrd}t ||ddkrd}t |dS)z Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. rNrrr"znot enough image datazcannot decode image data) rprorqrrrnrr'r-decoder)rrrr decoder_argsdsrr"r"r#r#Vs     zImage.frombyteszcore.PixelAccess | NonecCs|jdur|jr|jjr|j\}}|j|jj||d|j_d|j_d|jvr|dvrt |jdt r|j |jddn|j |jdd|j_n|j |jj|jj|j_|jdur|j|jSdS)at Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :py:class:`.PixelAccess` Nr transparencyrrr)rrdirtyrr-r"rnrawmoderrrputpalettealphaputpalettealphasrZ pixel_accessr)rrnarrr"r"r#r{s    z Image.loadcCsdS)as Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. Nr"rr"r"r#verifys z Image.verifyztuple[float, ...] | Nonez Dither | NonerL)rnmatrixditherrcolorsr+c s0|dvrt|d|d|jv}|sV|jdkrV|jrB|jj}nd}|dkrV|rVd}|rh||jkrpsp|Sr&|dvrd}t||j|}| |} |r"|jj d kr"| jdd d d d dd|dkrn2t |d krt fddt dt D| jd<| S|dkrF|jdkrF||Sd} d} |rB|jdvrj|dvs|jdkr|dvr| |j||jd} | jd=| S|jdvr|dvr|jd} t| trtdd} nt|jd} |jdkr|jdus J| |j|jjt| t rd}| jdus}zd}t||WYd}~n d}~00Yn0| |} |dkr|tjkrd"d#l m!}|!d|"d| _| r| jd=| dur,| jdkr"| jr"z&| jt#t td$f| | | jd<WnFty}z,| jd=t|dkr td%WYd}~n d}~00n | | jd<| S)*a Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. This supports all possible conversions between "L", "RGB" and "CMYK". The ``matrix`` argument only supports "L" and "RGB". When translating a color image to grayscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a grayscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is ``None``, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. When converting from "PA", if an "RGBA" palette is present, the alpha channel from the image will be used instead of the values from the palette. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`Palette.WEB` or :data:`Palette.ADAPTIVE`. :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. zBGR;15zBGR;16zBGR;24r,r:rrr)rrzillegal conversionr2ztuple[float, ...]ztuple[int, int, int]r)rtvr+cSsP|d|d|d|d|d|d|dd}tdtdt|S)Nrrr1r2rF)r(minr)rtrGvaluer"r"r#convert_transparencys<z+Image.convert..convert_transparencyrc3s,|]$}|d|ddVqdS)r3Nr".0irKrCr:r"r# sz Image.convert..rNF)rxrr{r|rr)rrrr)rrrzVPalette images with Transparency expressed in bytes should be converted to RGBA imagesTrrz2Couldn't allocate a palette color for transparencyz$cannot allocate more than 256 colorsrrrrz.Transparency for P mode should be bytes or intrr.z0Couldn't allocate palette entry for transparencyr)rrr)ImageCmsZsRGB)-rrrrnrrrr-Zconvert_matrixrrrrqrrangequantizeZconvert_transparentrr%warningswarnrr"getcolorrputpixelconvertgetpixelr?rr>rLrNrrXrrrrTZ createProfileZbuildTransformapplyrIrKrr)rrnrCrDrrEZhas_transparencyrr-new_imZtrnsZ delete_trnsr*Ztrns_imerrrrXZ other_moderTZsrgbZlabZprofiles transformZmodebaser"rOr#r[s*4                                          &    z Image.convertrr'z Image | NonerI)rEmethodkmeansrrDr+c Cs.||dur&tj}|jdkr&tj}|jdkrL|tjtjfvrLd}t||r||jdkrnd}t||jdvrd}t||jd||j}| |}|j dusJ|j |_ |S|dkrd }t|| |j |||}d d l m} |j} |j| | d|t| } | | | |_ |S) a3 Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`Quantize.MEDIANCUT` (median cut), :data:`Quantize.MAXCOVERAGE` (maximum coverage), :data:`Quantize.FASTOCTREE` (fast octree), :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`Quantize.MEDIANCUT` will be used. The exception to this is RGBA images. :data:`Quantize.MEDIANCUT` and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so :data:`Quantize.FASTOCTREE` is used by default instead. :param kmeans: Integer greater than or equal to zero. :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). :returns: A new image NrzoFast Octree (method == 2) and libimagequant (method == 3) are the only valid methods for quantizing RGBA imagesrzbad mode for palette image>rrz7only RGB or L mode images can be quantized to a paletterzkmeans must not be negativerr)rrOrPrnrQrRrr-r[rrrrVrrXgetpalettemoderrq) rrErarbrrDrr-r^rXrnZ palette_datar"r"r#rVsD#        zImage.quantizecCs|||jS)z Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. )rrr-rrr"r"r#rsz Image.copyz(tuple[float, float, float, float] | None)boxr+cCsf|dur|S|d|dkr.d}t|n|d|dkrJd}t|||||j|S)a Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. Nr1rz&Coordinate 'right' is less than 'left'r2rz'Coordinate 'lower' is less than 'upper')rrrr_cropr-)rrdrr"r"r#crops  z Image.crop!tuple[float, float, float, float])r-rdr+cCsJtttt|\}}}}t||t||f}t||||||fS)a] Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. )rrroundabs_decompression_bomb_checkrf)rr-rdx0y0x1y1Zabsolute_valuesr"r"r#re!sz Image._croptuple[int, int] | Nonez0tuple[str, tuple[int, int, float, float]] | None)rnrr+cCsdS)aY Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to grayscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size in pixels, as a 2-tuple: (width, height). Nr")rrnrr"r"r#draft7sz Image.draft)xmarginymarginr+cCs(|dur |}|||j||Sr)rrr-expand)rrqrrr"r"r#_expandPsz Image._expandz-ImageFilter.Filter | type[ImageFilter.Filter])filterr+csddlm}tr"tds8d}t|t|j}jj dksT|rf jSfddt jj D}t j|S)z Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.r)rWruz>filter argument should be ImageFilter.Filter instance or classc s$g|]}j|qSr")rrur-getband)rMcrurr"r# lsz Image.filter..)rrWrcallabler. TypeErrorrZMultibandFilterr-rrrrurUmergern)rrurWrZ multibandZimsr"rxr#ruVs     z Image.filterrcCst|jjS)z Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple )rrmrnrrrr"r"r#getbandsqszImage.getbands) alpha_onlyz tuple[int, int, int, int] | None)r~r+cCs||j|S)aG Calculates the bounding box of the non-zero regions in the image. :param alpha_only: Optional flag, defaulting to ``True``. If ``True`` and the image has an alpha channel, trim transparent pixels. Otherwise, trim pixels when all channels are zero. Keyword-only argument. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. )rr-getbbox)rr~r"r"r#r{sz Image.getbboxzBlist[tuple[int, tuple[int, ...]]] | list[tuple[int, float]] | None) maxcolorsr+csR||jdvrF|jfddtdD}t||krBdS|S|j|S)a Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. )rxrrcs g|]}|r||fqSr"r"rLhr"r#ryr&z#Image.getcolors..rBN)rrnr- histogramrUrq getcolors)rroutr"rr#rs   zImage.getcolors)bandr+cCs"||dur|j|S|jS)a Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. N)rr-rv)rrr"r"r#rs z Image.getdataz1tuple[float, float] | tuple[tuple[int, int], ...]cs<jjdkr2tfddtjjDSjS)a" Gets the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. rc3s|]}j|VqdSr)r-rv getextremarLrr"r#rPr&z#Image.getextrema..)rr-rrrrUrrr"rr#rs  zImage.getextremadict[str, Any]csrddddddddfdd td ur.get_namerTzstr | dict[str, Any] | None)elementr+csfdd|jD}t|}|r~|D]R}|j}|}||vrrt||tsb||g||<|||q(|||<q(n|r|jr|j|d<n|jS|S)Ncsi|]\}}||qSr"r"rMkrG)rr"r# r&z3Image.getxmp..get_value..r)Zattribitemslistrrr*r)rrJchildrenchildr1Z child_valuer get_valuer"r#rs    zImage.getxmp..get_valueNz5XMP data cannot be read without defusedxml dependencyZxmp)rrWrXrZ fromstringrstripr)rrootr"rr#getxmps  z Image.getxmpExifcCs|jdurt|_n|jjr"|jSd|j_|jd}|durd|jvrntd|jdddd}n6t |dr|j j |j_ |j j |j_|j|j|j j|dur|j|tjj|jvr|jd }|rtd |}|rt|d |jtjj<|jS) zj Gets EXIF data from the image. :returns: an :py:class:`~PIL.Image.Exif` object. NTexifzRaw profile type exifrr2r2tag_v2zXML:com.adobe.xmpztiff:Orientation(="|>)([0-9])r1)rr_loadedrgetr%fromhexr,splitr.rZ_bigtiffbigtiff_endianendian load_from_fpr_offsetrrBaseZ Orientationrsearchr)rZ exif_infoZxmp_tagsmatchr"r"r#getexifs0          z Image.getexifcCs*|jdus|jjsdSd|j_|dSr)rrrrr"r"r# _reload_exifszImage._reload_exifzlist[ImageFile.ImageFile]c Csg}|}g}tjj|vrZ|tjj}|rZt|ts<|f}|D]}||||fq@|tj j }|r| dr|j dusJ|||j j fd}|D]\}} |j} |dur| }|j} |dur| d} | dur| t|dd7} |j| |j| d} t| } t| X}ddlm}| durXt||jrX| g|_|d|||Wdq1s0Yq|dur|j||S)NiZ _exif_offsetrirrZ)rrrZSubIFDsrrr* _get_ifd_dictget_ifdIFDIFD1r_infonextrtellrseekreadrropenrrZZ TiffImageFileZ _frame_posZ_seekr)rZ child_imagesrZifdsZsubifd_offsetsZ subifd_offsetZifd1rifd ifd_offsetcurrent_offsetrZthumbnail_offsetrr-rZr"r"r#get_child_imagessN              ,  zImage.get_child_imagesr[cCs||jjS)zr Returns a capsule that points to the internal image memory. :returns: A capsule object. )rr-Zptrrr"r"r#getimKsz Image.getimrzlist[int] | None)r=r+cCsJ|z|j}Wnty*YdS0|dur8|}t|j||S)aG Returns the image palette as a list. :param rawmode: The mode in which to return the palette. ``None`` will return the palette in its current mode. .. versionadded:: 9.1.0 :returns: A list of color values [r, g, b, ...], or None if the image has no palette. N)rr-rcrrr)rr=rnr"r"r#rUs  zImage.getpalettecCsB|jdvsd|jvrdS|jdkr>|jdus0J|jjdSdS)aN Determine if an image has transparency data, whether in the form of an alpha channel, a palette with an alpha channel, or a "transparency" key in the info dictionary. Note the image might still appear solid, if all of the values shown within are opaque. :returns: A boolean. )rrrrrr:TrNAF)rnrrrrr"r"r#has_transparency_dataks  zImage.has_transparency_datacCs|jdksd|jvrdSddlm}|d}|dus:J|jd}t|trrt|D]\}}|||dd<qVnd ||dd<|dt||_d|j_ |jd=dS) z If a P mode image has a "transparency" key in the info dictionary, remove the key and instead apply the transparency to the palette. Otherwise, the image is unchanged. rr:Nrrrr3r2r) rnrrrXrrr% enumeraterr<)rrXrr:rNalphar"r"r#apply_transparencys     zImage.apply_transparencytuple[int, int] | list[int]zfloat | tuple[int, ...] | None)xyr+cCs||jt|S)a  Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. )rr-r\r)rrr"r"r#r\s zImage.getpixelztuple[list[int], list[int]]cCs&||j\}}t|t|fS)z Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. )rr- getprojectionr)rxyr"r"r#rszImage.getprojectionztuple[float, float] | Nonez list[int])maskextremar+cCsT||r$||jd|jS|jdvrJ|j|dur@|n|S|jS)a Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. Counts are grouped into 256 bins for each band, even if the image has more than 8 bits per band. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a grayscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a grayscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. rr{rzN)rr-rrnrrrrr"r"r#rs zImage.histogramrcCsT||r$||jd|jS|jdvrJ|j|dur@|n|S|jS)ah Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a grayscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a grayscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy rrN)rr-entropyrnrrr"r"r#rs z Image.entropyz'Image | str | float | tuple[float, ...]z:Image | tuple[int, int, int, int] | tuple[int, int] | None)r-rdrr+cCs>t|tr&|durd}t||}d}|dur2d}t|dkrt|trP|j}nt|trb|j}n d}t|||d|d|d|df7}t|trddlm}|||j }nJt|tr| |j |j kr|j d ks|j d vr| |j }|j }n|}| |r,| |j |||j n|j ||dS) a Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", "LA", "RGBA" or "RGBa" images (if present, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer, float or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. Nz=If using second argument as mask, third argument must be Nonerr1z,cannot determine region size; use 4-item boxrr ImageColorr)rrr)rrjrrqrrrrrYrnrr[r-rpaste)rr-rdrrrrsourcer"r"r#rs>-    $     z Image.pasterz Sequence[int])r-destrr+c Cst|ttfsd}t|t|ttfs4d}t|t|dkrJt|}n(t|dkrft||j}n d}t|t|dksd}t|t|dkrd}t||d |jkr|}n ||}t||d|j|d |j f}|d |jkr|}n ||}t ||} | | |d S) a-'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. zSource must be a list or tuplez#Destination must be a list or tupler3r1z*Source must be a sequence of length 2 or 4z*Destination must be a sequence of length 2rzSource must be non-negativerrN) rrrrrqrrIrfrproalpha_compositer) rr-rrrZoverlay_crop_boxoverlayrd backgroundresultr"r"r#rLs6      $  zImage.alpha_compositezSequence[float] | NumpyArray | Callable[[int], float] | Callable[[ImagePointTransform], ImagePointTransform | float] | ImagePointHandler)lutrnr+cs|ttr|Strn|jdvrNt\}}||j ||Sfddt dD|jj }n}|jdkrd}t ||dkrdd|D}||j||S)a Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, im: Image) -> Image: # Return result :param mode: Output mode (default is same as input). This can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. )r{r|rzcsg|] }|qSr"r"rLrr"r#ryr&zImage.point..rBrzz+point operation not supported for this modecSsg|] }t|qSr")rhrLr"r"r#ryr&) rrImagePointHandlerpointrzrnrrr-Zpoint_transformrUrrr)rrrnrrZflatLutrr"rr#rs!      z Image.pointz Image | int)rr+c Csn||jdvrzt|jd}z|j|WnRttfy}z6|j|}|jdvrjd}t||||_WYd}~n d}~00|jj|_Wn2t y}zd}t||WYd}~n d}~00|jdvrd}nd}t |t r|jd vrd}t|| |jd krZ|d }n>z|j ||Wn&ttfyTtd |j|}Yn0dS|j|j|dS) aZ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer. rSrz alpha channel could not be addedNillegal image moder;rr2)rxrrxr)rrnrr-Zsetmoderrr[rrrrjrZfillbandrrZputband)rrrnrr-rrr"r"r#putalphas@           zImage.putalpharGzISequence[float] | Sequence[Sequence[int]] | core.ImagingCore | NumpyArray)rrrr+cCs||j|||dS)a| Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. N)rr-putdata)rrrrr"r"r#rsz Image.putdataz1ImagePalette.ImagePalette | bytes | Sequence[int])rr=r+cCsddlm}|jdvr"d}t|t||jr`|jdurJ||j|j}q~|j|jd}d|_nt|t srt |}|||}d|jvrdnd |_ ||_d|vrd nd |j_| dS) a} Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L"). rrr!rNrrrrrr) rrXrnrrr=rrr<r%rr)rrr=rXrrr"r"r#r"s       zImage.putpalettez#float | tuple[int, ...] | list[int])rrJr+cCs|jr|||jdvrt|ttfrt|dvr|jdkrht|dkrX|dnd}|dd}|jdusvJ|j t||}|jdkr||fn|}|j ||S)a Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P and PA images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. r)r2r3rr3r2rHN) rrrrnrrrrqrrYr-rZ)rrrJrZ palette_indexr"r"r#rZ9s     zImage.putpixelzbytes | bytearray | None)dest_mapsource_paletter+c Csddlm}|jdvr"d}t|d}d}|dur|jdkrj||j}|d krZd }|j||}qtd d t d D}nt |d krd }d }d}dgd}t |D],\} } ||| || ||7}| || <qt|} | } d| _ |j|| |d| _| j||d| j| d} | |||j||d| _d|jvrz||jd| jd<Wn(tyd| jvr| jd=Yn0| S)ae Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. rr)rrrr2rNrrr3css|]}|dVqdS)r2Nr"rLr"r"r#rPr&z&Image.remap_palette..ir&rrBrz;Lrr:)rrXrnrrr-rcr bytearrayrUrqrrrrr"r r[rindex) rrrrXrrrZ palette_modeZ palette_bytesZ new_positionsrNZ oldPositionZmapping_paletteZm_imr"r"r# remap_palettecsR           zImage.remap_paletter?ztuple[int, int, int, int])rresamplerdr+c Cst|d}|d|d|d}|d|d|d}||}||}tdt|d|tdt|d|t|jdt|d|t|jdt|d|fS)zExpands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. rFr1rr2r)_filters_supportr(rrIrmathceil) rrrrdZfilter_supportZscale_xZscale_yZ support_xZ support_yr"r"r# _get_safe_boxs zImage._get_safe_boxz(tuple[int, int] | list[int] | NumpyArrayz float | None)rrrd reducing_gapr+c Cs|dur&|jd}|rtjntj}n|tjtjtjtjtjtjfvrd|d}ddtjdftjdftjd ftjd ftjd ftjd ffD}|d d |ddd|d7}t ||dur|dkrd}t ||durd|j }t |}|j |kr|d|j kr| S|jdvr*tj}|jdvrr|tjkrr|ddd|j}||||}||jS||dur|tjkrt|d|d|d|pd} t|d|d|d|pd} | dks| dkr||tt||} | | f} t|jr&|j| | dntj|| | d}|d| d| |d| d| |d| d| |d| d| f}||j|||S)aH Returns a resized copy of this image. :param size: The requested size in pixels, as a tuple or array: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`Resampling.NEAREST`. If the image mode is "BGR;15", "BGR;16" or "BGR;24", then the default filter is :py:data:`Resampling.NEAREST`. Otherwise, the default filter is :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. NzBGR;Unknown resampling filter ().cSs$g|]}|dd|ddqSr (r)r"rMrur"r"r#ry sz Image.resize..Image.Resampling.NEARESTImage.Resampling.LANCZOSImage.Resampling.BILINEARImage.Resampling.BICUBICImage.Resampling.BOXImage.Resampling.HAMMING Use ,  or rGz#reducing_gap must be 1.0 or greaterrrxrrQrrr1rrr2)rd)rn startswithr?r@rDrBrErArCr,rrrrr[resizerrrrrzreducerjrr-) rrrrdrZbgrrfiltersr-Zfactor_xZfactor_yZ reduce_boxfactorr"r"r#rsl(   &   &&z Image.resizezint | tuple[int, int])rrdr+cCst|ttfs||f}|dur(d|j}|dkrF|d|jkrF|S|jdvr~|ddd|j}|||}||jS|| |j ||S)a! Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. NrrRrQrr) rrrrrrnr[rrrr-)rrrdr-r"r"r#r? s    z Image.reduceFz int | bool&float | tuple[float, ...] | str | None)anglerrscenter translate fillcolorr+cCs6|d}|sf|sf|dkr |S|dkr4|tjS|dvrf|sL|j|jkrf||dkr^tjntjS|j\}}|dur~d} n|} |dur|d|df}t | }t t |d t t |d d t t | d t t |d d g} d d d d ddd} | |d | d|d | d| \| d<| d<| d|d7<| d|d7<|rg} g} d|df||fd|ffD].\}}| ||| \}}| || |q~t t| t t| }t t| t t| }| || d|| d| \| d<| d<||}}|j||ftj| ||dS)a Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. gv@r)ZirNrr1rrz list[float]r)rrrCr+c Ss8|\}}}}}}||||||||||fSrr") rrrCrrrwr8rrr"r"r#r` szImage.rotate..transformrr4rH)r)r transposer0r7rpror6r8rrradiansrhcossinr*rr(floorrIr`r9r:)rrrrsrrrwrZ post_transrCr`xxyyrrZ transformed_xZ transformed_ynwZnhr"r"r#rotateb sX"    "  , z Image.rotateStrOrBytesPath | IO[bytes])rrparamsr+c Ks d}d}t|r(tjt|}d}n*|tjkrRz tjj}WntyPYn0|s~t |dr~t|j r~tjt|j }| | dd}||_ d|_ttj|d}t|tr|n|}|s*|tvrtz t|}Wn:ty(} z d|} t| | WYd } ~ n d } ~ 00|tvr>t|rRt|} n t|} d} |rtj| } |d drt|d }n t|d }nt t!t|}z| |||WnNt"y |r|#| rzt$|Wnt%yYn0Yn0|r|#d S) a Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), os.PathLike object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. rFTr1save_allr"rzunknown file extension: Nr*zr+bzw+b)&rrpathrealpathfspathsysstdoutbufferrr.r1rpopZ encoderinfoZ encoderconfigrsplitextlowerrr%r6rdrrrupperrbrcexistsrbuiltinsrrr rrremovePermissionError) rrrrrZopen_fprZ filename_extextrrZ save_handlercreatedr"r"r#r sh         z Image.save)framer+cCs|dkrd}t|dS)a0 Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. rzno more images in fileN)EOFError)rr$rr"r"r#r: sz Image.seek)titler+cCst||ddS)a Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **xdg-open**, **display**, **gm**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. )r&N)_show)rr&r"r"r#showP sz Image.showztuple[Image, ...]cCs4||jjdkr|fStt|j|jS)a Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. r)rr-rrrrrrrrr"r"r#rf s  z Image.splitz int | str)channelr+c Csr|t|tr`z||}Wn:ty^}z"d|d}t||WYd}~n d}~00||j|S)a@ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 zThe image has no channel ""N) rrrr}rrrr-rv)rr)rrr"r"r# getchannely s    zImage.getchannelcCsdS)z Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. rr"rr"r"r#r s z Image.tellrHr)rrrr+c stttj|ddfdd }|}|dur6dS|}d}|dur~dt|d|t|d|f}|dur~|d}j|krj||||d} | j_|_ jj _ d_ dS) an Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: Optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If omitted, it defaults to :py:data:`Resampling.BICUBIC`. (was :py:data:`Resampling.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None rorcsdddddd}\jkr2jkr2dSjjkrf|fddd n|fd dd fS) NrCallable[[int], float]r)numberkeyr+cSs ttt|t||ddS)Nr.r)r(rIrr r)r-r.r"r"r# round_aspect szDImage.thumbnail..preserve_aspect_ratio..round_aspectcst|Srrin)aspectrr"r# r&z@Image.thumbnail..preserve_aspect_ratio..r/cs|dkr dSt|Srr1r2)r4rr"r#r5 r&)rpro)r0Z provided_sizer)r4rrr#preserve_aspect_ratio s  z.Image.thumbnail..preserve_aspect_ratioNrr)rdr) rrrr rprrrr-rrnrr) rrrrr7Zpreserved_sizeZ final_sizerdresr-r"r6r# thumbnail s&-   zImage.thumbnailrz3Transform | ImageTransformHandler | SupportsGetDatazSequence[Any] | None)rrarrfillrr+c Cs|jdvrB|tjkrB|ddd|j|||||||jSt|tr^|j||||dSt|drt|\}}|durd}t |t |j||}|jdkr|j r|j |_ |j |_ |tjkr|D]"\} } || |tj| ||duqn|d ||||||du|S) ar Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size in pixels, as a 2-tuple: (width, height). :param method: The transformation method. This is one of :py:data:`Transform.EXTENT` (cut out a rectangular subregion), :py:data:`Transform.AFFINE` (affine transform), :py:data:`Transform.PERSPECTIVE` (perspective transform), :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or :py:data:`Transform.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result Implementations of :py:class:`~PIL.Image.ImageTransformHandler` for some of the :py:class:`Transform` methods are provided in :py:mod:`~PIL.ImageTransform`. It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.Transform.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. rQrr)rr:rNzmissing method datarr)rnr?r@r[r`rImageTransformHandlerr.rrrrrrr9r>_Image__transformerr=) rrrarrr:rrr-rdZquadr"r"r#r` s6;        zImage.transformr9zSequence[float])rdr0rarrr:r+c Cst|d|d}|d|d}|tjkr:|dd}nD|tjkr|\} } } } | | |} | | |}tj}| d| d|| f}n|tjkr|dd}n|tjkrr|dd}|dd}|dd}|dd}|\} } d|}d|}| |d| ||d| ||d|d|d| ||| |d| ||d| ||d|d|d| ||f}n d }t||tjtjtj fvr6|tj tj tj fvrtj d tj d tj d i}||d |d}n d|d}ddtjdftjdftj dffD}|dd |ddd|d7}t||||jdvrXtj}|j||j||||dS)Nr1rr2rr5r3rGzunknown transformation methodrrrrz) cannot be used.rrcSs$g|]}|dd|ddqSrr"rr"r"r#ry sz'Image.__transformer..rrrrrrrr)r9r:r;r<r=rr?r@rBrDrArCrEr,rrnr-r`)rrdr0rarrr:r rrkrlrmrnZxsZysrswseneZAsZAtrZunusablerr"r"r#Z __transformerP sp            ""  & zImage.__transformerr0)rar+cCs|||j|S)a Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`, :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`, :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`, :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. )rrr-r)rrar"r"r#r s zImage.transpose)distancer+cCs|||j|S)zj Randomly spread pixels in an image. :param distance: Distance to spread pixels. )rrr- effect_spread)rrAr"r"r#rB szImage.effect_spreadzImageQt.ImageQtcCs(ddlm}|jsd}t|||S)z#Returns a QImage copy of this imagerrYQt bindings are not installed)rrYqt_is_installedrtoqimagerrYrr"r"r#rF s  zImage.toqimageImageQt.QPixmapcCs(ddlm}|jsd}t|||S)z$Returns a QPixmap copy of this imagerrCrD)rrYrEr toqpixmaprGr"r"r#rI s  zImage.toqpixmap)NN)r)r0)r)N)N)rB)N)r)NN)NN)NN)rr)N)rGr)r)N)NNN)N)N)N)`rr r!rr__annotations__rZ!_close_exclusive_fp_after_loadingrpropertyr-setterrprorrnrrrrrrrrr r rrrrrrr$r r4r#rrArLrMr[rIrKrVr__copy__rfrerprtrur}rrrrrrrrrrrrr\rrrrrrrrr"rZrrrrr?r@rrrr(rr+rrDr9r`r<rrBrFrIr"r"r"r#rjs         5%$ S  '#.  "\A<:++Zo&ud\&d&V  c@s&eZdZdZejdddddZdS)rzb Used as a mixin by point transforms (for use with :py:meth:`~PIL.Image.Image.point`) rjrkcCsdSrr"rr"r"r#r szImagePointHandler.pointN)rr r!rabcabstractmethodrr"r"r"r#r src@s*eZdZdZejdddddddZdS) r;zi Used as a mixin by geometry transforms (for use with :py:meth:`~PIL.Image.Image.transform`) rrjr )rr0rr+cKsdSrr")rrr0rr"r"r#r` szImageTransformHandler.transformN)rr r!rrNrOr`r"r"r"r#r; sr;cCsttdS)z+Create grayscale wedge (for debugging only)r)rjrrZwedger"r"r"r#_wedge srP)rr+cCsZt|ttfsd}t|t|dkr2d}t||ddksJ|ddkrVd}t|dS)z Common check to enforce type and sanity check on size tuples :param size: Should be a 2 tuple of (width, height) :returns: None, or raises a ValueError zSize must be a list or tupler1z#Size must be a sequence of length 2rrzWidth and height must be >= 0N)rrrrrq)rrr"r"r# _check_size s rQrr)rnrcolorr+cCs|dvrt|dt||dur6tt||St|trXddlm }| ||}t}|dkrt|t t frt dd|Drtt td ft |}t|d kst|d krdd lm}||_|j |}|t|||S) a Creates a new image with the given mode and size. :param mode: The mode to use for the new image. See: :ref:`concept-modes`. :param size: A 2-tuple, containing (width, height) in pixels. :param color: What color to use for the image. Default is black. If given, this should be a single integer or floating point value for single-band modes, and a tuple for multi-band modes (one value per band). When creating RGB or HSV images, you can also use color strings as supported by the ImageColor module. If the color is None, the image is not initialised. :returns: An :py:class:`~PIL.Image.Image` object. rFr,Nrrrcss|]}t|tVqdSr)rrrLr"r"r#rP7 r&znew...r2r3r)rrQrjrrrrrrrrYrrallrrrqrXrr:)rnrrRrr-Z color_intsrXr"r"r#r s*        rrrr5)rnrrrrr+cGsrt|t||}|jdkrn|jdkrn|}t|dkrLt|dtrL|d}|dkr`|dkr`|}|||||S)a Creates a copy of an image memory from pixel data in a buffer. In its simplest form, this function takes three arguments (mode, size, and unpacked pixel data). You can also use any pixel decoder supported by PIL. For more information on available decoders, see the section :ref:`Writing Your Own File Codec `. Note that this function decodes pixel data only, not entire images. If you have an entire image in a string, wrap it in a :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load it. :param mode: The image mode. See: :ref:`concept-modes`. :param size: The image size. :param data: A byte buffer containing raw data for the given mode. :param decoder_name: What decoder to use. :param args: Additional parameters for the given decoder. :returns: An :py:class:`~PIL.Image.Image` object. rrrr")rQrrprorqrrr#)rnrrrrr-r7r"r"r#r#C s r#zbytes | SupportsArrayInterfacec Gst|t|dkr*t|dtr*|d}|dkr|dkrD|ddf}|dtvrt|d}|t|||d|}|dkrddl m }| d|j d|_ d|_|St|||||S) a Creates an image memory referencing pixel data in a byte buffer. This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data in the byte buffer, where possible. This means that changes to the original buffer object are reflected in this image). Not all modes can share memory; supported modes include "L", "RGBX", "RGBA", and "CMYK". Note that this function decodes pixel data only, not entire images. If you have an entire image file in a string, wrap it in a :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load it. The default parameters used for the "raw" decoder differs from that used for :py:func:`~PIL.Image.frombytes`. This is a bug, and will probably be fixed in a future release. The current release issues a warning if you do this; to disable the warning, you should provide the full set of parameters. See below for details. :param mode: The image mode. See: :ref:`concept-modes`. :param size: The image size. :param data: A bytes or other buffer object containing raw data for the given mode. :param decoder_name: What decoder to use. :param args: Additional parameters for the given decoder. For the default encoder ("raw"), it's recommended that you provide the full set of parameters:: frombuffer(mode, size, data, "raw", mode, 0, 1) :returns: An :py:class:`~PIL.Image.Image` object. .. versionadded:: 1.1.4 rrrr"rrrr)rQrqrr _MAPMODESrrrZ map_bufferrrXr-rrrr#)rnrrrrr-rXr"r"r# frombufferq s(    rUc@s"eZdZdZeddddZdS)SupportsArrayInterfacezC An object that has an ``__array_interface__`` dictionary. rrcCs tdSr)NotImplementedErrorrr"r"r#r sz*SupportsArrayInterface.__array_interface__N)rr r!rrKrr"r"r"r#rV srVr)objrnr+c Cs|j}|d}t|}|dd}|durzd|dd|df}Wn2tyx}zd}t||WYd}~n d}~00zt|\}} Wqty}z.|\} } d| d | }t||WYd}~qd}~00n|} |d vrd} n|d krd } nd } || krd|d| d}t||dkr*dn|d|df} |dur|t|drZ|}n"t|drp| }n d}t|t || |d| ddS)a  Creates an image memory from an object exporting the array interface (using the buffer protocol):: from PIL import Image import numpy as np a = np.zeros((5, 5)) im = Image.fromarray(a) If ``obj`` is not contiguous, then the ``tobytes`` method is called and :py:func:`~PIL.Image.frombuffer` is used. In the case of NumPy, be aware that Pillow modes do not always correspond to NumPy dtypes. Pillow modes only offer 1-bit pixels, 8-bit pixels, 32-bit signed integer pixels, and 32-bit floating point pixels. Pillow images can also be converted to arrays:: from PIL import Image import numpy as np im = Image.open("hopper.jpg") a = np.asarray(im) When converting Pillow images to arrays however, only pixel values are transferred. This means that P and PA mode images will lose their palette. :param obj: Object with array interface :param mode: Optional mode to use when reading ``obj``. Will be determined from type if ``None``. This will not be used to convert the data after reading, but will be used to change how the data is read:: from PIL import Image import numpy as np a = np.full((1, 1), 300) im = Image.fromarray(a, mode="L") im.getpixel((0, 0)) # 44 im = Image.fromarray(a, mode="RGB") im.getpixel((0, 0)) # (44, 1, 0) See: :ref:`concept-modes` for general information about modes. :returns: An image object. .. versionadded:: 1.1.6 rustridesNrRr1rszCannot handle this data typezCannot handle this data type: r)rxrr{rrzrr2r3zToo many dimensions: z > rrrr tostringz1'strides' requires either tobytes() or tostring()r) rrqrrr{_fromarray_typemaprr.r rZrU)rXrnr@rundimrYZtypekeyrrr=Z typekey_shapersZndmaxrr"r"r# fromarray sD/  "      r]zImageQt.QImagezImageFile.ImageFilecCs(ddlm}|jsd}t|||S)z-Creates an image instance from a QImage imagerrCrD)rrYrEr fromqimager-rYrr"r"r#r^ s  r^rHcCs(ddlm}|jsd}t|||S)z.Creates an image instance from a QPixmap imagerrCrD)rrYrEr fromqpixmapr_r"r"r#r` s  r`)rRz|b1)rxz1;8)rR|u1)rr)rRz|i1)r{zI;8)rRzu2)r{r})rRzi2)r{zI;16BS)rRzu4)r{zI;32B)rRzi4)r{zI;32BS)rRzf4)rzzF;32BF)rRzf8)rzzF;64BF))rrr1ra)rr))rrr2ra)rr))rrr3ra)rrrRi4)r{r{Zf4)rzrzcCsxtdur dStd|dtd|d}|dtkrRd|ddtd}t||tkrttd|dtdtdS)Nrrr1z Image size (z pixels) exceeds limit of z0 pixels, could be decompression bomb DOS attack.)r(r(r$rWrXr)rZpixelsrr"r"r#rj@ s rjrrz Literal['r']z"list[str] | tuple[str, ...] | None)rrnformatsr+c s|dkr dt|}t|nt|tjr8d}t||durFt}nt|ttfs`d}t|dd}t |rt j t |}|rt|d}d nttt|}z|d Wn*ttjfyt|}d Yn0|d }tgd d ddddfdd }|||||}|durb|turbttrb||||tfdd|D}|rr|_|Sr|D]}t|qd|r|n|}t|dS)a Opens and identifies the given image file. This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the :py:meth:`~PIL.Image.Image.load` method). See :py:func:`~PIL.Image.new`. See :ref:`file-handling`. :param fp: A filename (string), os.PathLike object or a file object. The file object must implement ``file.read``, ``file.seek``, and ``file.tell`` methods, and be opened in binary mode. The file object will also seek to zero before reading. :param mode: The mode. If given, this argument must be "r". :param formats: A list or tuple of formats to attempt to load the file in. This can be used to restrict the set of formats checked. Pass ``None`` to try all supported formats. You can print the set of available formats by running ``python3 -m PIL`` or using the :py:func:`PIL.features.pilinfo` function. :returns: An :py:class:`~PIL.Image.Image` object. :exception FileNotFoundError: If the file cannot be found. :exception PIL.UnidentifiedImageError: If the image cannot be opened and identified. :exception ValueError: If the ``mode`` is not "r", or if a ``StringIO`` instance is used for ``fp``. :exception TypeError: If ``formats`` is not ``None``, a list or a tuple. rcz bad mode zKStringIO cannot be used to open an image. Binary data must be used instead.Nzformats must be a list or tupleFrrbTr IO[bytes]z str | bytesr%zlist[str] | tuple[str, ...]zImageFile.ImageFile | None)rrprefixrdr+c s|D]}|}|tvrtz`t|\}}| p8||}t|trP|n,|r||d|||}t|j|WSWqt t t t j fy} z&tr|dt| WYd} ~ qd} ~ 0tyr|Yq0qdS)Nrz opening failed. )rr`rrrr*rrjr SyntaxError IndexErrorr{structerrorr& BaseExceptionr) rrrhrdrNfactoryacceptrr-r) exclusive_fpwarning_messagesr"r# _open_core s,      *  zopen.._open_corec3s|]}|vr|VqdSrr")rMr)checked_formatsr"r#rP r&zopen..zcannot identify image file %r) reprrrrStringIOr_rrr{rrrrrrrrr r%rrUnsupportedOperationrrrrrrrrWrXr) rrnrdrrrhrrr-messager")rsrprqr#rU s`"     r)im1im2r+cCs&|||t|j|jS)z Alpha composite im2 over im1. :param im1: The first image. Must have mode RGBA. :param im2: The second image. Must have mode RGBA, and the same size as the first image. :returns: An :py:class:`~PIL.Image.Image` object. )rrrrr-)rxryr"r"r#r s rr)rxryrr+cCs(|||t|j|j|S)a Creates a new image by interpolating between two input images, using a constant alpha:: out = image1 * (1.0 - alpha) + image2 * alpha :param im1: The first image. :param im2: The second image. Must have the same mode and size as the first image. :param alpha: The interpolation alpha factor. If alpha is 0.0, a copy of the first image is returned. If alpha is 1.0, a copy of the second image is returned. There are no restrictions on the alpha value. If necessary, the result is clipped to fit into the allowed output range. :returns: An :py:class:`~PIL.Image.Image` object. )rrrblendr-)rxryrr"r"r#rz srz)image1image2rr+cCs|}||d||S)af Create composite image by blending images using a transparency mask. :param image1: The first image. :param image2: The second image. Must have the same mode and size as the first image. :param mask: A mask image. This image can have mode "1", "L", or "RGBA", and must have the same size as the other two images. N)rr)r{r|rr0r"r"r# composite s r}r,)r0rr+cGs||dS)a Applies the function (which should take one argument) to each pixel in the given image. If the image has more than one band, the same function is applied to each band. Note that the function is evaluated once for each possible pixel value, so you cannot use random components or other generators. :param image: The input image. :param function: A function object, taking one integer argument. :returns: An :py:class:`~PIL.Image.Image` object. r)r)r0rr"r"r#evals r~zSequence[Image])rnrrr+cCst|t|ksd|vr$d}t||ddD]:}|jt|krNd}t||j|djkr0d}t|q0|D] }|qp|dtj |gdd |DRS) am Merge a set of single band images into a new multiband image. :param mode: The mode to use for the output image. See: :ref:`concept-modes`. :param bands: A sequence containing one single-band image for each band in the output image. All bands must have the same size. :returns: An :py:class:`~PIL.Image.Image` object. *zwrong number of bandsrNz mode mismatchrz size mismatchcSsg|] }|jqSr")r-)rMrr"r"r#ry6r&zmerge..) rrqrrnrrrrrr|)rnrrrrr"r"r#r|s   r|zSCallable[[IO[bytes], str | bytes], ImageFile.ImageFile] | type[ImageFile.ImageFile]z$Callable[[bytes], bool | str] | None)r rnror+cCs*|}|tvrt|||ft|<dS)a1 Register an image file plugin. This function should not be used in application code. :param id: An image format identifier. :param factory: An image file factory method. :param accept: An optional function that can be used to quickly reject images having another format. N)rr_r*r`)r rnror"r"r# register_open=s r)r mimetyper+cCs|t|<dS)a Registers an image MIME type by populating ``Image.MIME``. This function should not be used in application code. ``Image.MIME`` provides a mapping from image format identifiers to mime formats, but :py:meth:`~PIL.ImageFile.ImageFile.get_format_mimetype` can provide a different result for specific images. :param id: An image format identifier. :param mimetype: The image MIME type for this format. N)rar)r rr"r"r# register_mimeTs rz/Callable[[Image, IO[bytes], str | bytes], None])r driverr+cCs|t|<dS)z Registers an image save function. This function should not be used in application code. :param id: An image format identifier. :param driver: A function to save images in this format. N)rbrr rr"r"r# register_savecs rcCs|t|<dS)z Registers an image function to save all the frames of a multiframe format. This function should not be used in application code. :param id: An image format identifier. :param driver: A function to save images in this format. N)rcrrr"r"r#register_save_allps r)r  extensionr+cCs|t|<dS)z Registers an image extension. This function should not be used in application code. :param id: An image format identifier. :param extension: An extension used for this format. N)rrdr)r rr"r"r#register_extension~sr)r  extensionsr+cCs|D]}t||qdS)z Registers image extensions. This function should not be used in application code. :param id: An image format identifier. :param extensions: A list of extensions used for this format. N)r)r rrr"r"r#register_extensionssrcCs ttS)za Returns a dictionary containing all file extensions belonging to registered plugins )rrdr"r"r"r#registered_extensionssrztype[ImageFile.PyDecoder])r1rr+cCs |t|<dS)z Registers an image decoder. This function should not be used in application code. :param name: The name of the decoder :param decoder: An ImageFile.PyDecoder object .. versionadded:: 4.1.0 N)re)r1rr"r"r#register_decoders rztype[ImageFile.PyEncoder])r1rr+cCs |t|<dS)z Registers an image encoder. This function should not be used in application code. :param name: The name of the encoder :param encoder: An ImageFile.PyEncoder object .. versionadded:: 4.1.0 N)rf)r1rr"r"r#register_encoders r)r0rr+cKs"ddlm}|j|fi|dS)Nr) ImageShow)rrr()r0rrr"r"r#r's r'rg)rextentqualityr+cCstt|||S)a Generate a Mandelbrot set covering the given extent. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param extent: The extent to cover, as a 4-tuple: (x0, y0, x1, y1). :param quality: Quality. )rjrreffect_mandelbrot)rrrr"r"r#rs r)rsigmar+cCstt||S)z Generate Gaussian noise centered around 128. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param sigma: Standard deviation of noise. )rjrr effect_noise)rrr"r"r#rsrcCstt|S)zl Generate 256x256 linear gradient from black to white, top to bottom. :param mode: Input mode. )rjrrlinear_gradientrr"r"r#rsrcCstt|S)zm Generate 256x256 radial gradient from black to white, centre to edge. :param mode: Input mode. )rjrrradial_gradientrr"r"r#rsrzdict[str, str] | None)envr+c Cs|dur |ntj}dtjfdtjfdtjffD]\}}||vr@q.||}d}dD](\}}||rT|}|dt| }qTzt ||}Wn&t yt |dYq.Yn0z ||Wq.t y} z t |d| WYd} ~ q.d} ~ 00q.dS)NZPILLOW_ALIGNMENTZPILLOW_BLOCK_SIZEZPILLOW_BLOCKS_MAXr))ri)rtiz is not intz: ) renvironrZ set_alignmentZset_block_sizeZset_blocks_maxrrrqrrrWrX) rZenv_dictvar_namerLvarZunitsZpostfixmulZvar_intrr"r"r#_apply_env_variabless,       rc@sDeZdZUdZdZded<dZdZdddd Zd d d d d Z dddddZ d@ddddddZ ddddZ dddddZ dAddddd d!Zddd"d#ZdBddd%d&d'Zddd(d)d*Zddd+d,Zd-dd.d/Zddd0d1Zdd d(d2d3Zd4d5d(d6d7Zdd dd8d9d:Zddd(d;d<Zd=dd>d?ZdS)Cra This class provides read and write access to EXIF image data:: from PIL import Image im = Image.open("exif.png") exif = im.getexif() # Returns an instance of this class Information can be read and written, iterated over or deleted:: print(exif[274]) # 1 exif[274] = 2 for k, v in exif.items(): print("Tag", k, "Value", v) # Tag 274 Value 2 del exif[274] To access information beyond IFD0, :py:meth:`~PIL.Image.Exif.get_ifd` returns a dictionary:: from PIL import ExifTags im = Image.open("exif_gps.jpg") exif = im.getexif() gps_ifd = exif.get_ifd(ExifTags.IFD.GPSInfo) print(gps_ifd) Other IFDs include ``ExifTags.IFD.Exif``, ``ExifTags.IFD.Makernote``, ``ExifTags.IFD.Interop`` and ``ExifTags.IFD.IFD1``. :py:mod:`~PIL.ExifTags` also has enum classes to provide names for data:: print(exif[ExifTags.Base.Software]) # PIL print(gps_ifd[ExifTags.GPS.GPSDateStamp]) # 1999:99:99 99:99:99 NrrFrrcCs"i|_i|_i|_d|_d|_dSr)_data _hidden_data_ifdsr _loaded_exifrr"r"r#rEs z Exif.__init__r )rJr+cCs<z$t|dkr"t|tr"|dWSWnty6Yn0|Sr)rqrrr)rrJr"r"r#_fixupLs  z Exif._fixupzdict[int, Any])src_dictr+csfdd|DS)Ncsi|]\}}||qSr")rrrr"r#rWr&z$Exif._fixup_dict..)r)rrr"rr# _fixup_dictTszExif._fixup_dictrr'zdict[int, Any] | None)rgroupr+c Csdz|j|Wnttfy(YdS0ddlm}|j|j|d}||j| t |SdS)Nrr)r) rrrr{rrZImageFileDirectory_v2headrrdict)rrrrZrr"r"r#rYs  zExif._get_ifd_dictr%cCsn|jr dnd}|jdkr.d|dtd}nd|td}|jrj||jdkrXtdntd7}|d7}|S) N+*rhsIIrr=sMMs)rrrr)rrrr"r"r# _get_headis zExif._get_head)rr+cCs||jkrdS||_|j|j|j|rN|drN|dd}q2|s\d|_dSt||_ |j d|_ ddl m }||j |_|jj|_|j |jj|j|j dS)NExifr5r=rr)rrclearrrrrrrrrrrrZrrrrrr)rrrZr"r"r#rts$       z Exif.loadrg)rrr+cCsd|_|j|j|jddlm}||_|durJ||_ n|j d|_ | |j |_ |j durz|j j|_ |dur|j j}|j|j||j |jdS)Nrrr=)rrrrrrrZrrrrrrrrrrrr)rrrrZr"r"r#rs"         zExif.load_from_fpcCsjt|}tjj|vr:||tjjtjj}|r:||tjj|vrf||tjjtjj|tjj<|Sr)rrrrrupdateGPSInfo)rZ merged_dictrr"r"r#_get_merged_dicts    zExif._get_merged_dictr=)rr+cCsddlm}|}|j|d}|D]\}}|tjjtjjfvrt |t s| |}|tjjkrtjj |vrt |tjj t s| }| tjj |tjj <|||<q(d|||S)Nrr)Zifhr)rrZrrrrrrrrrrInteroprr )rrrZrrrrJr"r"r#r s*      z Exif.tobytesrc Cs||jvr|tjjkrR|jdurN|jjdkrN||jj}|durN||j|<nv|tjjtjjfvr|j || |}|dur|||}|dur||j|<n$|tjj tjj fvrtjj|jvr| tjj|jtjj|}|tjj krddlm}|dddkr^t|d}||d}i}tdtd|dddD]} td|| d d| dd d\} } } } z|j| \}}WntyYqLYn0| |}|d krtd | \}||d ||d } n | d|} t| |kr&td |d t| d| qL| s0qL||| d|| <qLt|||j|<q| ddkri}tdtd|dddD]} td|| d d| dd d\} } } } | dkrtd| \}|j|d|jd i}|jd t|jd |d<|jd |jd |d<|jd |jd }|jtjd}|||dd|d<|jd |jd|d<d|i}q||j|<n |||}|dur||j|<|j |i}|tjjkr|j rdd|!D}|S)Nrr)rr=sFUJIFILMzHz>HHL4siz>LZModelIDZ TimeStampZInternalSerialNumberZParallaxZCategorycSs*i|]"\}}|tjjtjjfvr||qSr")rrr Makernoterr"r"r#r3sz Exif.get_ifd..)"rrrrrrrrrrrrrrrZrrrUrkunpackZ_load_dispatchrrqrWrXrrrrrrFLOAT setdefaultr)rrrrZtag_datarrZifd_dataZ makernoterNZifd_tagtypcountrZ unit_sizehandlerrZ camerainfoZparallaxr"r"r#rs      "     $              z Exif.get_ifdcCs6tjjtjjfD] }||vr|||j|<||=qdSr)rrrrrrrr"r"r# hide_offsets:szExif.hide_offsetsrcCs(|jdur|jD] }||qt|jSr)rrrrr"r"r#__str__@s   z Exif.__str__cCs(t|j}|jdur ||jt|Sr)setrrrrqrkeysr"r"r#__len__Hs   z Exif.__len__cCsF|jdur<||jvr<||jvr<||j||j|<|j|=|j|Sr)rrrrr"r"r# __getitem__NszExif.__getitem__rr%cCs||jvp|jduo||jvSr)rrrr"r"r# __contains__TszExif.__contains__)rrJr+cCs*|jdur||jvr|j|=||j|<dSrrr)rrrJr"r"r# __setitem__WszExif.__setitem__cCs*|jdur||jvr|j|=n|j|=dSrrrr"r"r# __delitem__\s zExif.__delitem__z Iterator[int]cCs(t|j}|jdur ||jt|Sr)rrrriterrr"r"r#__iter__bs   z Exif.__iter__)N)N)r=)rr r!rrrJrrrrrrrrrrr rrrrrrrrrr"r"r"r#rs. !  lr)r")r")r)r)r)N)rcN)N)N) __future__rrNatexitrrloggingrrrrkrrrWcollections.abcrrrrenumrtypesrtypingr r r r r rrrrrrrr_binaryrrrZ _deprecaterZ_utilrrrJZ defusedxmlrr getLoggerrrRuntimeWarningrrr$r&rr(r)rrrrGrrrrXr/r0r9r?rArBrCrDrErrIrLrOmodulesmoduleitemsetattrr1rJr.rSZFILTEREDZ HUFFMAN_ONLYZRLEZFIXEDmmapZxml.etree.ElementTreerTZIPython.lib.prettyrUrVrWrXrYrZZ_typingr[r\r]r^r_r`rarbrcrdrerf byteorderZ_ENDIANrwZMODESrTrrrrrrrrrrrrrjrr;rPrQr#rUrVr]r^r`r[rjrrrzr}r~r|rrrrrrrrrr'rrrrrregister clear_cacheZ _ExifBaserr"r"r"r#s                             - * R 82> X  %