3 }\ܠY@sddlmZmZmZddlmZddlZddlZddlZy ddl Z Wn e k rdddl Z e Z YnXddlm Z m Z ddlmZmZddlmZmZmZddlZddlZddlZddlZddlZddlZyddlmZmZWn&e k rddlmZmZYnXesteje Z!Gd d d e"Z#Gd d d e$Z%Gd dde&Z'e(dȃZ)y:ddlm*Z+ee,e+ddkre de,e+ddefWne k r.Z-ze'Z+e.e-j/drej0de"nXe.e-j/drej0e.e-e"n6de.e-krej0de"nde.e-krej0de"WYddZ-[-XnXe1edZ2y ddl3Z3Wne k r`dZ3YnXyddl4m5Z5dZ6WnFe k ryddl7m5Z5dZ6Wne k rdZ6YnXYnXd d!Z8dZ9dZ:dZ;d"Zd#Z?d$Z@dZAdZBd"ZCdZDdZEdZFZ9dZGd"ZHZId#ZJdZKZLdZMZNdZFZ9dZOd"ZPdZQdZRdZSdZTdZUd"ZVdZWdZXdZYd"ZZe1e+d%re+j[Z[e+j\Z\e+j]Z]e+j^Z^e+j_Z_gZ`iZaiZbiZciZdiZeiZfiZgddddddddddddd: Zhejid;krd|b1|u1i4Zf4u2i2u4i4)r*r)LAr+r,r-r.r=r>r?r@rArBzI;16zI;16BzI;16LzI;16SzI;16BSzI;16LSzI;32zI;32BzI;32LzI;32SzI;32BSzI;32LScCsLt|j\}}|dkr.|jd|jdf|fS|jd|jd|f|fSdS)Nrr) _MODE_CONVmodesize)r!typextrarrr_conv_type_shape-srWr=r>r?I;16I;16LI;16BcCs tj|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. )rgetmodeZbasemode)rSrrr getmodebase<s r\cCs tj|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. )rr[Zbasetype)rSrrr getmodetypeIs r]cCs tj|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. )rr[bands)rSrrrgetmodebandnamesUs r_cCsttj|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. )lenrr[r^)rSrrr getmodebandsdsrac+Cstdkr dSyddlm}|s"tWntk r8YnXyddlm}|sPtWntk rfYnXyddlm}|s~tWntk rYnXyddlm}|stWntk rYnXyddlm}|stWntk rYnXdadS)z-Explicitly load standard file format drivers.rN)BmpImagePlugin)GifImagePlugin)JpegImagePlugin)PpmImagePlugin)PngImagePlugin) _initializedrbAssertionErrorrrcrdrerf)rbrcrdrerfrrrpreinitus8          rjcCstdkr dSxdtD]\}y&tjd|td|ttgWqtk rl}ztjd||WYdd}~XqXqWtszt rdadSdS)zw Explicitly initializes the Python Imaging Library. This function loads all available file format drivers. r%rz Importing %szPIL.%szImage: failed to import %s: %sNr) rgrloggerdebug __import__globalslocalsrOPENSAVE)Zpluginerrrinits  $rscCs|dkrf}nt|ts|f}yt|}||f||Stk rLYnXy tt|d}||f||Stk rtd|YnXdS)N_decoderzdecoder %s not available) isinstancetupleDECODERSKeyErrorgetattrcoreAttributeErrorIOError)rS decoder_nameargsrVdecoderrrr _getdecoders rcCs|dkrf}nt|ts|f}yt|}||f||Stk rLYnXy tt|d}||f||Stk rtd|YnXdS)N_encoderzencoder %s not available)rurvENCODERSrxryrzr{r|)rS encoder_namer~rVencoderrrr _getencoders rcCst|tr|St|S)N)ru_E)valuerrrcoerce_esrc@s$eZdZddZddZddZdS)rcCs ||_dS)N)data)rrrrr__init__sz _E.__init__cCst|jdt|jfS)N__add__)rrr)rotherrrrrsz _E.__add__cCst|jdt|jfS)N__mul__)rrr)rrrrrrsz _E.__mul__N)rrrrrrrrrrrsrcCsdg}|t|j}yV|\}}}||krD|dkrDt|tjrD|dfS||krh|dkrht|tjrhd|fSWntk r~YnXyL|\\}}}}}||kr|dkrt|tjr|dkrt|tjr||fSWntk rYnXtddS)Nstubrgrg?zillegal expression)rrrunumbersNumber TypeError ValueError)exprrrabcdrrrrr_getscaleoffsets$   rc@seZdZdZdZdZdZddZeddZ edd Z ed d Z d d Z ddZ ddZddZejjdkrxddZddZddZdddZddZdd Zd!d"Zd#d$Zed%d&Zd'd(Zd)d*Zdd,d-Zd.d/Zdd1d2Z dd3d4Z!d5d6Z"d7d8Z#d9d:Z$ddde%d;fdddpdqZ?ddsdtZ@dudvZAddwdxZBeCdfdydzZDeCd>dddfd{d|ZEdd}d~ZFddZGdddZHddZIddZJddZKeLfddZMdeCd?dfddZNeCd?fddZOddZPddZQddZRddZSdS)ImageaD 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` NTcCs4d|_d|_d|_d|_i|_t|_d|_d|_dS)Nrhr)rr) r!rS_sizepaletteinfoNORMALcategoryreadonlypyaccess)rrrrrszImage.__init__cCs |jdS)Nr)rT)rrrrwidth&sz Image.widthcCs |jdS)Nr)rT)rrrrheight*sz Image.heightcCs|jS)N)r)rrrrrT.sz Image.sizecCs`t}||_|j|_|j|_|jdkrP|jr:|jj|_nddlm}|j|_|j j|_ |S)Nr-PAr) ImagePalette)r-r) rr!rSrTrrcopyrhrr)rr!newrrrr_new2s    z Image._newcCs|S)Nr)rrrr __enter__AszImage.__enter__cGsBt|dr8t|ddr8t|dr(|j|jr8|jjd|_dS)Nfp _exclusive_fpF _close__fp)r"ryrrclose)rr~rrr__exit__Ds   zImage.__exit__cCszy&t|dr|j|jjd|_Wn.tk rT}ztjd|WYdd}~XnXt|ddrhd|_t t 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 only required to close images that 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: %smapzOperation on closed image) r"rrr Exceptionrkrlryrr rr!)rmsgrrrrLs     z Image.closercCs |jdS)N)r)rrrr__del__isz Image.__del__cCs$|j|jj|_d|_d|_dS)Nr)loadr!rrr)rrrr_copyls z Image._copycCs|jr|jn|jdS)N)rrr)rrrr_ensure_mutablers zImage._ensure_mutablecKsddl}d}|rd|}|s6|j|\}}tj|n|}|j|sL||}|j| sb|dkrp|jj|n|j||f||S)Nrrh.ZPPM) tempfilemkstemposrendswithrr!Zsave_ppmsave)rfileformatoptionsrsuffixffilenamerrr_dumpxs  z Image._dumpcCsh|j|jkof|j|jkof|j|jkof|j|jkof|j|jkof|j|jkof|j|jkof|j|jkS)N) __class__rSrTrrr getpalettetobytes)rrrrr__eq__s      z Image.__eq__cCs||k}| S)Nr)rreqrrr__ne__sz Image.__ne__cCs.d|jj|jj|j|jd|jdt|fS)Nz(<%s.%s image mode=%s size=%dx%d at 0x%X>rr)rrrrSrTr)rrrr__repr__s zImage.__repr__cCstj}|j|d|jS)z[ iPython display hook support :returns: png version of the image as bytes ZPNG)ioBytesIOrgetvalue)rrrrr _repr_png_s zImage._repr_png_cCsTi}t|\}}||d<||d<d|d<|jdkrD|jdd|d<n |j|d<|S) Nshapetypestrrversionr*rawr)r)rWrSr)rrrrrrr__array_interface__s   zImage.__array_interface__cCs|j|j|j|j|jgS)N)rrSrTrr)rrrr __getstate__s zImage.__getstate__cCsbtj|g|_|\}}}}}||_||_||_tj|||_|dkrT|rT|j ||j |dS)Nr)r-)r)r-) rrZtilerrSrrzrr! putpalette frombytes)rstaterrSrTrrrrr __setstate__s   zImage.__setstate__rc Gst|dkr"t|dtr"|d}|dkr8|fkr8|j}|jt|j||}|j|jtd|j dd}g}x$|j |\}}}|j ||rtPqtW|dkrt d|dj |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. :param args: Extra arguments to the encoder. :rtype: A bytes object. rrrirzencoder error %d in tobytes)r`rurvrSrrsetimager!maxrTencodeappend RuntimeErrorjoin) rrr~rrbufsizerlsrrrrrs"   z Image.tobytescOs tddS)Nz;tostring() has been removed. Please call tobytes() instead.)NotImplementedError)rr~kwrrrtostringszImage.tostringimagecCsj|j|jdkrtd|jd}djd||jdfjdd||jd fjdd |jd|d gS) 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" r*z not a bitmapZxbmrz#define %s_width %d rasciiz#define %s_height %d rzstatic char %s_bits[] = { s};)rrSrrrrTr)rnamerrrrtobitmaps   zImage.tobitmapcGst|dkr"t|dtr"|d}|dkr8|fkr8|j}t|j||}|j|j|j|}|ddkrptd|ddkrtddS)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. rrrznot enough image datazcannot decode image dataN) r`rurvrSrrr!decoder)rrr}r~rrrrrrs     zImage.frombytescOs tddS)Nz?fromstring() has been removed. Please call frombytes() instead.)r)rr~rrrr fromstring0szImage.fromstringcCs|jr|jr|jjr|jj|jjd|j_d|j_d|j_d|jkrt|jdt rn|jj |jddn|jj |jdd|j_|jrt rt r|jr|jSddlm}|j||j|_|jr|jS|jj|jSdS)a 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: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` rr.N transparencyr>r)PyAccess)r!rZdirtyrgetdatarSrawmoderruintputpalettealphaputpalettealphascffiUSE_CFFI_ACCESSrrhrrrZ pixel_access)rrrrrr4s&  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)rrrrverifyZs z Image.verifyc)sD|j| r,|jdkr,|jr(|jj}nd}| sB||jkrJ rJ|jS|jjddk }r|dkrntd|jj|}|j |}|r|jj dkr|jddd |dkrn0t |dkrt fd d t d t D|jd<|S|dkr|jd kr|j|Sd} d} |r|jdkrd|d krd|j |jj||jd} | jd=| S|jdkrB|dkrB|jd} t| trtjd!d} ntj tj|jd"} |jdkr | j|jt| t r y| jj| } Wntk rtdYnX| jd#| |d$kr,| j|} n | jd} | jd%} nb|jdkr|d kr|jd} d} t| tr|jj| n$t| tr|jj| d ntd&|dkrL|t krL|jj|}|j |}ddl!m"}|j#d|jj$d|_| r|jd=| dk rHy|jj| |jd<Wn(tk rF|jd=tjd'YnX|S|dkrZt%}y|jj||}WnXtk ry"|jjt&|j}|j||}Wnt'k rtdYnXYnX|j |} | r| jd=| dk r@| jdkr6y| jj| | jd<Wn(tk r2| jd=tjd(YnXn | | 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. The current version supports all possible conversions between "L", "RGB" and "CMYK." The **matrix** argument only supports "L" and "RGB". When translating a color image to greyscale (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 greyscale ("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 128 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. :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 NONE or 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 WEB or ADAPTIVE. :param colors: Number of colors to use for the ADAPTIVE palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. r-r.rNr)zillegal conversionrcSsP|d|d|d|d|d|d|dd}tdtdt|S)Nrrr%rg?)rminr)mvrrrconvert_transparencys<z+Image.convert..convert_transparencycs*g|]"}|d|ddqS)rr).0i)rmatrixrrr sz!Image.convert..rr>Fr*r+z"Palette images with Transparency z( expressed in bytes should be converted zto RGBA imagesTrz2Couldn't allocate a palette color for transparencyzTransparency for P mode shouldz be bytes or int)rz Couldn't allocate palette entry zfor transparency)r)r.)r*r)r+r.)r)r.r-)r)r.r-zJPalette images with Transparency expressed in bytes should be converted zXPalette images with Transparency expressed in bytes should be converted to RGBA images)rr)rr)r)r.)rrz.Transparency for P mode should be bytes or intz0Couldn't allocate palette entry for transparencyz0Couldn't allocate palette entry for transparency)(rrSrrrgetrr!Zconvert_matrixrr^r`rvrangequantizeZconvert_transparentrubyteswarningswarnrrzrrgetcolorrputpixelconvertgetpixelrrrADAPTIVErhrrrFLOYDSTEINBERGr\rx)rrSrditherrcolorsZhas_transparencyr!rZtrnsZ delete_trnsZnew_imr#Ztrns_imrr)rrrrres+                               z Image.convertrrc Cs|j|dkr"d}|jdkr"d}|jdkr<|dkrr%rz:Fast Octree (method == 2) and libimagequant (method == 3) z5are the only valid methods for quantizing RGBA imagesr-zbad mode for palette imager.r)z7only RGB or L mode images can be quantized to a paletter)r)r%rzoFast Octree (method == 2) and libimagequant (method == 3) are the only valid methods for quantizing RGBA images) rrSrr!rrrrhrZgetpalettemoderr) rr methodZkmeansrr r!rrSrrrrs.     zImage.quantizecCs|j|j|jjS)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!r)rrrrrSsz Image.copycCs,|dkr|jS|j|j|j|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. N)rrr_cropr!)rboxrrrcrop`s z Image.cropcCsJtttt|\}}}}t||t||f}t||j||||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_checkr)rr!rx0y0x1y1Zabsolute_valuesrrrr ss z Image._cropcCsdS)a 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 greyscale while loading it, or to extract a 128x192 version from a PCD file. 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 PCD images. :param mode: The requested mode. :param size: The requested size. Nr)rrSrTrrrdraftsz Image.draftcCs*|dkr |}|j|j|jj||dS)Nr)rrr!expand)rZxmarginZymarginrrr_expandsz Image._expandcCsddlm}|jt|tr$|}t|ds6tdt||j}|jj dksR|rd|j |j |jSg}x2t |jj D]"}|j |j |j |jj|qvWt|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) ImageFilterfilterz-filter argument should be ImageFilter.Filter zinstance or classz>filter argument should be ImageFilter.Filter instance or class)rhrrrurr"rZMultibandFilterr!r^rrrrgetbandmergerS)rrrZ multibandimsrrrrrs    "z Image.filtercCstj|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 )rr[rSr^)rrrrgetbandsszImage.getbandscCs|j|jjS)aQ Calculates the bounding box of the non-zero regions in the image. :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)rrrrr s z Image.getbboxcCsl|j|jdkr`|jj}g}x*tdD]}||r*|j|||fq*Wt||kr\dS|S|jj|S)a Returns a list of colors used in this image. :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. r*r)r-rN)r*r)r-)rrSr! histogramrrr` getcolors)rZ maxcolorshoutrrrrr"s    zImage.getcolorscCs"|j|dk r|jj|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!r)rbandrrrrs z Image.getdatacCsV|j|jjdkrLg}x*t|jjD]}|j|jj|jq&Wt|S|jjS)a& Gets the 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. r)rr!r^rrr getextremarv)rextremarrrrr&s  zImage.getextremacCs$t}d|jkr |j|jd|S)Nexif)Exifrr)rr(rrrgetexifs z Image.getexifcCs|j|jjS)zr Returns a capsule that points to the internal image memory. :returns: A capsule object. )rr!ptr)rrrrgetimsz Image.getimc CsL|jy*trt|jjSdd|jjDSWntk rFdSXdS)z Returns the image palette as a list. :returns: A list of color values [r, g, b, ...], or None if the image has no palette. cSsg|] }t|qSr)r )rrrrrr1sz$Image.getpalette..N)rrlistr!rr)rrrrr$szImage.getpalettecCs&|j|jr|jj|S|jj|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. )rrrr!)rxyrrrr5s  zImage.getpixelcCs2|j|jj\}}dd|Ddd|DfS)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. cSsg|] }t|qSr)r )rrrrrrNsz'Image.getprojection..)rr! getprojection)rxyrrrr/DszImage.getprojectioncCsT|j|r$|j|jjd|jS|jdkrJ|dkr>|j}|jj|S|jjS)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. 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 greyscale ("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 greyscale image ("L"). :param mask: An optional mask. :returns: A list containing pixel counts. rr+r,N)rr)r+r,)rr!r!rSr&)rmaskr'rrrr!Ps  zImage.histogramcCs tddS)NzCoffset() has been removed. Please call ImageChops.offset() instead.)r)rZxoffsetZyoffsetrrroffsetmsz Image.offsetcCst|r|dkr|}d}|dkr$d }t|dkr|t|r@|j}nt|rP|j}ntd||d|d|d|df7}t|rddlm}|j||j}nBt|r|j |j|jkr|jdks|jd kr|j |j}|j }|j |r |j |j j |||j n|j 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" or "RGBA" images (in the latter case, 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 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. Nrr%z,cannot determine region size; use 4-item boxr) ImageColorr.r>RGBa)rr)r>r5)r$r`rTrr rhr4rrSrrr!rpaste)rr!rr2rTr4rrrr6qs6( $   z Image.pastecCst|ttfstdt|ttfs,tdt|d kr@tdt|dksTtdt|dkrhtdt|dkr|td t|dkr||j}|d |jkr|}n |j|}||d|j|d |j f}|d|jkr|}n |j|}t ||}|j ||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 tuplezDestination must be a tupler%rzSource must be a 2 or 4-tuplezDestination must be a 2-tuplerzSource must be non-negativez Destination must be non-negativerN)r%r)rr)rr) rur-rvrr`rrTrrralpha_compositer6)rr!destsourceoverlayrZ backgroundresultrrrr7s.          zImage.alpha_compositecs|jttrj|Strl|jdkrNt\}}|j|jj ||Sfddt dD|jj |jdkr~t d|j|jj|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. :param mode: Output mode (default is same as input). In the current version, 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+I;16r,csg|] }|qSrr)rr)lutrrrszImage.point..rz+point operation not supported for this mode)r+r<r,) rruImagePointHandlerpointcallablerSrrr!Zpoint_transformrr^r)rr=rSscaler3r)r=rr?s     z Image.pointcCsD|j|jd krylt|jd}y|jj|Wn8ttfk rj|jj|}|jd kr`t||_YnXd|_|jj|_Wn t tfk rtdYnX|jd krd}nd}t |r|jdkrtd|j |jd kr0|jd }n@y|jj ||Wn(ttfk r*t d |j|}YnXdS|jj|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 or other color value. rQrr>r3Nzillegal image moderrr*r))rQrr>)rQrr>)rQr)r*r))rrSr\r!Zsetmoder{rrrrxr$rZfillbandrrTZputband)ralpharSr!r%rrrputalphas<          zImage.putalpha?cCs|j|jj|||dS)a Copies pixel data to this image. This method copies data from a sequence object into the image, starting at the upper left corner (0, 0), and continuing 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 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)rrrAr3rrrrFOs z Image.putdatar.cCsddlm}|jdkrtd|jt||jrD|j|j|j}n8t|t spt r\t |}ndj d d |D}|j||}d |jkrdnd|_||_d |j_|jd S)a Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image, and the palette sequence must contain 768 integer values, where each group of three values represent the red, green, and blue values for the corresponding pixel index. Instead of an integer sequence, you can use an 8-bit string. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. r)rr)rQr-rzillegal image moderhcss|]}t|VqdS)N)chr)rr0rrr xsz#Image.putpalette..r3r.N)r)rQr-r) rhrrSrrrurrrrrr)rrrrrrrrr`s      zImage.putpalettecCsh|jr|j|j|jr*|jj||S|jdkrZt|ttfrZt |dkrZ|j j |}|j 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 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-rr)rr) rrrrrrSrur-rvr`rrr!)rr.rrrrrs  zImage.putpixelc Cs*ddlm}|jdkrtd|dkr^|jdkrF|jjddd}qbtd d tdD}n|}d }d gd }x8t|D],\}}|||d|dd7}|||<qzWt|} |j } d| _|jd| ddd| _ | jj | j j | j d} |dt|d} | j | |jd|t|d| _ | S)a] 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. r)rr)r-zillegal image modeNr.icss|]}|dVqdS)rNr)rrrrrrHsz&Image.remap_palette..rrrr)rrT)r)r-)rhrrSrr!r bytearrayr enumeraterrrrrr`) rZdest_mapZsource_paletterZreal_source_paletteZ palette_bytesZ new_positionsr oldPositionZmapping_paletteZm_imZnew_palette_bytesrrr remap_palettes8        zImage.remap_palettecCs|ttttttfkrtdt|}|dkr8d |j}nt|}|j|kr`|d |jkr`|j S|j d krnt}|j d kr|j |j ddd }|j |||}|j |j S|j |j|jj |||S)a Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BOX`, :py:attr:`PIL.Image.BILINEAR`, :py:attr:`PIL.Image.HAMMING`, :py:attr:`PIL.Image.BICUBIC` or :py:attr:`PIL.Image.LANCZOS`. If omitted, or if the image has mode "1" or "P", it is set :py:attr:`PIL.Image.NEAREST`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats giving the region of the source image which should be scaled. The values should be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :returns: An :py:class:`~PIL.Image.Image` object. zunknown resampling filterNrr*r-rQr>rr)rr)rr)r*r-)rQr>)NEARESTBILINEARBICUBICLANCZOSBOXHAMMINGrrvrTrrSrresizerrr!)rrTresamplerr!rrrrUs"    z Image.resizecCs2|d}|p|s^|dkr |jS|dkr2|jtS|dkrH|rH|jtS|dkr^|r^|jtS|j\}}|dkrvd} n|} |dkr|d|df} n|} tj| }ttj |dttj |dd ttj | dttj |dd g} d d } | | d | d| d  | d | \| d <| d<| d | d7<| d| d 7<|rg} g}xJd|df||fd|ffD].\}}| ||| \}}| j ||j |qrWt tj t| tjt| }t tj t|tjt|}| || d|| d| \| d <| d<||}}|j||ft| ||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:attr:`PIL.Image.NEAREST` (use nearest neighbour), :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set :py:attr:`PIL.Image.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@rZiNg@gc Ss8|\}}}}}}||||||||||fS)Nr) r0r1rrrrrrrrrrr transformjszImage.rotate..transformrr%r&) fillcolor)rr)rr)r transpose ROTATE_180 ROTATE_90 ROTATE_270rTmathradiansrcossinrrceilrfloorrrZAFFINE)rZanglerVrcenter translater[wr#Z post_transZ rotn_centerrrZZxxyyr0r1nwZnhrrrrotatesR       $"     z Image.rotatec KsTd}d}t|r|}d}ntr4t|tr4t|}d}| rTt|drTt|jrT|j}|j|jdd}||_ f|_ t t j j|dj}|s|tkrty t|}Wn"tk rtdj|YnX|jtkrt|rt|j}n t|j}|r.|jddr"tj|d }n tj|d }z||||Wd |rN|jXd 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), pathlib.Path 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 IOError: If the file could not be written. The file may have been created, and may contain partial data. rhFTrsave_allrzunknown file extension: {}rzr+bzw+bN)r HAS_PATHLIBrur strr"rrpopZ encoderinfoZ encoderconfigrjrpathsplitextlower EXTENSIONrsrxrrupperrqSAVE_ALLrbuiltinsopenr) rrrparamsrZopen_fprmextZ save_handlerrrrrsH     z Image.savecCs|dkr tdS)a 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`. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. rN)EOFError)rframerrrseeksz Image.seekcCst|||ddS)a Displays this image. This method is mainly intended for debugging purposes. On Unix platforms, this method saves the image to a temporary PPM file, and calls the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, this method saves the image to a temporary PNG file, and opens it with the native Preview application. On Windows, it saves the image to a temporary BMP file, and uses the standard BMP display utility to show it (usually Paint). :param title: Optional title to use for the image window, where possible. :param command: command used to show the image )titlecommandN)_show)rr~rrrrshowsz Image.showcCs:|j|jjdkr |jg}nt|j|jj}t|S)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!r^rrrsplitrv)rrrrrrs   z Image.splitc CsX|jt|rFy|jj|}Wn"tk rDtdj|YnX|j|jj|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 "{}") rr rindexrrrr!r)rZchannelrrr getchannels zImage.getchannelcCsdS)z Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. :returns: Frame number, starting with 0. rr)rrrrtell0sz Image.tellcCs|j\}}||dkrr5)rVfillrNzmissing method datar)rr) rSrrZruImageTransformHandlerr"rrrMESH_Image__transformerQUAD) rrTr rrVrr[r!rZquadrrrrZjs(,        zImage.transformc Cs|d|d}|d|d}|tkr8|dd}n@|tkr|\} } } } t| | |} t| | |}t}| d| d|| f}n|tkr|dd}n|tkrp|dd}|dd}|dd}|dd}|\} } d|}d|}| |d| ||d| ||d|d|d| ||| |d| ||d| ||d|d|d| ||f}ntd |tttfkrtd |j |j |j d krt}|j j ||j ||||dS)Nr%rrrr'rg?zunknown transformation methodzunknown resampling filterr*r-)r*r-) rfEXTENTfloat PERSPECTIVErrrOrPrQrrSr!Z transform2)rrrr rrVrrir#rrrrxsZysrkswseneZAsZAtrrrZ __transformers@      "( zImage.__transformercCs|j|j|jj|S)a Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`, :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`, :py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.ROTATE_270`, :py:attr:`PIL.Image.TRANSPOSE` or :py:attr:`PIL.Image.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. )rrr!r\)rr rrrr\s zImage.transposecCs|j|j|jj|S)zj Randomly spread pixels in an image. :param distance: Distance to spread pixels. )rrr! effect_spread)rZdistancerrrrszImage.effect_spreadcCs$ddlm}|jstd|j|S)z#Returns a QImage copy of this imager)ImageQtzQt bindings are not installed)rhrqt_is_installedrtoqimage)rrrrrrs zImage.toqimagecCs$ddlm}|jstd|j|S)z$Returns a QPixmap copy of this imager)rzQt bindings are not installed)rhrrr toqpixmap)rrrrrr s zImage.toqpixmap)NN)r)r)r)rNrNr)N)N)r)N)NN)N)NNrrrr)rr)N)rDrE)r.)N)N)NN)Trrr__doc__rformat_descriptionZ!_close_exclusive_fp_after_loadingrpropertyrrrTrrrrsys version_infomajorrrrrrrrrrrrrrrrrrrWEBrrr__copy__rr rrrrr r"rr&r*r,rrr/r!r3r6r7r?rCrFrrrMrOrUrlrr}rrrrrQrrZrr\rrrrrrrr s         +  & 7 7          Q 0 '6  # L/l S  2J0 rc@s eZdZdS)r>N)rrrrrrrr> sr>c@s eZdZdS)rN)rrrrrrrr srcCstjtjdS)z+Create greyscale wedge (for debugging only)r))rrrzZwedgerrrr_wedge srcCsNt|ttfstdt|dkr*td|ddksB|ddkrJtddS)z Common check to enforce type and sanity check on size tuples :param size: Should be a 2 tuple of (width, height) :returns: True, or raises a ValueError zSize must be a tupler%z Size must be a tuple of length 2rrzWidth and height must be >= 0T)rur-rvrr`)rTrrr _check_size$ s rcCst||dkr$tjtj||St|rDddlm}|j||}t}|dkrt |t t frt |dkrddlm }|j |_|jj|}|jtj|||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 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. Nr)r4r-rr)r)rr)rrrrzrr rhr4rrur-rvr`rrr)rSrTcolorr4r!rrrrr6 s     rrcGsZt|t|dkr*t|dtr*|d}|dkr>|fkr>|}t||}|j||||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 Decoder `. 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. rrr)rr`rurvrr)rSrTrr}r~r!rrrr\ s rcOs tddS)Nzfromstring() has been removed. z Please call frombytes() instead.z?fromstring() has been removed. Please call frombytes() instead.)r)r~rrrrr srcGst|t|dkr*t|dtr*|d}|dkr|fkrTtjdtdd|ddf}|dtkrt|d }|j t j |||dd|}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 **BytesIO** object, and use :py:func:`~PIL.Image.open` to load it. In the current version, 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 rrrzthe frombuffer defaults may change in a future release; for portability, change the call to read: frombuffer(mode, size, data, 'raw', mode, 0, 1)r%) stacklevelNrN)rr)rr`rurvrrRuntimeWarning _MAPMODESrrrzZ map_bufferrr)rSrTrr}r~r!rrr frombuffer s #    rc Cs|j}|d}t|}|jdd}|dkrry(d|dd|df}t|\}}Wqvtk rntdYqvXn|}|dkrd}n|d krd}nd}||krtd||f|d|df} |dk rt|dr|j}n|j }t || |d|ddS)a Creates an image memory from an object exporting the array interface (using the buffer protocol). If **obj** is not contiguous, then the tobytes method is called and :py:func:`~PIL.Image.frombuffer` is used. If you have an image in NumPy:: from PIL import Image import numpy as np im = Image.open('hopper.jpg') a = np.asarray(im) Then this can be used to convert it to a Pillow image:: im = Image.fromarray(a) :param obj: Object with array interface :param mode: Mode to use (will be determined from type if None) See: :ref:`concept-modes`. :returns: An image object. .. versionadded:: 1.1.6 rstridesNrr%rzCannot handle this data typer*r)r+r-r,r.rrzToo many dimensions: %d > %d.rrr)rr)r*r)r+r-r,) rr`r_fromarray_typemaprxrrr"rrr) objrSZarrrndimrZtypekeyrZndmaxrTrrr fromarray s0   rcCs$ddlm}|jstd|j|S)z-Creates an image instance from a QImage imager)rzQt bindings are not installed)rhrrr fromqimage)r!rrrrr s rcCs$ddlm}|jstd|j|S)z.Creates an image instance from a QPixmap imager)rzQt bindings are not installed)rhrrr fromqpixmap)r!rrrrr s r1;8|i1I;8I;16SI;16BSI;32I;32BI;32SI;32BSf4F;32BFf8F;64BFrQcCs\tdkr dS|d|d}|dtkr._open_coreNzcannot identify image file %r)rr rnrur roresolverwrxr}r{rUnsupportedOperationrreadrjrsrrrrr|)rrSrrrr!messager)rrrrx= sB        rxcCs&|j|j|jtj|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. )rrrzr7r!)im1im2rrrr7 s r7cCs(|j|j|jtj|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. )rrrzblendr!)rrrBrrrr srcCs|j}|j|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)rr6)Zimage1Zimage2r2rrrr composite s rcGs|j|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?)rr~rrreval s rcCst|t|ksd|kr tdxB|ddD]2}|jt|krHtd|j|djkr.tdq.Wx|D] }|jqjW|djtj |fdd |DS) 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!)rrrrrr szmerge..) rar`rrSr]rTrrrzr)rSr^r%rrrr s    rcCs"|j}tj|||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)rurrrp)rrrrrr register_open s  rcCs|t|j<dS)z Registers an image MIME type. This function should not be used in application code. :param id: An image format identifier. :param mimetype: The image MIME type for this format. N)MIMEru)rmimetyperrr register_mime srcCs|t|j<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)rqru)rdriverrrr register_save srcCs|t|j<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)rvru)rrrrrregister_save_all s rcCs|jt|j<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)rurtrs)r extensionrrrregister_extension* srcCsx|D]}t||qWdS)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 extensionsrrrrregister_extensions5 s rcCsts ttS)za Returns a dictionary containing all file extensions belonging to registered plugins )rtrsrrrrregistered_extensionsA srcCs |t|<dS)a Registers an image decoder. This function should not be used in application code. :param name: The name of the decoder :param decoder: A callable(mode, args) that returns an ImageFile.PyDecoder object .. versionadded:: 4.1.0 N)rw)rrrrrregister_decoderK s rcCs |t|<dS)a Registers an image encoder. This function should not be used in application code. :param name: The name of the encoder :param encoder: A callable(mode, args) that returns an ImageFile.PyEncoder object .. versionadded:: 4.1.0 N)r)rrrrrregister_encoderY s rcKst|f|dS)N)_showxv)rrrrrrj srcKs ddlm}|j||f|dS)Nr) ImageShow)rhrr)rr~rrrrrro s rcCstjtj|||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, y2). :param quality: Quality. )rrrzeffect_mandelbrot)rTZextentZqualityrrrrw s rcCstjtj||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. )rrrz effect_noise)rTsigmarrrr srcCstjtj|S)zl Generate 256x256 linear gradient from black to white, top to bottom. :param mode: Input mode. )rrrzlinear_gradient)rSrrrr srcCstjtj|S)zm Generate 256x256 radial gradient from black to white, centre to edge. :param mode: Input mode. )rrrzradial_gradient)rSrrrr srcCs|dkrtj}xdtjfdtjfdtjfgD]\}}||kr@q.||j}d}x0d D](\}}|j|rV|}|dt| }qVWyt ||}Wn&t k rt j dj |w.YnXy ||Wq.t k r}zt j d j ||WYdd}~Xq.Xq.WdS)NZPILLOW_ALIGNMENTZPILLOW_BLOCK_SIZEZPILLOW_BLOCKS_MAXrkrz{0} is not intz{0}: {1}rrrr)rr)renvironrzZ set_alignmentZset_block_sizeZset_blocks_maxrsrr`rrrrr)envvar_namesettervarZunitsZpostfixmulrrrrr_apply_env_variables s.   rc@seZdZdZddZddZddZdd Zd d d Zd dZ ddZ ddZ ddZ ddZ esjddZddZddZddZdS)!r)rDcCsi|_i|_dS)N)_data_ifds)rrrrr sz Exif.__init__csddfdd|jDS)Nc Ss>y$t|dkr"t|t r"|dSWntk r8YnX|S)Nrr)r`rudictr)rrrr_fixup s  z Exif._fixup_dict.._fixupcsi|]\}}||qSrr)rrr)rrr sz$Exif._fixup_dict..)items)rZsrc_dictr)rr _fixup_dict szExif._fixup_dictc Csby|jj|j|Wnttfk r.Yn0Xddlm}|j|j}|j |j|j |SdS)Nr)TiffImagePlugin) rr}rrxrrhrImageFileDirectory_v1headrr)rtagrrrrr _get_ifd_dict s   zExif._get_ifd_dictcCstj|dd|_|jjd|_ddlm}|j|j}|j|_ |jj |j |j |jt |j||_|jd}|r|jj|||jd<|jd}|r||jd<||jd<dS)Nr'rr)riii%)rrrrrrhrr_endianendianr}nextrrrrr updater)rrrrifdrrrr s         z Exif.loadrcCs^ddlm}|jdkrd}nd}|j|d}x|jjD]\}}|||<q8Wd||j|S)Nr)rrDsII*sMM*)ZifhsExif)rhrr ImageFileDirectory_v2rrr)rr3rrrrrrrrr s    z Exif.tobytescCs&||jko||jkr|dkr2|j||j|<n|dkrddlm}|jddddkr|jd}t|dd}||d}i}xtdtjd |dd dD]}tjd ||dd |ddd \}} } } y|j j | \} } Wnt k r wYnX| | }|d krHtjd | \}||d||d} n | d|} t | |kr|t jd|t | |fq| sq| |j | d||<qWt|j||jd<nd|jjddkr|jd}i}x6tdtjd|dd dD]}tjd||dd |ddd \}} } } |dkrtjd| \}|jj|d|jjd i}|jjd t|jjd|d<|jjd |jjd |d<|jjd|jjd }|j j tjd} | |j |d|d<|jjd |jjd |d<dt|j|i}qW||jd<|jj|iS)Nii|r)rrsFUJIFILM rzHz>HHL4siz>LZModelIDZ TimeStampZInternalSerialNumberZParallaxZCategory)rrr rhrr rrunpackrZ_load_dispatchrxr`rrrrrrr}rrFLOAT)rrrZ exif_dataZ ifd_offsetZifd_dataZ makernoterZifd_tagrUcountrZ unit_sizehandlerrTr3Z camerainfoZparallaxrrrget_ifd sv    &,   (,         z Exif.get_ifdcCs t|jS)N)ror)rrrr__str__a sz Exif.__str__cCs t|jS)N)r`r)rrrr__len__d sz Exif.__len__cCs |j|S)N)r)rrrrr __getitem__g szExif.__getitem__cCs ||jkS)N)r)rrrrr __contains__j szExif.__contains__cCs||kS)Nr)rrrrrhas_keyn sz Exif.has_keycCs||j|<dS)N)r)rrrrrr __setitem__q szExif.__setitem__cCs |j|=dS)N)r)rrrrr __delitem__t szExif.__delitem__cCstt|jS)N)itersetr)rrrr__iter__w sz Exif.__iter__N)r)rrrr rrr rrrrrrrrrrrrrrrrr) s    Pr)ii@iiUUUr*)r)r)r r))r)r)r!r+)r)r+r"r,)r)r,r#r-)r-r)r$r/r0r1)r.r)r%r/r0r1r2)r.r)r&r/r0r1r3)r.r)r'r4r5r6r7)r.r)r(r6r8r9)r.r)r)r)r3r1)r.r)r*r:r;r<)r.r)r+)rFN)rGN)rGr%)rGN)rGr)rGr)rGr)rGr)rGr)rGr)rGr)rIN)rJN)rIN)rKN)rLN)rKN)rMN)rNN)rMN)rON)rPN)rON)r)r-r=r>r?rXrYrZ)r)r)r)Nrr)r,rF)r*rrr)r-rG)r)r)rr)r.r)r+rrr)r/rI)r+rXrr)r0rJ)r+rZrr)r1rK)r+rrr)r2rL)r+rrr)r3rM)r+rrr)r4rN)r+rrr)r5rO)r+rrr)r6rP)r+rrr)r7r)r,rrr)r8r)r,rrr)r9r)r,rrr)r:r)r,rrrr%)r;rG)rQrQrrr)r<rG)r.r.rrr)r=rG)r>r>)r+r+)rr)r,r,)rr)r)N)N)N)rhrrrZ_utilrloggingrr`rwr __builtin__rr_binaryr r r r r rrrratexitrcollections.abcrr collectionsri getLoggerrrkrrrrobjectrrrrrzryrro startswithrr"rrZpathlibr rnZpathlib2r$NONEZFLIP_LEFT_RIGHTZFLIP_TOP_BOTTOMr^r]r_Z TRANSPOSEZ TRANSVERSErfrrrrrOrSrPZLINEARrTrQZCUBICrRZ ANTIALIASZORDEREDZ RASTERIZEr rrZ MEDIANCUTZ MAXCOVERAGEZ FASTOCTREEZ LIBIMAGEQUANTrZSEQUENCEZ CONTAINERr(ZFILTEREDZ HUFFMAN_ONLYZRLEZFIXEDrrprrqrvrtrwrZ _MODEINFO byteorderZ_ENDIANrRrWsortedZMODESrr\r]r_rargrjrsrrrrrrr>rrrrrrrrrrrrrxr7rrrrrrrrrrrrrrrrrrrrregister clear_cacher)rrrrs                   )     & & = 9   Z