Image.py 145 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # the Image class wrapper
  6. #
  7. # partial release history:
  8. # 1995-09-09 fl Created
  9. # 1996-03-11 fl PIL release 0.0 (proof of concept)
  10. # 1996-04-30 fl PIL release 0.1b1
  11. # 1999-07-28 fl PIL release 1.0 final
  12. # 2000-06-07 fl PIL release 1.1
  13. # 2000-10-20 fl PIL release 1.1.1
  14. # 2001-05-07 fl PIL release 1.1.2
  15. # 2002-03-15 fl PIL release 1.1.3
  16. # 2003-05-10 fl PIL release 1.1.4
  17. # 2005-03-28 fl PIL release 1.1.5
  18. # 2006-12-02 fl PIL release 1.1.6
  19. # 2009-11-15 fl PIL release 1.1.7
  20. #
  21. # Copyright (c) 1997-2009 by Secret Labs AB. All rights reserved.
  22. # Copyright (c) 1995-2009 by Fredrik Lundh.
  23. #
  24. # See the README file for information on usage and redistribution.
  25. #
  26. from __future__ import annotations
  27. import abc
  28. import atexit
  29. import builtins
  30. import io
  31. import logging
  32. import math
  33. import os
  34. import re
  35. import struct
  36. import sys
  37. import tempfile
  38. import warnings
  39. from collections.abc import MutableMapping
  40. from enum import IntEnum
  41. from typing import IO, Protocol, cast
  42. # VERSION was removed in Pillow 6.0.0.
  43. # PILLOW_VERSION was removed in Pillow 9.0.0.
  44. # Use __version__ instead.
  45. from . import (
  46. ExifTags,
  47. ImageMode,
  48. TiffTags,
  49. UnidentifiedImageError,
  50. __version__,
  51. _plugins,
  52. )
  53. from ._binary import i32le, o32be, o32le
  54. from ._deprecate import deprecate
  55. from ._util import DeferredError, is_path
  56. ElementTree: ModuleType | None
  57. try:
  58. from defusedxml import ElementTree
  59. except ImportError:
  60. ElementTree = None
  61. TYPE_CHECKING = False
  62. if TYPE_CHECKING:
  63. from collections.abc import Callable, Iterator, Sequence
  64. from types import ModuleType
  65. from typing import Any, Literal
  66. logger = logging.getLogger(__name__)
  67. class DecompressionBombWarning(RuntimeWarning):
  68. pass
  69. class DecompressionBombError(Exception):
  70. pass
  71. WARN_POSSIBLE_FORMATS: bool = False
  72. # Limit to around a quarter gigabyte for a 24-bit (3 bpp) image
  73. MAX_IMAGE_PIXELS: int | None = int(1024 * 1024 * 1024 // 4 // 3)
  74. try:
  75. # If the _imaging C module is not present, Pillow will not load.
  76. # Note that other modules should not refer to _imaging directly;
  77. # import Image and use the Image.core variable instead.
  78. # Also note that Image.core is not a publicly documented interface,
  79. # and should be considered private and subject to change.
  80. from . import _imaging as core
  81. if __version__ != getattr(core, "PILLOW_VERSION", None):
  82. msg = (
  83. "The _imaging extension was built for another version of Pillow or PIL:\n"
  84. f"Core version: {getattr(core, 'PILLOW_VERSION', None)}\n"
  85. f"Pillow version: {__version__}"
  86. )
  87. raise ImportError(msg)
  88. except ImportError as v:
  89. # Explanations for ways that we know we might have an import error
  90. if str(v).startswith("Module use of python"):
  91. # The _imaging C module is present, but not compiled for
  92. # the right version (windows only). Print a warning, if
  93. # possible.
  94. warnings.warn(
  95. "The _imaging extension was built for another version of Python.",
  96. RuntimeWarning,
  97. )
  98. elif str(v).startswith("The _imaging extension"):
  99. warnings.warn(str(v), RuntimeWarning)
  100. # Fail here anyway. Don't let people run with a mostly broken Pillow.
  101. # see docs/porting.rst
  102. raise
  103. #
  104. # Constants
  105. # transpose
  106. class Transpose(IntEnum):
  107. FLIP_LEFT_RIGHT = 0
  108. FLIP_TOP_BOTTOM = 1
  109. ROTATE_90 = 2
  110. ROTATE_180 = 3
  111. ROTATE_270 = 4
  112. TRANSPOSE = 5
  113. TRANSVERSE = 6
  114. # transforms (also defined in Imaging.h)
  115. class Transform(IntEnum):
  116. AFFINE = 0
  117. EXTENT = 1
  118. PERSPECTIVE = 2
  119. QUAD = 3
  120. MESH = 4
  121. # resampling filters (also defined in Imaging.h)
  122. class Resampling(IntEnum):
  123. NEAREST = 0
  124. BOX = 4
  125. BILINEAR = 2
  126. HAMMING = 5
  127. BICUBIC = 3
  128. LANCZOS = 1
  129. _filters_support = {
  130. Resampling.BOX: 0.5,
  131. Resampling.BILINEAR: 1.0,
  132. Resampling.HAMMING: 1.0,
  133. Resampling.BICUBIC: 2.0,
  134. Resampling.LANCZOS: 3.0,
  135. }
  136. # dithers
  137. class Dither(IntEnum):
  138. NONE = 0
  139. ORDERED = 1 # Not yet implemented
  140. RASTERIZE = 2 # Not yet implemented
  141. FLOYDSTEINBERG = 3 # default
  142. # palettes/quantizers
  143. class Palette(IntEnum):
  144. WEB = 0
  145. ADAPTIVE = 1
  146. class Quantize(IntEnum):
  147. MEDIANCUT = 0
  148. MAXCOVERAGE = 1
  149. FASTOCTREE = 2
  150. LIBIMAGEQUANT = 3
  151. module = sys.modules[__name__]
  152. for enum in (Transpose, Transform, Resampling, Dither, Palette, Quantize):
  153. for item in enum:
  154. setattr(module, item.name, item.value)
  155. if hasattr(core, "DEFAULT_STRATEGY"):
  156. DEFAULT_STRATEGY = core.DEFAULT_STRATEGY
  157. FILTERED = core.FILTERED
  158. HUFFMAN_ONLY = core.HUFFMAN_ONLY
  159. RLE = core.RLE
  160. FIXED = core.FIXED
  161. # --------------------------------------------------------------------
  162. # Registries
  163. TYPE_CHECKING = False
  164. if TYPE_CHECKING:
  165. import mmap
  166. from xml.etree.ElementTree import Element
  167. from IPython.lib.pretty import PrettyPrinter
  168. from . import ImageFile, ImageFilter, ImagePalette, ImageQt, TiffImagePlugin
  169. from ._typing import CapsuleType, NumpyArray, StrOrBytesPath
  170. ID: list[str] = []
  171. OPEN: dict[
  172. str,
  173. tuple[
  174. Callable[[IO[bytes], str | bytes], ImageFile.ImageFile],
  175. Callable[[bytes], bool | str] | None,
  176. ],
  177. ] = {}
  178. MIME: dict[str, str] = {}
  179. SAVE: dict[str, Callable[[Image, IO[bytes], str | bytes], None]] = {}
  180. SAVE_ALL: dict[str, Callable[[Image, IO[bytes], str | bytes], None]] = {}
  181. EXTENSION: dict[str, str] = {}
  182. DECODERS: dict[str, type[ImageFile.PyDecoder]] = {}
  183. ENCODERS: dict[str, type[ImageFile.PyEncoder]] = {}
  184. # --------------------------------------------------------------------
  185. # Modes
  186. _ENDIAN = "<" if sys.byteorder == "little" else ">"
  187. def _conv_type_shape(im: Image) -> tuple[tuple[int, ...], str]:
  188. m = ImageMode.getmode(im.mode)
  189. shape: tuple[int, ...] = (im.height, im.width)
  190. extra = len(m.bands)
  191. if extra != 1:
  192. shape += (extra,)
  193. return shape, m.typestr
  194. MODES = [
  195. "1",
  196. "CMYK",
  197. "F",
  198. "HSV",
  199. "I",
  200. "I;16",
  201. "I;16B",
  202. "I;16L",
  203. "I;16N",
  204. "L",
  205. "LA",
  206. "La",
  207. "LAB",
  208. "P",
  209. "PA",
  210. "RGB",
  211. "RGBA",
  212. "RGBa",
  213. "RGBX",
  214. "YCbCr",
  215. ]
  216. # raw modes that may be memory mapped. NOTE: if you change this, you
  217. # may have to modify the stride calculation in map.c too!
  218. _MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16L", "I;16B")
  219. def getmodebase(mode: str) -> str:
  220. """
  221. Gets the "base" mode for given mode. This function returns "L" for
  222. images that contain grayscale data, and "RGB" for images that
  223. contain color data.
  224. :param mode: Input mode.
  225. :returns: "L" or "RGB".
  226. :exception KeyError: If the input mode was not a standard mode.
  227. """
  228. return ImageMode.getmode(mode).basemode
  229. def getmodetype(mode: str) -> str:
  230. """
  231. Gets the storage type mode. Given a mode, this function returns a
  232. single-layer mode suitable for storing individual bands.
  233. :param mode: Input mode.
  234. :returns: "L", "I", or "F".
  235. :exception KeyError: If the input mode was not a standard mode.
  236. """
  237. return ImageMode.getmode(mode).basetype
  238. def getmodebandnames(mode: str) -> tuple[str, ...]:
  239. """
  240. Gets a list of individual band names. Given a mode, this function returns
  241. a tuple containing the names of individual bands (use
  242. :py:method:`~PIL.Image.getmodetype` to get the mode used to store each
  243. individual band.
  244. :param mode: Input mode.
  245. :returns: A tuple containing band names. The length of the tuple
  246. gives the number of bands in an image of the given mode.
  247. :exception KeyError: If the input mode was not a standard mode.
  248. """
  249. return ImageMode.getmode(mode).bands
  250. def getmodebands(mode: str) -> int:
  251. """
  252. Gets the number of individual bands for this mode.
  253. :param mode: Input mode.
  254. :returns: The number of bands in this mode.
  255. :exception KeyError: If the input mode was not a standard mode.
  256. """
  257. return len(ImageMode.getmode(mode).bands)
  258. # --------------------------------------------------------------------
  259. # Helpers
  260. _initialized = 0
  261. def preinit() -> None:
  262. """
  263. Explicitly loads BMP, GIF, JPEG, PPM and PPM file format drivers.
  264. It is called when opening or saving images.
  265. """
  266. global _initialized
  267. if _initialized >= 1:
  268. return
  269. try:
  270. from . import BmpImagePlugin
  271. assert BmpImagePlugin
  272. except ImportError:
  273. pass
  274. try:
  275. from . import GifImagePlugin
  276. assert GifImagePlugin
  277. except ImportError:
  278. pass
  279. try:
  280. from . import JpegImagePlugin
  281. assert JpegImagePlugin
  282. except ImportError:
  283. pass
  284. try:
  285. from . import PpmImagePlugin
  286. assert PpmImagePlugin
  287. except ImportError:
  288. pass
  289. try:
  290. from . import PngImagePlugin
  291. assert PngImagePlugin
  292. except ImportError:
  293. pass
  294. _initialized = 1
  295. def init() -> bool:
  296. """
  297. Explicitly initializes the Python Imaging Library. This function
  298. loads all available file format drivers.
  299. It is called when opening or saving images if :py:meth:`~preinit()` is
  300. insufficient, and by :py:meth:`~PIL.features.pilinfo`.
  301. """
  302. global _initialized
  303. if _initialized >= 2:
  304. return False
  305. parent_name = __name__.rpartition(".")[0]
  306. for plugin in _plugins:
  307. try:
  308. logger.debug("Importing %s", plugin)
  309. __import__(f"{parent_name}.{plugin}", globals(), locals(), [])
  310. except ImportError as e:
  311. logger.debug("Image: failed to import %s: %s", plugin, e)
  312. if OPEN or SAVE:
  313. _initialized = 2
  314. return True
  315. return False
  316. # --------------------------------------------------------------------
  317. # Codec factories (used by tobytes/frombytes and ImageFile.load)
  318. def _getdecoder(
  319. mode: str, decoder_name: str, args: Any, extra: tuple[Any, ...] = ()
  320. ) -> core.ImagingDecoder | ImageFile.PyDecoder:
  321. # tweak arguments
  322. if args is None:
  323. args = ()
  324. elif not isinstance(args, tuple):
  325. args = (args,)
  326. try:
  327. decoder = DECODERS[decoder_name]
  328. except KeyError:
  329. pass
  330. else:
  331. return decoder(mode, *args + extra)
  332. try:
  333. # get decoder
  334. decoder = getattr(core, f"{decoder_name}_decoder")
  335. except AttributeError as e:
  336. msg = f"decoder {decoder_name} not available"
  337. raise OSError(msg) from e
  338. return decoder(mode, *args + extra)
  339. def _getencoder(
  340. mode: str, encoder_name: str, args: Any, extra: tuple[Any, ...] = ()
  341. ) -> core.ImagingEncoder | ImageFile.PyEncoder:
  342. # tweak arguments
  343. if args is None:
  344. args = ()
  345. elif not isinstance(args, tuple):
  346. args = (args,)
  347. try:
  348. encoder = ENCODERS[encoder_name]
  349. except KeyError:
  350. pass
  351. else:
  352. return encoder(mode, *args + extra)
  353. try:
  354. # get encoder
  355. encoder = getattr(core, f"{encoder_name}_encoder")
  356. except AttributeError as e:
  357. msg = f"encoder {encoder_name} not available"
  358. raise OSError(msg) from e
  359. return encoder(mode, *args + extra)
  360. # --------------------------------------------------------------------
  361. # Simple expression analyzer
  362. class ImagePointTransform:
  363. """
  364. Used with :py:meth:`~PIL.Image.Image.point` for single band images with more than
  365. 8 bits, this represents an affine transformation, where the value is multiplied by
  366. ``scale`` and ``offset`` is added.
  367. """
  368. def __init__(self, scale: float, offset: float) -> None:
  369. self.scale = scale
  370. self.offset = offset
  371. def __neg__(self) -> ImagePointTransform:
  372. return ImagePointTransform(-self.scale, -self.offset)
  373. def __add__(self, other: ImagePointTransform | float) -> ImagePointTransform:
  374. if isinstance(other, ImagePointTransform):
  375. return ImagePointTransform(
  376. self.scale + other.scale, self.offset + other.offset
  377. )
  378. return ImagePointTransform(self.scale, self.offset + other)
  379. __radd__ = __add__
  380. def __sub__(self, other: ImagePointTransform | float) -> ImagePointTransform:
  381. return self + -other
  382. def __rsub__(self, other: ImagePointTransform | float) -> ImagePointTransform:
  383. return other + -self
  384. def __mul__(self, other: ImagePointTransform | float) -> ImagePointTransform:
  385. if isinstance(other, ImagePointTransform):
  386. return NotImplemented
  387. return ImagePointTransform(self.scale * other, self.offset * other)
  388. __rmul__ = __mul__
  389. def __truediv__(self, other: ImagePointTransform | float) -> ImagePointTransform:
  390. if isinstance(other, ImagePointTransform):
  391. return NotImplemented
  392. return ImagePointTransform(self.scale / other, self.offset / other)
  393. def _getscaleoffset(
  394. expr: Callable[[ImagePointTransform], ImagePointTransform | float],
  395. ) -> tuple[float, float]:
  396. a = expr(ImagePointTransform(1, 0))
  397. return (a.scale, a.offset) if isinstance(a, ImagePointTransform) else (0, a)
  398. # --------------------------------------------------------------------
  399. # Implementation wrapper
  400. class SupportsGetData(Protocol):
  401. def getdata(
  402. self,
  403. ) -> tuple[Transform, Sequence[int]]: ...
  404. class Image:
  405. """
  406. This class represents an image object. To create
  407. :py:class:`~PIL.Image.Image` objects, use the appropriate factory
  408. functions. There's hardly ever any reason to call the Image constructor
  409. directly.
  410. * :py:func:`~PIL.Image.open`
  411. * :py:func:`~PIL.Image.new`
  412. * :py:func:`~PIL.Image.frombytes`
  413. """
  414. format: str | None = None
  415. format_description: str | None = None
  416. _close_exclusive_fp_after_loading = True
  417. def __init__(self) -> None:
  418. # FIXME: take "new" parameters / other image?
  419. self._im: core.ImagingCore | DeferredError | None = None
  420. self._mode = ""
  421. self._size = (0, 0)
  422. self.palette: ImagePalette.ImagePalette | None = None
  423. self.info: dict[str | tuple[int, int], Any] = {}
  424. self.readonly = 0
  425. self._exif: Exif | None = None
  426. @property
  427. def im(self) -> core.ImagingCore:
  428. if isinstance(self._im, DeferredError):
  429. raise self._im.ex
  430. assert self._im is not None
  431. return self._im
  432. @im.setter
  433. def im(self, im: core.ImagingCore) -> None:
  434. self._im = im
  435. @property
  436. def width(self) -> int:
  437. return self.size[0]
  438. @property
  439. def height(self) -> int:
  440. return self.size[1]
  441. @property
  442. def size(self) -> tuple[int, int]:
  443. return self._size
  444. @property
  445. def mode(self) -> str:
  446. return self._mode
  447. @property
  448. def readonly(self) -> int:
  449. return (self._im and self._im.readonly) or self._readonly
  450. @readonly.setter
  451. def readonly(self, readonly: int) -> None:
  452. self._readonly = readonly
  453. def _new(self, im: core.ImagingCore) -> Image:
  454. new = Image()
  455. new.im = im
  456. new._mode = im.mode
  457. new._size = im.size
  458. if im.mode in ("P", "PA"):
  459. if self.palette:
  460. new.palette = self.palette.copy()
  461. else:
  462. from . import ImagePalette
  463. new.palette = ImagePalette.ImagePalette()
  464. new.info = self.info.copy()
  465. return new
  466. # Context manager support
  467. def __enter__(self) -> Image:
  468. return self
  469. def __exit__(self, *args: object) -> None:
  470. pass
  471. def close(self) -> None:
  472. """
  473. This operation will destroy the image core and release its memory.
  474. The image data will be unusable afterward.
  475. This function is required to close images that have multiple frames or
  476. have not had their file read and closed by the
  477. :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for
  478. more information.
  479. """
  480. if getattr(self, "map", None):
  481. if sys.platform == "win32" and hasattr(sys, "pypy_version_info"):
  482. self.map.close()
  483. self.map: mmap.mmap | None = None
  484. # Instead of simply setting to None, we're setting up a
  485. # deferred error that will better explain that the core image
  486. # object is gone.
  487. self._im = DeferredError(ValueError("Operation on closed image"))
  488. def _copy(self) -> None:
  489. self.load()
  490. self.im = self.im.copy()
  491. self.readonly = 0
  492. def _ensure_mutable(self) -> None:
  493. if self.readonly:
  494. self._copy()
  495. else:
  496. self.load()
  497. def _dump(
  498. self, file: str | None = None, format: str | None = None, **options: Any
  499. ) -> str:
  500. suffix = ""
  501. if format:
  502. suffix = f".{format}"
  503. if not file:
  504. f, filename = tempfile.mkstemp(suffix)
  505. os.close(f)
  506. else:
  507. filename = file
  508. if not filename.endswith(suffix):
  509. filename = filename + suffix
  510. self.load()
  511. if not format or format == "PPM":
  512. self.im.save_ppm(filename)
  513. else:
  514. self.save(filename, format, **options)
  515. return filename
  516. def __eq__(self, other: object) -> bool:
  517. if self.__class__ is not other.__class__:
  518. return False
  519. assert isinstance(other, Image)
  520. return (
  521. self.mode == other.mode
  522. and self.size == other.size
  523. and self.info == other.info
  524. and self.getpalette() == other.getpalette()
  525. and self.tobytes() == other.tobytes()
  526. )
  527. def __repr__(self) -> str:
  528. return (
  529. f"<{self.__class__.__module__}.{self.__class__.__name__} "
  530. f"image mode={self.mode} size={self.size[0]}x{self.size[1]} "
  531. f"at 0x{id(self):X}>"
  532. )
  533. def _repr_pretty_(self, p: PrettyPrinter, cycle: bool) -> None:
  534. """IPython plain text display support"""
  535. # Same as __repr__ but without unpredictable id(self),
  536. # to keep Jupyter notebook `text/plain` output stable.
  537. p.text(
  538. f"<{self.__class__.__module__}.{self.__class__.__name__} "
  539. f"image mode={self.mode} size={self.size[0]}x{self.size[1]}>"
  540. )
  541. def _repr_image(self, image_format: str, **kwargs: Any) -> bytes | None:
  542. """Helper function for iPython display hook.
  543. :param image_format: Image format.
  544. :returns: image as bytes, saved into the given format.
  545. """
  546. b = io.BytesIO()
  547. try:
  548. self.save(b, image_format, **kwargs)
  549. except Exception:
  550. return None
  551. return b.getvalue()
  552. def _repr_png_(self) -> bytes | None:
  553. """iPython display hook support for PNG format.
  554. :returns: PNG version of the image as bytes
  555. """
  556. return self._repr_image("PNG", compress_level=1)
  557. def _repr_jpeg_(self) -> bytes | None:
  558. """iPython display hook support for JPEG format.
  559. :returns: JPEG version of the image as bytes
  560. """
  561. return self._repr_image("JPEG")
  562. @property
  563. def __array_interface__(self) -> dict[str, str | bytes | int | tuple[int, ...]]:
  564. # numpy array interface support
  565. new: dict[str, str | bytes | int | tuple[int, ...]] = {"version": 3}
  566. if self.mode == "1":
  567. # Binary images need to be extended from bits to bytes
  568. # See: https://github.com/python-pillow/Pillow/issues/350
  569. new["data"] = self.tobytes("raw", "L")
  570. else:
  571. new["data"] = self.tobytes()
  572. new["shape"], new["typestr"] = _conv_type_shape(self)
  573. return new
  574. def __arrow_c_schema__(self) -> object:
  575. self.load()
  576. return self.im.__arrow_c_schema__()
  577. def __arrow_c_array__(
  578. self, requested_schema: object | None = None
  579. ) -> tuple[object, object]:
  580. self.load()
  581. return (self.im.__arrow_c_schema__(), self.im.__arrow_c_array__())
  582. def __getstate__(self) -> list[Any]:
  583. im_data = self.tobytes() # load image first
  584. return [self.info, self.mode, self.size, self.getpalette(), im_data]
  585. def __setstate__(self, state: list[Any]) -> None:
  586. Image.__init__(self)
  587. info, mode, size, palette, data = state[:5]
  588. self.info = info
  589. self._mode = mode
  590. self._size = size
  591. self.im = core.new(mode, size)
  592. if mode in ("L", "LA", "P", "PA") and palette:
  593. self.putpalette(palette)
  594. self.frombytes(data)
  595. def tobytes(self, encoder_name: str = "raw", *args: Any) -> bytes:
  596. """
  597. Return image as a bytes object.
  598. .. warning::
  599. This method returns raw image data derived from Pillow's internal
  600. storage. For compressed image data (e.g. PNG, JPEG) use
  601. :meth:`~.save`, with a BytesIO parameter for in-memory data.
  602. :param encoder_name: What encoder to use.
  603. The default is to use the standard "raw" encoder.
  604. To see how this packs pixel data into the returned
  605. bytes, see :file:`libImaging/Pack.c`.
  606. A list of C encoders can be seen under codecs
  607. section of the function array in
  608. :file:`_imaging.c`. Python encoders are registered
  609. within the relevant plugins.
  610. :param args: Extra arguments to the encoder.
  611. :returns: A :py:class:`bytes` object.
  612. """
  613. encoder_args: Any = args
  614. if len(encoder_args) == 1 and isinstance(encoder_args[0], tuple):
  615. # may pass tuple instead of argument list
  616. encoder_args = encoder_args[0]
  617. if encoder_name == "raw" and encoder_args == ():
  618. encoder_args = self.mode
  619. self.load()
  620. if self.width == 0 or self.height == 0:
  621. return b""
  622. # unpack data
  623. e = _getencoder(self.mode, encoder_name, encoder_args)
  624. e.setimage(self.im)
  625. from . import ImageFile
  626. bufsize = max(ImageFile.MAXBLOCK, self.size[0] * 4) # see RawEncode.c
  627. output = []
  628. while True:
  629. bytes_consumed, errcode, data = e.encode(bufsize)
  630. output.append(data)
  631. if errcode:
  632. break
  633. if errcode < 0:
  634. msg = f"encoder error {errcode} in tobytes"
  635. raise RuntimeError(msg)
  636. return b"".join(output)
  637. def tobitmap(self, name: str = "image") -> bytes:
  638. """
  639. Returns the image converted to an X11 bitmap.
  640. .. note:: This method only works for mode "1" images.
  641. :param name: The name prefix to use for the bitmap variables.
  642. :returns: A string containing an X11 bitmap.
  643. :raises ValueError: If the mode is not "1"
  644. """
  645. self.load()
  646. if self.mode != "1":
  647. msg = "not a bitmap"
  648. raise ValueError(msg)
  649. data = self.tobytes("xbm")
  650. return b"".join(
  651. [
  652. f"#define {name}_width {self.size[0]}\n".encode("ascii"),
  653. f"#define {name}_height {self.size[1]}\n".encode("ascii"),
  654. f"static char {name}_bits[] = {{\n".encode("ascii"),
  655. data,
  656. b"};",
  657. ]
  658. )
  659. def frombytes(
  660. self,
  661. data: bytes | bytearray | SupportsArrayInterface,
  662. decoder_name: str = "raw",
  663. *args: Any,
  664. ) -> None:
  665. """
  666. Loads this image with pixel data from a bytes object.
  667. This method is similar to the :py:func:`~PIL.Image.frombytes` function,
  668. but loads data into this image instead of creating a new image object.
  669. """
  670. if self.width == 0 or self.height == 0:
  671. return
  672. decoder_args: Any = args
  673. if len(decoder_args) == 1 and isinstance(decoder_args[0], tuple):
  674. # may pass tuple instead of argument list
  675. decoder_args = decoder_args[0]
  676. # default format
  677. if decoder_name == "raw" and decoder_args == ():
  678. decoder_args = self.mode
  679. # unpack data
  680. d = _getdecoder(self.mode, decoder_name, decoder_args)
  681. d.setimage(self.im)
  682. s = d.decode(data)
  683. if s[0] >= 0:
  684. msg = "not enough image data"
  685. raise ValueError(msg)
  686. if s[1] != 0:
  687. msg = "cannot decode image data"
  688. raise ValueError(msg)
  689. def load(self) -> core.PixelAccess | None:
  690. """
  691. Allocates storage for the image and loads the pixel data. In
  692. normal cases, you don't need to call this method, since the
  693. Image class automatically loads an opened image when it is
  694. accessed for the first time.
  695. If the file associated with the image was opened by Pillow, then this
  696. method will close it. The exception to this is if the image has
  697. multiple frames, in which case the file will be left open for seek
  698. operations. See :ref:`file-handling` for more information.
  699. :returns: An image access object.
  700. :rtype: :py:class:`.PixelAccess`
  701. """
  702. if self._im is not None and self.palette and self.palette.dirty:
  703. # realize palette
  704. mode, arr = self.palette.getdata()
  705. self.im.putpalette(self.palette.mode, mode, arr)
  706. self.palette.dirty = 0
  707. self.palette.rawmode = None
  708. if "transparency" in self.info and mode in ("LA", "PA"):
  709. if isinstance(self.info["transparency"], int):
  710. self.im.putpalettealpha(self.info["transparency"], 0)
  711. else:
  712. self.im.putpalettealphas(self.info["transparency"])
  713. self.palette.mode = "RGBA"
  714. else:
  715. self.palette.palette = self.im.getpalette(
  716. self.palette.mode, self.palette.mode
  717. )
  718. if self._im is not None:
  719. return self.im.pixel_access(self.readonly)
  720. return None
  721. def verify(self) -> None:
  722. """
  723. Verifies the contents of a file. For data read from a file, this
  724. method attempts to determine if the file is broken, without
  725. actually decoding the image data. If this method finds any
  726. problems, it raises suitable exceptions. If you need to load
  727. the image after using this method, you must reopen the image
  728. file.
  729. """
  730. pass
  731. def convert(
  732. self,
  733. mode: str | None = None,
  734. matrix: tuple[float, ...] | None = None,
  735. dither: Dither | None = None,
  736. palette: Palette = Palette.WEB,
  737. colors: int = 256,
  738. ) -> Image:
  739. """
  740. Returns a converted copy of this image. For the "P" mode, this
  741. method translates pixels through the palette. If mode is
  742. omitted, a mode is chosen so that all information in the image
  743. and the palette can be represented without a palette.
  744. This supports all possible conversions between "L", "RGB" and "CMYK". The
  745. ``matrix`` argument only supports "L" and "RGB".
  746. When translating a color image to grayscale (mode "L"),
  747. the library uses the ITU-R 601-2 luma transform::
  748. L = R * 299/1000 + G * 587/1000 + B * 114/1000
  749. The default method of converting a grayscale ("L") or "RGB"
  750. image into a bilevel (mode "1") image uses Floyd-Steinberg
  751. dither to approximate the original image luminosity levels. If
  752. dither is ``None``, all values larger than 127 are set to 255 (white),
  753. all other values to 0 (black). To use other thresholds, use the
  754. :py:meth:`~PIL.Image.Image.point` method.
  755. When converting from "RGBA" to "P" without a ``matrix`` argument,
  756. this passes the operation to :py:meth:`~PIL.Image.Image.quantize`,
  757. and ``dither`` and ``palette`` are ignored.
  758. When converting from "PA", if an "RGBA" palette is present, the alpha
  759. channel from the image will be used instead of the values from the palette.
  760. :param mode: The requested mode. See: :ref:`concept-modes`.
  761. :param matrix: An optional conversion matrix. If given, this
  762. should be 4- or 12-tuple containing floating point values.
  763. :param dither: Dithering method, used when converting from
  764. mode "RGB" to "P" or from "RGB" or "L" to "1".
  765. Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG`
  766. (default). Note that this is not used when ``matrix`` is supplied.
  767. :param palette: Palette to use when converting from mode "RGB"
  768. to "P". Available palettes are :data:`Palette.WEB` or
  769. :data:`Palette.ADAPTIVE`.
  770. :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE`
  771. palette. Defaults to 256.
  772. :rtype: :py:class:`~PIL.Image.Image`
  773. :returns: An :py:class:`~PIL.Image.Image` object.
  774. """
  775. self.load()
  776. has_transparency = "transparency" in self.info
  777. if not mode and self.mode == "P":
  778. # determine default mode
  779. if self.palette:
  780. mode = self.palette.mode
  781. else:
  782. mode = "RGB"
  783. if mode == "RGB" and has_transparency:
  784. mode = "RGBA"
  785. if not mode or (mode == self.mode and not matrix):
  786. return self.copy()
  787. if matrix:
  788. # matrix conversion
  789. if mode not in ("L", "RGB"):
  790. msg = "illegal conversion"
  791. raise ValueError(msg)
  792. im = self.im.convert_matrix(mode, matrix)
  793. new_im = self._new(im)
  794. if has_transparency and self.im.bands == 3:
  795. transparency = new_im.info["transparency"]
  796. def convert_transparency(
  797. m: tuple[float, ...], v: tuple[int, int, int]
  798. ) -> int:
  799. value = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5
  800. return max(0, min(255, int(value)))
  801. if mode == "L":
  802. transparency = convert_transparency(matrix, transparency)
  803. elif len(mode) == 3:
  804. transparency = tuple(
  805. convert_transparency(matrix[i * 4 : i * 4 + 4], transparency)
  806. for i in range(len(transparency))
  807. )
  808. new_im.info["transparency"] = transparency
  809. return new_im
  810. if self.mode == "RGBA":
  811. if mode == "P":
  812. return self.quantize(colors)
  813. elif mode == "PA":
  814. r, g, b, a = self.split()
  815. rgb = merge("RGB", (r, g, b))
  816. p = rgb.quantize(colors)
  817. return merge("PA", (p, a))
  818. trns = None
  819. delete_trns = False
  820. # transparency handling
  821. if has_transparency:
  822. if (self.mode in ("1", "L", "I", "I;16") and mode in ("LA", "RGBA")) or (
  823. self.mode == "RGB" and mode in ("La", "LA", "RGBa", "RGBA")
  824. ):
  825. # Use transparent conversion to promote from transparent
  826. # color to an alpha channel.
  827. new_im = self._new(
  828. self.im.convert_transparent(mode, self.info["transparency"])
  829. )
  830. del new_im.info["transparency"]
  831. return new_im
  832. elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"):
  833. t = self.info["transparency"]
  834. if isinstance(t, bytes):
  835. # Dragons. This can't be represented by a single color
  836. warnings.warn(
  837. "Palette images with Transparency expressed in bytes should be "
  838. "converted to RGBA images"
  839. )
  840. delete_trns = True
  841. else:
  842. # get the new transparency color.
  843. # use existing conversions
  844. trns_im = new(self.mode, (1, 1))
  845. if self.mode == "P":
  846. assert self.palette is not None
  847. trns_im.putpalette(self.palette, self.palette.mode)
  848. if isinstance(t, tuple):
  849. err = "Couldn't allocate a palette color for transparency"
  850. assert trns_im.palette is not None
  851. try:
  852. t = trns_im.palette.getcolor(t, self)
  853. except ValueError as e:
  854. if str(e) == "cannot allocate more than 256 colors":
  855. # If all 256 colors are in use,
  856. # then there is no need for transparency
  857. t = None
  858. else:
  859. raise ValueError(err) from e
  860. if t is None:
  861. trns = None
  862. else:
  863. trns_im.putpixel((0, 0), t)
  864. if mode in ("L", "RGB"):
  865. trns_im = trns_im.convert(mode)
  866. else:
  867. # can't just retrieve the palette number, got to do it
  868. # after quantization.
  869. trns_im = trns_im.convert("RGB")
  870. trns = trns_im.getpixel((0, 0))
  871. elif self.mode == "P" and mode in ("LA", "PA", "RGBA"):
  872. t = self.info["transparency"]
  873. delete_trns = True
  874. if isinstance(t, bytes):
  875. self.im.putpalettealphas(t)
  876. elif isinstance(t, int):
  877. self.im.putpalettealpha(t, 0)
  878. else:
  879. msg = "Transparency for P mode should be bytes or int"
  880. raise ValueError(msg)
  881. if mode == "P" and palette == Palette.ADAPTIVE:
  882. im = self.im.quantize(colors)
  883. new_im = self._new(im)
  884. from . import ImagePalette
  885. new_im.palette = ImagePalette.ImagePalette(
  886. "RGB", new_im.im.getpalette("RGB")
  887. )
  888. if delete_trns:
  889. # This could possibly happen if we requantize to fewer colors.
  890. # The transparency would be totally off in that case.
  891. del new_im.info["transparency"]
  892. if trns is not None:
  893. try:
  894. new_im.info["transparency"] = new_im.palette.getcolor(
  895. cast(tuple[int, ...], trns), # trns was converted to RGB
  896. new_im,
  897. )
  898. except Exception:
  899. # if we can't make a transparent color, don't leave the old
  900. # transparency hanging around to mess us up.
  901. del new_im.info["transparency"]
  902. warnings.warn("Couldn't allocate palette entry for transparency")
  903. return new_im
  904. if "LAB" in (self.mode, mode):
  905. im = self
  906. if mode == "LAB":
  907. if im.mode not in ("RGB", "RGBA", "RGBX"):
  908. im = im.convert("RGBA")
  909. other_mode = im.mode
  910. else:
  911. other_mode = mode
  912. if other_mode in ("RGB", "RGBA", "RGBX"):
  913. from . import ImageCms
  914. srgb = ImageCms.createProfile("sRGB")
  915. lab = ImageCms.createProfile("LAB")
  916. profiles = [lab, srgb] if im.mode == "LAB" else [srgb, lab]
  917. transform = ImageCms.buildTransform(
  918. profiles[0], profiles[1], im.mode, mode
  919. )
  920. return transform.apply(im)
  921. # colorspace conversion
  922. if dither is None:
  923. dither = Dither.FLOYDSTEINBERG
  924. try:
  925. im = self.im.convert(mode, dither)
  926. except ValueError:
  927. try:
  928. # normalize source image and try again
  929. modebase = getmodebase(self.mode)
  930. if modebase == self.mode:
  931. raise
  932. im = self.im.convert(modebase)
  933. im = im.convert(mode, dither)
  934. except KeyError as e:
  935. msg = "illegal conversion"
  936. raise ValueError(msg) from e
  937. new_im = self._new(im)
  938. if mode in ("P", "PA") and palette != Palette.ADAPTIVE:
  939. from . import ImagePalette
  940. new_im.palette = ImagePalette.ImagePalette("RGB", im.getpalette("RGB"))
  941. if delete_trns:
  942. # crash fail if we leave a bytes transparency in an rgb/l mode.
  943. del new_im.info["transparency"]
  944. if trns is not None:
  945. if new_im.mode == "P" and new_im.palette:
  946. try:
  947. new_im.info["transparency"] = new_im.palette.getcolor(
  948. cast(tuple[int, ...], trns), new_im # trns was converted to RGB
  949. )
  950. except ValueError as e:
  951. del new_im.info["transparency"]
  952. if str(e) != "cannot allocate more than 256 colors":
  953. # If all 256 colors are in use,
  954. # then there is no need for transparency
  955. warnings.warn(
  956. "Couldn't allocate palette entry for transparency"
  957. )
  958. else:
  959. new_im.info["transparency"] = trns
  960. return new_im
  961. def quantize(
  962. self,
  963. colors: int = 256,
  964. method: int | None = None,
  965. kmeans: int = 0,
  966. palette: Image | None = None,
  967. dither: Dither = Dither.FLOYDSTEINBERG,
  968. ) -> Image:
  969. """
  970. Convert the image to 'P' mode with the specified number
  971. of colors.
  972. :param colors: The desired number of colors, <= 256
  973. :param method: :data:`Quantize.MEDIANCUT` (median cut),
  974. :data:`Quantize.MAXCOVERAGE` (maximum coverage),
  975. :data:`Quantize.FASTOCTREE` (fast octree),
  976. :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support
  977. using :py:func:`PIL.features.check_feature` with
  978. ``feature="libimagequant"``).
  979. By default, :data:`Quantize.MEDIANCUT` will be used.
  980. The exception to this is RGBA images. :data:`Quantize.MEDIANCUT`
  981. and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so
  982. :data:`Quantize.FASTOCTREE` is used by default instead.
  983. :param kmeans: Integer greater than or equal to zero.
  984. :param palette: Quantize to the palette of given
  985. :py:class:`PIL.Image.Image`.
  986. :param dither: Dithering method, used when converting from
  987. mode "RGB" to "P" or from "RGB" or "L" to "1".
  988. Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG`
  989. (default).
  990. :returns: A new image
  991. """
  992. self.load()
  993. if method is None:
  994. # defaults:
  995. method = Quantize.MEDIANCUT
  996. if self.mode == "RGBA":
  997. method = Quantize.FASTOCTREE
  998. if self.mode == "RGBA" and method not in (
  999. Quantize.FASTOCTREE,
  1000. Quantize.LIBIMAGEQUANT,
  1001. ):
  1002. # Caller specified an invalid mode.
  1003. msg = (
  1004. "Fast Octree (method == 2) and libimagequant (method == 3) "
  1005. "are the only valid methods for quantizing RGBA images"
  1006. )
  1007. raise ValueError(msg)
  1008. if palette:
  1009. # use palette from reference image
  1010. palette.load()
  1011. if palette.mode != "P":
  1012. msg = "bad mode for palette image"
  1013. raise ValueError(msg)
  1014. if self.mode not in {"RGB", "L"}:
  1015. msg = "only RGB or L mode images can be quantized to a palette"
  1016. raise ValueError(msg)
  1017. im = self.im.convert("P", dither, palette.im)
  1018. new_im = self._new(im)
  1019. assert palette.palette is not None
  1020. new_im.palette = palette.palette.copy()
  1021. return new_im
  1022. if kmeans < 0:
  1023. msg = "kmeans must not be negative"
  1024. raise ValueError(msg)
  1025. im = self._new(self.im.quantize(colors, method, kmeans))
  1026. from . import ImagePalette
  1027. mode = im.im.getpalettemode()
  1028. palette_data = im.im.getpalette(mode, mode)[: colors * len(mode)]
  1029. im.palette = ImagePalette.ImagePalette(mode, palette_data)
  1030. return im
  1031. def copy(self) -> Image:
  1032. """
  1033. Copies this image. Use this method if you wish to paste things
  1034. into an image, but still retain the original.
  1035. :rtype: :py:class:`~PIL.Image.Image`
  1036. :returns: An :py:class:`~PIL.Image.Image` object.
  1037. """
  1038. self.load()
  1039. return self._new(self.im.copy())
  1040. __copy__ = copy
  1041. def crop(self, box: tuple[float, float, float, float] | None = None) -> Image:
  1042. """
  1043. Returns a rectangular region from this image. The box is a
  1044. 4-tuple defining the left, upper, right, and lower pixel
  1045. coordinate. See :ref:`coordinate-system`.
  1046. Note: Prior to Pillow 3.4.0, this was a lazy operation.
  1047. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
  1048. :rtype: :py:class:`~PIL.Image.Image`
  1049. :returns: An :py:class:`~PIL.Image.Image` object.
  1050. """
  1051. if box is None:
  1052. return self.copy()
  1053. if box[2] < box[0]:
  1054. msg = "Coordinate 'right' is less than 'left'"
  1055. raise ValueError(msg)
  1056. elif box[3] < box[1]:
  1057. msg = "Coordinate 'lower' is less than 'upper'"
  1058. raise ValueError(msg)
  1059. self.load()
  1060. return self._new(self._crop(self.im, box))
  1061. def _crop(
  1062. self, im: core.ImagingCore, box: tuple[float, float, float, float]
  1063. ) -> core.ImagingCore:
  1064. """
  1065. Returns a rectangular region from the core image object im.
  1066. This is equivalent to calling im.crop((x0, y0, x1, y1)), but
  1067. includes additional sanity checks.
  1068. :param im: a core image object
  1069. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
  1070. :returns: A core image object.
  1071. """
  1072. x0, y0, x1, y1 = map(int, map(round, box))
  1073. absolute_values = (abs(x1 - x0), abs(y1 - y0))
  1074. _decompression_bomb_check(absolute_values)
  1075. return im.crop((x0, y0, x1, y1))
  1076. def draft(
  1077. self, mode: str | None, size: tuple[int, int] | None
  1078. ) -> tuple[str, tuple[int, int, float, float]] | None:
  1079. """
  1080. Configures the image file loader so it returns a version of the
  1081. image that as closely as possible matches the given mode and
  1082. size. For example, you can use this method to convert a color
  1083. JPEG to grayscale while loading it.
  1084. If any changes are made, returns a tuple with the chosen ``mode`` and
  1085. ``box`` with coordinates of the original image within the altered one.
  1086. Note that this method modifies the :py:class:`~PIL.Image.Image` object
  1087. in place. If the image has already been loaded, this method has no
  1088. effect.
  1089. Note: This method is not implemented for most images. It is
  1090. currently implemented only for JPEG and MPO images.
  1091. :param mode: The requested mode.
  1092. :param size: The requested size in pixels, as a 2-tuple:
  1093. (width, height).
  1094. """
  1095. pass
  1096. def filter(self, filter: ImageFilter.Filter | type[ImageFilter.Filter]) -> Image:
  1097. """
  1098. Filters this image using the given filter. For a list of
  1099. available filters, see the :py:mod:`~PIL.ImageFilter` module.
  1100. :param filter: Filter kernel.
  1101. :returns: An :py:class:`~PIL.Image.Image` object."""
  1102. from . import ImageFilter
  1103. self.load()
  1104. if callable(filter):
  1105. filter = filter()
  1106. if not hasattr(filter, "filter"):
  1107. msg = "filter argument should be ImageFilter.Filter instance or class"
  1108. raise TypeError(msg)
  1109. multiband = isinstance(filter, ImageFilter.MultibandFilter)
  1110. if self.im.bands == 1 or multiband:
  1111. return self._new(filter.filter(self.im))
  1112. ims = [
  1113. self._new(filter.filter(self.im.getband(c))) for c in range(self.im.bands)
  1114. ]
  1115. return merge(self.mode, ims)
  1116. def getbands(self) -> tuple[str, ...]:
  1117. """
  1118. Returns a tuple containing the name of each band in this image.
  1119. For example, ``getbands`` on an RGB image returns ("R", "G", "B").
  1120. :returns: A tuple containing band names.
  1121. :rtype: tuple
  1122. """
  1123. return ImageMode.getmode(self.mode).bands
  1124. def getbbox(self, *, alpha_only: bool = True) -> tuple[int, int, int, int] | None:
  1125. """
  1126. Calculates the bounding box of the non-zero regions in the
  1127. image.
  1128. :param alpha_only: Optional flag, defaulting to ``True``.
  1129. If ``True`` and the image has an alpha channel, trim transparent pixels.
  1130. Otherwise, trim pixels when all channels are zero.
  1131. Keyword-only argument.
  1132. :returns: The bounding box is returned as a 4-tuple defining the
  1133. left, upper, right, and lower pixel coordinate. See
  1134. :ref:`coordinate-system`. If the image is completely empty, this
  1135. method returns None.
  1136. """
  1137. self.load()
  1138. return self.im.getbbox(alpha_only)
  1139. def getcolors(
  1140. self, maxcolors: int = 256
  1141. ) -> list[tuple[int, tuple[int, ...]]] | list[tuple[int, float]] | None:
  1142. """
  1143. Returns a list of colors used in this image.
  1144. The colors will be in the image's mode. For example, an RGB image will
  1145. return a tuple of (red, green, blue) color values, and a P image will
  1146. return the index of the color in the palette.
  1147. :param maxcolors: Maximum number of colors. If this number is
  1148. exceeded, this method returns None. The default limit is
  1149. 256 colors.
  1150. :returns: An unsorted list of (count, pixel) values.
  1151. """
  1152. self.load()
  1153. if self.mode in ("1", "L", "P"):
  1154. h = self.im.histogram()
  1155. out: list[tuple[int, float]] = [(h[i], i) for i in range(256) if h[i]]
  1156. if len(out) > maxcolors:
  1157. return None
  1158. return out
  1159. return self.im.getcolors(maxcolors)
  1160. def getdata(self, band: int | None = None) -> core.ImagingCore:
  1161. """
  1162. Returns the contents of this image as a sequence object
  1163. containing pixel values. The sequence object is flattened, so
  1164. that values for line one follow directly after the values of
  1165. line zero, and so on.
  1166. Note that the sequence object returned by this method is an
  1167. internal PIL data type, which only supports certain sequence
  1168. operations. To convert it to an ordinary sequence (e.g. for
  1169. printing), use ``list(im.getdata())``.
  1170. :param band: What band to return. The default is to return
  1171. all bands. To return a single band, pass in the index
  1172. value (e.g. 0 to get the "R" band from an "RGB" image).
  1173. :returns: A sequence-like object.
  1174. """
  1175. deprecate("Image.Image.getdata", 14, "get_flattened_data")
  1176. self.load()
  1177. if band is not None:
  1178. return self.im.getband(band)
  1179. return self.im # could be abused
  1180. def get_flattened_data(
  1181. self, band: int | None = None
  1182. ) -> tuple[tuple[int, ...], ...] | tuple[float, ...]:
  1183. """
  1184. Returns the contents of this image as a tuple containing pixel values.
  1185. The sequence object is flattened, so that values for line one follow
  1186. directly after the values of line zero, and so on.
  1187. :param band: What band to return. The default is to return
  1188. all bands. To return a single band, pass in the index
  1189. value (e.g. 0 to get the "R" band from an "RGB" image).
  1190. :returns: A tuple containing pixel values.
  1191. """
  1192. self.load()
  1193. if band is not None:
  1194. return tuple(self.im.getband(band))
  1195. return tuple(self.im)
  1196. def getextrema(self) -> tuple[float, float] | tuple[tuple[int, int], ...]:
  1197. """
  1198. Gets the minimum and maximum pixel values for each band in
  1199. the image.
  1200. :returns: For a single-band image, a 2-tuple containing the
  1201. minimum and maximum pixel value. For a multi-band image,
  1202. a tuple containing one 2-tuple for each band.
  1203. """
  1204. self.load()
  1205. if self.im.bands > 1:
  1206. return tuple(self.im.getband(i).getextrema() for i in range(self.im.bands))
  1207. return self.im.getextrema()
  1208. def getxmp(self) -> dict[str, Any]:
  1209. """
  1210. Returns a dictionary containing the XMP tags.
  1211. Requires defusedxml to be installed.
  1212. :returns: XMP tags in a dictionary.
  1213. """
  1214. def get_name(tag: str) -> str:
  1215. return re.sub("^{[^}]+}", "", tag)
  1216. def get_value(element: Element) -> str | dict[str, Any] | None:
  1217. value: dict[str, Any] = {get_name(k): v for k, v in element.attrib.items()}
  1218. children = list(element)
  1219. if children:
  1220. for child in children:
  1221. name = get_name(child.tag)
  1222. child_value = get_value(child)
  1223. if name in value:
  1224. if not isinstance(value[name], list):
  1225. value[name] = [value[name]]
  1226. value[name].append(child_value)
  1227. else:
  1228. value[name] = child_value
  1229. elif value:
  1230. if element.text:
  1231. value["text"] = element.text
  1232. else:
  1233. return element.text
  1234. return value
  1235. if ElementTree is None:
  1236. warnings.warn("XMP data cannot be read without defusedxml dependency")
  1237. return {}
  1238. if "xmp" not in self.info:
  1239. return {}
  1240. root = ElementTree.fromstring(self.info["xmp"].rstrip(b"\x00 "))
  1241. return {get_name(root.tag): get_value(root)}
  1242. def getexif(self) -> Exif:
  1243. """
  1244. Gets EXIF data from the image.
  1245. :returns: an :py:class:`~PIL.Image.Exif` object.
  1246. """
  1247. if self._exif is None:
  1248. self._exif = Exif()
  1249. elif self._exif._loaded:
  1250. return self._exif
  1251. self._exif._loaded = True
  1252. exif_info = self.info.get("exif")
  1253. if exif_info is None:
  1254. if "Raw profile type exif" in self.info:
  1255. exif_info = bytes.fromhex(
  1256. "".join(self.info["Raw profile type exif"].split("\n")[3:])
  1257. )
  1258. elif hasattr(self, "tag_v2"):
  1259. from . import TiffImagePlugin
  1260. assert isinstance(self, TiffImagePlugin.TiffImageFile)
  1261. self._exif.bigtiff = self.tag_v2._bigtiff
  1262. self._exif.endian = self.tag_v2._endian
  1263. assert self.fp is not None
  1264. self._exif.load_from_fp(self.fp, self.tag_v2._offset)
  1265. if exif_info is not None:
  1266. self._exif.load(exif_info)
  1267. # XMP tags
  1268. if ExifTags.Base.Orientation not in self._exif:
  1269. xmp_tags = self.info.get("XML:com.adobe.xmp")
  1270. pattern: str | bytes = r'tiff:Orientation(="|>)([0-9])'
  1271. if not xmp_tags and (xmp_tags := self.info.get("xmp")):
  1272. pattern = rb'tiff:Orientation(="|>)([0-9])'
  1273. if xmp_tags:
  1274. match = re.search(pattern, xmp_tags)
  1275. if match:
  1276. self._exif[ExifTags.Base.Orientation] = int(match[2])
  1277. return self._exif
  1278. def _reload_exif(self) -> None:
  1279. if self._exif is None or not self._exif._loaded:
  1280. return
  1281. self._exif._loaded = False
  1282. self.getexif()
  1283. def get_child_images(self) -> list[ImageFile.ImageFile]:
  1284. from . import ImageFile
  1285. deprecate("Image.Image.get_child_images", 13)
  1286. return ImageFile.ImageFile.get_child_images(self) # type: ignore[arg-type]
  1287. def getim(self) -> CapsuleType:
  1288. """
  1289. Returns a capsule that points to the internal image memory.
  1290. :returns: A capsule object.
  1291. """
  1292. self.load()
  1293. return self.im.ptr
  1294. def getpalette(self, rawmode: str | None = "RGB") -> list[int] | None:
  1295. """
  1296. Returns the image palette as a list.
  1297. :param rawmode: The mode in which to return the palette. ``None`` will
  1298. return the palette in its current mode.
  1299. .. versionadded:: 9.1.0
  1300. :returns: A list of color values [r, g, b, ...], or None if the
  1301. image has no palette.
  1302. """
  1303. self.load()
  1304. try:
  1305. mode = self.im.getpalettemode()
  1306. except ValueError:
  1307. return None # no palette
  1308. if rawmode is None:
  1309. rawmode = mode
  1310. return list(self.im.getpalette(mode, rawmode))
  1311. @property
  1312. def has_transparency_data(self) -> bool:
  1313. """
  1314. Determine if an image has transparency data, whether in the form of an
  1315. alpha channel, a palette with an alpha channel, or a "transparency" key
  1316. in the info dictionary.
  1317. Note the image might still appear solid, if all of the values shown
  1318. within are opaque.
  1319. :returns: A boolean.
  1320. """
  1321. if (
  1322. self.mode in ("LA", "La", "PA", "RGBA", "RGBa")
  1323. or "transparency" in self.info
  1324. ):
  1325. return True
  1326. if self.mode == "P":
  1327. assert self.palette is not None
  1328. return self.palette.mode.endswith("A")
  1329. return False
  1330. def apply_transparency(self) -> None:
  1331. """
  1332. If a P mode image has a "transparency" key in the info dictionary,
  1333. remove the key and instead apply the transparency to the palette.
  1334. Otherwise, the image is unchanged.
  1335. """
  1336. if self.mode != "P" or "transparency" not in self.info:
  1337. return
  1338. from . import ImagePalette
  1339. palette = self.getpalette("RGBA")
  1340. assert palette is not None
  1341. transparency = self.info["transparency"]
  1342. if isinstance(transparency, bytes):
  1343. for i, alpha in enumerate(transparency):
  1344. palette[i * 4 + 3] = alpha
  1345. else:
  1346. palette[transparency * 4 + 3] = 0
  1347. self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette))
  1348. self.palette.dirty = 1
  1349. del self.info["transparency"]
  1350. def getpixel(
  1351. self, xy: tuple[int, int] | list[int]
  1352. ) -> float | tuple[int, ...] | None:
  1353. """
  1354. Returns the pixel value at a given position.
  1355. :param xy: The coordinate, given as (x, y). See
  1356. :ref:`coordinate-system`.
  1357. :returns: The pixel value. If the image is a multi-layer image,
  1358. this method returns a tuple.
  1359. """
  1360. self.load()
  1361. return self.im.getpixel(tuple(xy))
  1362. def getprojection(self) -> tuple[list[int], list[int]]:
  1363. """
  1364. Get projection to x and y axes
  1365. :returns: Two sequences, indicating where there are non-zero
  1366. pixels along the X-axis and the Y-axis, respectively.
  1367. """
  1368. self.load()
  1369. x, y = self.im.getprojection()
  1370. return list(x), list(y)
  1371. def histogram(
  1372. self, mask: Image | None = None, extrema: tuple[float, float] | None = None
  1373. ) -> list[int]:
  1374. """
  1375. Returns a histogram for the image. The histogram is returned as a
  1376. list of pixel counts, one for each pixel value in the source
  1377. image. Counts are grouped into 256 bins for each band, even if
  1378. the image has more than 8 bits per band. If the image has more
  1379. than one band, the histograms for all bands are concatenated (for
  1380. example, the histogram for an "RGB" image contains 768 values).
  1381. A bilevel image (mode "1") is treated as a grayscale ("L") image
  1382. by this method.
  1383. If a mask is provided, the method returns a histogram for those
  1384. parts of the image where the mask image is non-zero. The mask
  1385. image must have the same size as the image, and be either a
  1386. bi-level image (mode "1") or a grayscale image ("L").
  1387. :param mask: An optional mask.
  1388. :param extrema: An optional tuple of manually-specified extrema.
  1389. :returns: A list containing pixel counts.
  1390. """
  1391. self.load()
  1392. if mask:
  1393. mask.load()
  1394. return self.im.histogram((0, 0), mask.im)
  1395. if self.mode in ("I", "F"):
  1396. return self.im.histogram(
  1397. extrema if extrema is not None else self.getextrema()
  1398. )
  1399. return self.im.histogram()
  1400. def entropy(
  1401. self, mask: Image | None = None, extrema: tuple[float, float] | None = None
  1402. ) -> float:
  1403. """
  1404. Calculates and returns the entropy for the image.
  1405. A bilevel image (mode "1") is treated as a grayscale ("L")
  1406. image by this method.
  1407. If a mask is provided, the method employs the histogram for
  1408. those parts of the image where the mask image is non-zero.
  1409. The mask image must have the same size as the image, and be
  1410. either a bi-level image (mode "1") or a grayscale image ("L").
  1411. :param mask: An optional mask.
  1412. :param extrema: An optional tuple of manually-specified extrema.
  1413. :returns: A float value representing the image entropy
  1414. """
  1415. self.load()
  1416. if mask:
  1417. mask.load()
  1418. return self.im.entropy((0, 0), mask.im)
  1419. if self.mode in ("I", "F"):
  1420. return self.im.entropy(
  1421. extrema if extrema is not None else self.getextrema()
  1422. )
  1423. return self.im.entropy()
  1424. def paste(
  1425. self,
  1426. im: Image | str | float | tuple[float, ...],
  1427. box: Image | tuple[int, int, int, int] | tuple[int, int] | None = None,
  1428. mask: Image | None = None,
  1429. ) -> None:
  1430. """
  1431. Pastes another image into this image. The box argument is either
  1432. a 2-tuple giving the upper left corner, a 4-tuple defining the
  1433. left, upper, right, and lower pixel coordinate, or None (same as
  1434. (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size
  1435. of the pasted image must match the size of the region.
  1436. If the modes don't match, the pasted image is converted to the mode of
  1437. this image (see the :py:meth:`~PIL.Image.Image.convert` method for
  1438. details).
  1439. Instead of an image, the source can be a integer or tuple
  1440. containing pixel values. The method then fills the region
  1441. with the given color. When creating RGB images, you can
  1442. also use color strings as supported by the ImageColor module. See
  1443. :ref:`colors` for more information.
  1444. If a mask is given, this method updates only the regions
  1445. indicated by the mask. You can use either "1", "L", "LA", "RGBA"
  1446. or "RGBa" images (if present, the alpha band is used as mask).
  1447. Where the mask is 255, the given image is copied as is. Where
  1448. the mask is 0, the current value is preserved. Intermediate
  1449. values will mix the two images together, including their alpha
  1450. channels if they have them.
  1451. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to
  1452. combine images with respect to their alpha channels.
  1453. :param im: Source image or pixel value (integer, float or tuple).
  1454. :param box: An optional 4-tuple giving the region to paste into.
  1455. If a 2-tuple is used instead, it's treated as the upper left
  1456. corner. If omitted or None, the source is pasted into the
  1457. upper left corner.
  1458. If an image is given as the second argument and there is no
  1459. third, the box defaults to (0, 0), and the second argument
  1460. is interpreted as a mask image.
  1461. :param mask: An optional mask image.
  1462. """
  1463. if isinstance(box, Image):
  1464. if mask is not None:
  1465. msg = "If using second argument as mask, third argument must be None"
  1466. raise ValueError(msg)
  1467. # abbreviated paste(im, mask) syntax
  1468. mask = box
  1469. box = None
  1470. if box is None:
  1471. box = (0, 0)
  1472. if len(box) == 2:
  1473. # upper left corner given; get size from image or mask
  1474. if isinstance(im, Image):
  1475. size = im.size
  1476. elif isinstance(mask, Image):
  1477. size = mask.size
  1478. else:
  1479. # FIXME: use self.size here?
  1480. msg = "cannot determine region size; use 4-item box"
  1481. raise ValueError(msg)
  1482. box += (box[0] + size[0], box[1] + size[1])
  1483. source: core.ImagingCore | str | float | tuple[float, ...]
  1484. if isinstance(im, str):
  1485. from . import ImageColor
  1486. source = ImageColor.getcolor(im, self.mode)
  1487. elif isinstance(im, Image):
  1488. im.load()
  1489. if self.mode != im.mode:
  1490. if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"):
  1491. # should use an adapter for this!
  1492. im = im.convert(self.mode)
  1493. source = im.im
  1494. else:
  1495. source = im
  1496. self._ensure_mutable()
  1497. if mask:
  1498. mask.load()
  1499. self.im.paste(source, box, mask.im)
  1500. else:
  1501. self.im.paste(source, box)
  1502. def alpha_composite(
  1503. self, im: Image, dest: Sequence[int] = (0, 0), source: Sequence[int] = (0, 0)
  1504. ) -> None:
  1505. """'In-place' analog of Image.alpha_composite. Composites an image
  1506. onto this image.
  1507. :param im: image to composite over this one
  1508. :param dest: Optional 2 tuple (left, top) specifying the upper
  1509. left corner in this (destination) image.
  1510. :param source: Optional 2 (left, top) tuple for the upper left
  1511. corner in the overlay source image, or 4 tuple (left, top, right,
  1512. bottom) for the bounds of the source rectangle
  1513. Performance Note: Not currently implemented in-place in the core layer.
  1514. """
  1515. if not isinstance(source, (list, tuple)):
  1516. msg = "Source must be a list or tuple"
  1517. raise ValueError(msg)
  1518. if not isinstance(dest, (list, tuple)):
  1519. msg = "Destination must be a list or tuple"
  1520. raise ValueError(msg)
  1521. if len(source) == 4:
  1522. overlay_crop_box = tuple(source)
  1523. elif len(source) == 2:
  1524. overlay_crop_box = tuple(source) + im.size
  1525. else:
  1526. msg = "Source must be a sequence of length 2 or 4"
  1527. raise ValueError(msg)
  1528. if not len(dest) == 2:
  1529. msg = "Destination must be a sequence of length 2"
  1530. raise ValueError(msg)
  1531. if min(source) < 0:
  1532. msg = "Source must be non-negative"
  1533. raise ValueError(msg)
  1534. # over image, crop if it's not the whole image.
  1535. if overlay_crop_box == (0, 0) + im.size:
  1536. overlay = im
  1537. else:
  1538. overlay = im.crop(overlay_crop_box)
  1539. # target for the paste
  1540. box = tuple(dest) + (dest[0] + overlay.width, dest[1] + overlay.height)
  1541. # destination image. don't copy if we're using the whole image.
  1542. if box == (0, 0) + self.size:
  1543. background = self
  1544. else:
  1545. background = self.crop(box)
  1546. result = alpha_composite(background, overlay)
  1547. self.paste(result, box)
  1548. def point(
  1549. self,
  1550. lut: (
  1551. Sequence[float]
  1552. | NumpyArray
  1553. | Callable[[int], float]
  1554. | Callable[[ImagePointTransform], ImagePointTransform | float]
  1555. | ImagePointHandler
  1556. ),
  1557. mode: str | None = None,
  1558. ) -> Image:
  1559. """
  1560. Maps this image through a lookup table or function.
  1561. :param lut: A lookup table, containing 256 (or 65536 if
  1562. self.mode=="I" and mode == "L") values per band in the
  1563. image. A function can be used instead, it should take a
  1564. single argument. The function is called once for each
  1565. possible pixel value, and the resulting table is applied to
  1566. all bands of the image.
  1567. It may also be an :py:class:`~PIL.Image.ImagePointHandler`
  1568. object::
  1569. class Example(Image.ImagePointHandler):
  1570. def point(self, im: Image) -> Image:
  1571. # Return result
  1572. :param mode: Output mode (default is same as input). This can only be used if
  1573. the source image has mode "L" or "P", and the output has mode "1" or the
  1574. source image mode is "I" and the output mode is "L".
  1575. :returns: An :py:class:`~PIL.Image.Image` object.
  1576. """
  1577. self.load()
  1578. if isinstance(lut, ImagePointHandler):
  1579. return lut.point(self)
  1580. if callable(lut):
  1581. # if it isn't a list, it should be a function
  1582. if self.mode in ("I", "I;16", "F"):
  1583. # check if the function can be used with point_transform
  1584. # UNDONE wiredfool -- I think this prevents us from ever doing
  1585. # a gamma function point transform on > 8bit images.
  1586. scale, offset = _getscaleoffset(lut) # type: ignore[arg-type]
  1587. return self._new(self.im.point_transform(scale, offset))
  1588. # for other modes, convert the function to a table
  1589. flatLut = [lut(i) for i in range(256)] * self.im.bands # type: ignore[arg-type]
  1590. else:
  1591. flatLut = lut
  1592. if self.mode == "F":
  1593. # FIXME: _imaging returns a confusing error message for this case
  1594. msg = "point operation not supported for this mode"
  1595. raise ValueError(msg)
  1596. if mode != "F":
  1597. flatLut = [round(i) for i in flatLut]
  1598. return self._new(self.im.point(flatLut, mode))
  1599. def putalpha(self, alpha: Image | int) -> None:
  1600. """
  1601. Adds or replaces the alpha layer in this image. If the image
  1602. does not have an alpha layer, it's converted to "LA" or "RGBA".
  1603. The new layer must be either "L" or "1".
  1604. :param alpha: The new alpha layer. This can either be an "L" or "1"
  1605. image having the same size as this image, or an integer.
  1606. """
  1607. self._ensure_mutable()
  1608. if self.mode not in ("LA", "PA", "RGBA"):
  1609. # attempt to promote self to a matching alpha mode
  1610. try:
  1611. mode = getmodebase(self.mode) + "A"
  1612. try:
  1613. self.im.setmode(mode)
  1614. except (AttributeError, ValueError) as e:
  1615. # do things the hard way
  1616. im = self.im.convert(mode)
  1617. if im.mode not in ("LA", "PA", "RGBA"):
  1618. msg = "alpha channel could not be added"
  1619. raise ValueError(msg) from e # sanity check
  1620. self.im = im
  1621. self._mode = self.im.mode
  1622. except KeyError as e:
  1623. msg = "illegal image mode"
  1624. raise ValueError(msg) from e
  1625. if self.mode in ("LA", "PA"):
  1626. band = 1
  1627. else:
  1628. band = 3
  1629. if isinstance(alpha, Image):
  1630. # alpha layer
  1631. if alpha.mode not in ("1", "L"):
  1632. msg = "illegal image mode"
  1633. raise ValueError(msg)
  1634. alpha.load()
  1635. if alpha.mode == "1":
  1636. alpha = alpha.convert("L")
  1637. else:
  1638. # constant alpha
  1639. try:
  1640. self.im.fillband(band, alpha)
  1641. except (AttributeError, ValueError):
  1642. # do things the hard way
  1643. alpha = new("L", self.size, alpha)
  1644. else:
  1645. return
  1646. self.im.putband(alpha.im, band)
  1647. def putdata(
  1648. self,
  1649. data: Sequence[float] | Sequence[Sequence[int]] | core.ImagingCore | NumpyArray,
  1650. scale: float = 1.0,
  1651. offset: float = 0.0,
  1652. ) -> None:
  1653. """
  1654. Copies pixel data from a flattened sequence object into the image. The
  1655. values should start at the upper left corner (0, 0), continue to the
  1656. end of the line, followed directly by the first value of the second
  1657. line, and so on. Data will be read until either the image or the
  1658. sequence ends. The scale and offset values are used to adjust the
  1659. sequence values: **pixel = value*scale + offset**.
  1660. :param data: A flattened sequence object. See :ref:`colors` for more
  1661. information about values.
  1662. :param scale: An optional scale value. The default is 1.0.
  1663. :param offset: An optional offset value. The default is 0.0.
  1664. """
  1665. self._ensure_mutable()
  1666. self.im.putdata(data, scale, offset)
  1667. def putpalette(
  1668. self,
  1669. data: ImagePalette.ImagePalette | bytes | Sequence[int],
  1670. rawmode: str = "RGB",
  1671. ) -> None:
  1672. """
  1673. Attaches a palette to this image. The image must be a "P", "PA", "L"
  1674. or "LA" image.
  1675. The palette sequence must contain at most 256 colors, made up of one
  1676. integer value for each channel in the raw mode.
  1677. For example, if the raw mode is "RGB", then it can contain at most 768
  1678. values, made up of red, green and blue values for the corresponding pixel
  1679. index in the 256 colors.
  1680. If the raw mode is "RGBA", then it can contain at most 1024 values,
  1681. containing red, green, blue and alpha values.
  1682. Alternatively, an 8-bit string may be used instead of an integer sequence.
  1683. :param data: A palette sequence (either a list or a string).
  1684. :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode
  1685. that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L").
  1686. """
  1687. from . import ImagePalette
  1688. if self.mode not in ("L", "LA", "P", "PA"):
  1689. msg = "illegal image mode"
  1690. raise ValueError(msg)
  1691. if isinstance(data, ImagePalette.ImagePalette):
  1692. if data.rawmode is not None:
  1693. palette = ImagePalette.raw(data.rawmode, data.palette)
  1694. else:
  1695. palette = ImagePalette.ImagePalette(palette=data.palette)
  1696. palette.dirty = 1
  1697. else:
  1698. if not isinstance(data, bytes):
  1699. data = bytes(data)
  1700. palette = ImagePalette.raw(rawmode, data)
  1701. self._mode = "PA" if "A" in self.mode else "P"
  1702. self.palette = palette
  1703. self.palette.mode = "RGBA" if "A" in rawmode else "RGB"
  1704. self.load() # install new palette
  1705. def putpixel(
  1706. self, xy: tuple[int, int], value: float | tuple[int, ...] | list[int]
  1707. ) -> None:
  1708. """
  1709. Modifies the pixel at the given position. The color is given as
  1710. a single numerical value for single-band images, and a tuple for
  1711. multi-band images. In addition to this, RGB and RGBA tuples are
  1712. accepted for P and PA images. See :ref:`colors` for more information.
  1713. Note that this method is relatively slow. For more extensive changes,
  1714. use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`
  1715. module instead.
  1716. See:
  1717. * :py:meth:`~PIL.Image.Image.paste`
  1718. * :py:meth:`~PIL.Image.Image.putdata`
  1719. * :py:mod:`~PIL.ImageDraw`
  1720. :param xy: The pixel coordinate, given as (x, y). See
  1721. :ref:`coordinate-system`.
  1722. :param value: The pixel value.
  1723. """
  1724. self._ensure_mutable()
  1725. if (
  1726. self.mode in ("P", "PA")
  1727. and isinstance(value, (list, tuple))
  1728. and len(value) in [3, 4]
  1729. ):
  1730. # RGB or RGBA value for a P or PA image
  1731. if self.mode == "PA":
  1732. alpha = value[3] if len(value) == 4 else 255
  1733. value = value[:3]
  1734. assert self.palette is not None
  1735. palette_index = self.palette.getcolor(tuple(value), self)
  1736. value = (palette_index, alpha) if self.mode == "PA" else palette_index
  1737. return self.im.putpixel(xy, value)
  1738. def remap_palette(
  1739. self, dest_map: list[int], source_palette: bytes | bytearray | None = None
  1740. ) -> Image:
  1741. """
  1742. Rewrites the image to reorder the palette.
  1743. :param dest_map: A list of indexes into the original palette.
  1744. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))``
  1745. is the identity transform.
  1746. :param source_palette: Bytes or None.
  1747. :returns: An :py:class:`~PIL.Image.Image` object.
  1748. """
  1749. from . import ImagePalette
  1750. if self.mode not in ("L", "P"):
  1751. msg = "illegal image mode"
  1752. raise ValueError(msg)
  1753. bands = 3
  1754. palette_mode = "RGB"
  1755. if source_palette is None:
  1756. if self.mode == "P":
  1757. self.load()
  1758. palette_mode = self.im.getpalettemode()
  1759. if palette_mode == "RGBA":
  1760. bands = 4
  1761. source_palette = self.im.getpalette(palette_mode, palette_mode)
  1762. else: # L-mode
  1763. source_palette = bytearray(i // 3 for i in range(768))
  1764. elif len(source_palette) > 768:
  1765. bands = 4
  1766. palette_mode = "RGBA"
  1767. palette_bytes = b""
  1768. new_positions = [0] * 256
  1769. # pick only the used colors from the palette
  1770. for i, oldPosition in enumerate(dest_map):
  1771. palette_bytes += source_palette[
  1772. oldPosition * bands : oldPosition * bands + bands
  1773. ]
  1774. new_positions[oldPosition] = i
  1775. # replace the palette color id of all pixel with the new id
  1776. # Palette images are [0..255], mapped through a 1 or 3
  1777. # byte/color map. We need to remap the whole image
  1778. # from palette 1 to palette 2. New_positions is
  1779. # an array of indexes into palette 1. Palette 2 is
  1780. # palette 1 with any holes removed.
  1781. # We're going to leverage the convert mechanism to use the
  1782. # C code to remap the image from palette 1 to palette 2,
  1783. # by forcing the source image into 'L' mode and adding a
  1784. # mapping 'L' mode palette, then converting back to 'L'
  1785. # sans palette thus converting the image bytes, then
  1786. # assigning the optimized RGB palette.
  1787. # perf reference, 9500x4000 gif, w/~135 colors
  1788. # 14 sec prepatch, 1 sec postpatch with optimization forced.
  1789. mapping_palette = bytearray(new_positions)
  1790. m_im = self.copy()
  1791. m_im._mode = "P"
  1792. m_im.palette = ImagePalette.ImagePalette(
  1793. palette_mode, palette=mapping_palette * bands
  1794. )
  1795. # possibly set palette dirty, then
  1796. # m_im.putpalette(mapping_palette, 'L') # converts to 'P'
  1797. # or just force it.
  1798. # UNDONE -- this is part of the general issue with palettes
  1799. m_im.im.putpalette(palette_mode, palette_mode + ";L", m_im.palette.tobytes())
  1800. m_im = m_im.convert("L")
  1801. m_im.putpalette(palette_bytes, palette_mode)
  1802. m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes)
  1803. if "transparency" in self.info:
  1804. try:
  1805. m_im.info["transparency"] = dest_map.index(self.info["transparency"])
  1806. except ValueError:
  1807. if "transparency" in m_im.info:
  1808. del m_im.info["transparency"]
  1809. return m_im
  1810. def _get_safe_box(
  1811. self,
  1812. size: tuple[int, int],
  1813. resample: Resampling,
  1814. box: tuple[float, float, float, float],
  1815. ) -> tuple[int, int, int, int]:
  1816. """Expands the box so it includes adjacent pixels
  1817. that may be used by resampling with the given resampling filter.
  1818. """
  1819. filter_support = _filters_support[resample] - 0.5
  1820. scale_x = (box[2] - box[0]) / size[0]
  1821. scale_y = (box[3] - box[1]) / size[1]
  1822. support_x = filter_support * scale_x
  1823. support_y = filter_support * scale_y
  1824. return (
  1825. max(0, int(box[0] - support_x)),
  1826. max(0, int(box[1] - support_y)),
  1827. min(self.size[0], math.ceil(box[2] + support_x)),
  1828. min(self.size[1], math.ceil(box[3] + support_y)),
  1829. )
  1830. def resize(
  1831. self,
  1832. size: tuple[int, int] | list[int] | NumpyArray,
  1833. resample: int | None = None,
  1834. box: tuple[float, float, float, float] | None = None,
  1835. reducing_gap: float | None = None,
  1836. ) -> Image:
  1837. """
  1838. Returns a resized copy of this image.
  1839. :param size: The requested size in pixels, as a tuple or array:
  1840. (width, height).
  1841. :param resample: An optional resampling filter. This can be
  1842. one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`,
  1843. :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`,
  1844. :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`.
  1845. If the image has mode "1" or "P", it is always set to
  1846. :py:data:`Resampling.NEAREST`. Otherwise, the default filter is
  1847. :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`.
  1848. :param box: An optional 4-tuple of floats providing
  1849. the source image region to be scaled.
  1850. The values must be within (0, 0, width, height) rectangle.
  1851. If omitted or None, the entire source is used.
  1852. :param reducing_gap: Apply optimization by resizing the image
  1853. in two steps. First, reducing the image by integer times
  1854. using :py:meth:`~PIL.Image.Image.reduce`.
  1855. Second, resizing using regular resampling. The last step
  1856. changes size no less than by ``reducing_gap`` times.
  1857. ``reducing_gap`` may be None (no first step is performed)
  1858. or should be greater than 1.0. The bigger ``reducing_gap``,
  1859. the closer the result to the fair resampling.
  1860. The smaller ``reducing_gap``, the faster resizing.
  1861. With ``reducing_gap`` greater or equal to 3.0, the result is
  1862. indistinguishable from fair resampling in most cases.
  1863. The default value is None (no optimization).
  1864. :returns: An :py:class:`~PIL.Image.Image` object.
  1865. """
  1866. if resample is None:
  1867. resample = Resampling.BICUBIC
  1868. elif resample not in (
  1869. Resampling.NEAREST,
  1870. Resampling.BILINEAR,
  1871. Resampling.BICUBIC,
  1872. Resampling.LANCZOS,
  1873. Resampling.BOX,
  1874. Resampling.HAMMING,
  1875. ):
  1876. msg = f"Unknown resampling filter ({resample})."
  1877. filters = [
  1878. f"{filter[1]} ({filter[0]})"
  1879. for filter in (
  1880. (Resampling.NEAREST, "Image.Resampling.NEAREST"),
  1881. (Resampling.LANCZOS, "Image.Resampling.LANCZOS"),
  1882. (Resampling.BILINEAR, "Image.Resampling.BILINEAR"),
  1883. (Resampling.BICUBIC, "Image.Resampling.BICUBIC"),
  1884. (Resampling.BOX, "Image.Resampling.BOX"),
  1885. (Resampling.HAMMING, "Image.Resampling.HAMMING"),
  1886. )
  1887. ]
  1888. msg += f" Use {', '.join(filters[:-1])} or {filters[-1]}"
  1889. raise ValueError(msg)
  1890. if reducing_gap is not None and reducing_gap < 1.0:
  1891. msg = "reducing_gap must be 1.0 or greater"
  1892. raise ValueError(msg)
  1893. if box is None:
  1894. box = (0, 0) + self.size
  1895. size = tuple(size)
  1896. if self.size == size and box == (0, 0) + self.size:
  1897. return self.copy()
  1898. if self.mode in ("1", "P"):
  1899. resample = Resampling.NEAREST
  1900. if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST:
  1901. im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
  1902. im = im.resize(size, resample, box)
  1903. return im.convert(self.mode)
  1904. self.load()
  1905. if reducing_gap is not None and resample != Resampling.NEAREST:
  1906. factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1
  1907. factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1
  1908. if factor_x > 1 or factor_y > 1:
  1909. reduce_box = self._get_safe_box(size, cast(Resampling, resample), box)
  1910. factor = (factor_x, factor_y)
  1911. self = (
  1912. self.reduce(factor, box=reduce_box)
  1913. if callable(self.reduce)
  1914. else Image.reduce(self, factor, box=reduce_box)
  1915. )
  1916. box = (
  1917. (box[0] - reduce_box[0]) / factor_x,
  1918. (box[1] - reduce_box[1]) / factor_y,
  1919. (box[2] - reduce_box[0]) / factor_x,
  1920. (box[3] - reduce_box[1]) / factor_y,
  1921. )
  1922. return self._new(self.im.resize(size, resample, box))
  1923. def reduce(
  1924. self,
  1925. factor: int | tuple[int, int],
  1926. box: tuple[int, int, int, int] | None = None,
  1927. ) -> Image:
  1928. """
  1929. Returns a copy of the image reduced ``factor`` times.
  1930. If the size of the image is not dividable by ``factor``,
  1931. the resulting size will be rounded up.
  1932. :param factor: A greater than 0 integer or tuple of two integers
  1933. for width and height separately.
  1934. :param box: An optional 4-tuple of ints providing
  1935. the source image region to be reduced.
  1936. The values must be within ``(0, 0, width, height)`` rectangle.
  1937. If omitted or ``None``, the entire source is used.
  1938. """
  1939. if not isinstance(factor, (list, tuple)):
  1940. factor = (factor, factor)
  1941. if box is None:
  1942. box = (0, 0) + self.size
  1943. if factor == (1, 1) and box == (0, 0) + self.size:
  1944. return self.copy()
  1945. if self.mode in ["LA", "RGBA"]:
  1946. im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
  1947. im = im.reduce(factor, box)
  1948. return im.convert(self.mode)
  1949. self.load()
  1950. return self._new(self.im.reduce(factor, box))
  1951. def rotate(
  1952. self,
  1953. angle: float,
  1954. resample: Resampling = Resampling.NEAREST,
  1955. expand: int | bool = False,
  1956. center: tuple[float, float] | None = None,
  1957. translate: tuple[int, int] | None = None,
  1958. fillcolor: float | tuple[float, ...] | str | None = None,
  1959. ) -> Image:
  1960. """
  1961. Returns a rotated copy of this image. This method returns a
  1962. copy of this image, rotated the given number of degrees counter
  1963. clockwise around its centre.
  1964. :param angle: In degrees counter clockwise.
  1965. :param resample: An optional resampling filter. This can be
  1966. one of :py:data:`Resampling.NEAREST` (use nearest neighbour),
  1967. :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2
  1968. environment), or :py:data:`Resampling.BICUBIC` (cubic spline
  1969. interpolation in a 4x4 environment). If omitted, or if the image has
  1970. mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`.
  1971. See :ref:`concept-filters`.
  1972. :param expand: Optional expansion flag. If true, expands the output
  1973. image to make it large enough to hold the entire rotated image.
  1974. If false or omitted, make the output image the same size as the
  1975. input image. Note that the expand flag assumes rotation around
  1976. the center and no translation.
  1977. :param center: Optional center of rotation (a 2-tuple). Origin is
  1978. the upper left corner. Default is the center of the image.
  1979. :param translate: An optional post-rotate translation (a 2-tuple).
  1980. :param fillcolor: An optional color for area outside the rotated image.
  1981. :returns: An :py:class:`~PIL.Image.Image` object.
  1982. """
  1983. angle = angle % 360.0
  1984. # Fast paths regardless of filter, as long as we're not
  1985. # translating or changing the center.
  1986. if not (center or translate):
  1987. if angle == 0:
  1988. return self.copy()
  1989. if angle == 180:
  1990. return self.transpose(Transpose.ROTATE_180)
  1991. if angle in (90, 270) and (expand or self.width == self.height):
  1992. return self.transpose(
  1993. Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270
  1994. )
  1995. # Calculate the affine matrix. Note that this is the reverse
  1996. # transformation (from destination image to source) because we
  1997. # want to interpolate the (discrete) destination pixel from
  1998. # the local area around the (floating) source pixel.
  1999. # The matrix we actually want (note that it operates from the right):
  2000. # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx)
  2001. # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy)
  2002. # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1)
  2003. # The reverse matrix is thus:
  2004. # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx)
  2005. # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty)
  2006. # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1)
  2007. # In any case, the final translation may be updated at the end to
  2008. # compensate for the expand flag.
  2009. w, h = self.size
  2010. if translate is None:
  2011. post_trans = (0, 0)
  2012. else:
  2013. post_trans = translate
  2014. if center is None:
  2015. center = (w / 2, h / 2)
  2016. angle = -math.radians(angle)
  2017. matrix = [
  2018. round(math.cos(angle), 15),
  2019. round(math.sin(angle), 15),
  2020. 0.0,
  2021. round(-math.sin(angle), 15),
  2022. round(math.cos(angle), 15),
  2023. 0.0,
  2024. ]
  2025. def transform(x: float, y: float, matrix: list[float]) -> tuple[float, float]:
  2026. (a, b, c, d, e, f) = matrix
  2027. return a * x + b * y + c, d * x + e * y + f
  2028. matrix[2], matrix[5] = transform(
  2029. -center[0] - post_trans[0], -center[1] - post_trans[1], matrix
  2030. )
  2031. matrix[2] += center[0]
  2032. matrix[5] += center[1]
  2033. if expand:
  2034. # calculate output size
  2035. xx = []
  2036. yy = []
  2037. for x, y in ((0, 0), (w, 0), (w, h), (0, h)):
  2038. transformed_x, transformed_y = transform(x, y, matrix)
  2039. xx.append(transformed_x)
  2040. yy.append(transformed_y)
  2041. nw = math.ceil(max(xx)) - math.floor(min(xx))
  2042. nh = math.ceil(max(yy)) - math.floor(min(yy))
  2043. # We multiply a translation matrix from the right. Because of its
  2044. # special form, this is the same as taking the image of the
  2045. # translation vector as new translation vector.
  2046. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix)
  2047. w, h = nw, nh
  2048. return self.transform(
  2049. (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor
  2050. )
  2051. def save(
  2052. self, fp: StrOrBytesPath | IO[bytes], format: str | None = None, **params: Any
  2053. ) -> None:
  2054. """
  2055. Saves this image under the given filename. If no format is
  2056. specified, the format to use is determined from the filename
  2057. extension, if possible.
  2058. Keyword options can be used to provide additional instructions
  2059. to the writer. If a writer doesn't recognise an option, it is
  2060. silently ignored. The available options are described in the
  2061. :doc:`image format documentation
  2062. <../handbook/image-file-formats>` for each writer.
  2063. You can use a file object instead of a filename. In this case,
  2064. you must always specify the format. The file object must
  2065. implement the ``seek``, ``tell``, and ``write``
  2066. methods, and be opened in binary mode.
  2067. :param fp: A filename (string), os.PathLike object or file object.
  2068. :param format: Optional format override. If omitted, the
  2069. format to use is determined from the filename extension.
  2070. If a file object was used instead of a filename, this
  2071. parameter should always be used.
  2072. :param params: Extra parameters to the image writer. These can also be
  2073. set on the image itself through ``encoderinfo``. This is useful when
  2074. saving multiple images::
  2075. # Saving XMP data to a single image
  2076. from PIL import Image
  2077. red = Image.new("RGB", (1, 1), "#f00")
  2078. red.save("out.mpo", xmp=b"test")
  2079. # Saving XMP data to the second frame of an image
  2080. from PIL import Image
  2081. black = Image.new("RGB", (1, 1))
  2082. red = Image.new("RGB", (1, 1), "#f00")
  2083. red.encoderinfo = {"xmp": b"test"}
  2084. black.save("out.mpo", save_all=True, append_images=[red])
  2085. :returns: None
  2086. :exception ValueError: If the output format could not be determined
  2087. from the file name. Use the format option to solve this.
  2088. :exception OSError: If the file could not be written. The file
  2089. may have been created, and may contain partial data.
  2090. """
  2091. filename: str | bytes = ""
  2092. open_fp = False
  2093. if is_path(fp):
  2094. filename = os.fspath(fp)
  2095. open_fp = True
  2096. elif fp == sys.stdout:
  2097. try:
  2098. fp = sys.stdout.buffer
  2099. except AttributeError:
  2100. pass
  2101. if not filename and hasattr(fp, "name") and is_path(fp.name):
  2102. # only set the name for metadata purposes
  2103. filename = os.fspath(fp.name)
  2104. preinit()
  2105. filename_ext = os.path.splitext(filename)[1].lower()
  2106. ext = filename_ext.decode() if isinstance(filename_ext, bytes) else filename_ext
  2107. if not format:
  2108. if ext not in EXTENSION:
  2109. init()
  2110. try:
  2111. format = EXTENSION[ext]
  2112. except KeyError as e:
  2113. msg = f"unknown file extension: {ext}"
  2114. raise ValueError(msg) from e
  2115. from . import ImageFile
  2116. # may mutate self!
  2117. if isinstance(self, ImageFile.ImageFile) and os.path.abspath(
  2118. filename
  2119. ) == os.path.abspath(self.filename):
  2120. self._ensure_mutable()
  2121. else:
  2122. self.load()
  2123. save_all = params.pop("save_all", None)
  2124. self._default_encoderinfo = params
  2125. encoderinfo = getattr(self, "encoderinfo", {})
  2126. self._attach_default_encoderinfo(self)
  2127. self.encoderconfig: tuple[Any, ...] = ()
  2128. if format.upper() not in SAVE:
  2129. init()
  2130. if save_all or (
  2131. save_all is None
  2132. and params.get("append_images")
  2133. and format.upper() in SAVE_ALL
  2134. ):
  2135. save_handler = SAVE_ALL[format.upper()]
  2136. else:
  2137. save_handler = SAVE[format.upper()]
  2138. created = False
  2139. if open_fp:
  2140. created = not os.path.exists(filename)
  2141. if params.get("append", False):
  2142. # Open also for reading ("+"), because TIFF save_all
  2143. # writer needs to go back and edit the written data.
  2144. fp = builtins.open(filename, "r+b")
  2145. else:
  2146. fp = builtins.open(filename, "w+b")
  2147. else:
  2148. fp = cast(IO[bytes], fp)
  2149. try:
  2150. save_handler(self, fp, filename)
  2151. except Exception:
  2152. if open_fp:
  2153. fp.close()
  2154. if created:
  2155. try:
  2156. os.remove(filename)
  2157. except PermissionError:
  2158. pass
  2159. raise
  2160. finally:
  2161. self.encoderinfo = encoderinfo
  2162. if open_fp:
  2163. fp.close()
  2164. def _attach_default_encoderinfo(self, im: Image) -> dict[str, Any]:
  2165. encoderinfo = getattr(self, "encoderinfo", {})
  2166. self.encoderinfo = {**im._default_encoderinfo, **encoderinfo}
  2167. return encoderinfo
  2168. def seek(self, frame: int) -> None:
  2169. """
  2170. Seeks to the given frame in this sequence file. If you seek
  2171. beyond the end of the sequence, the method raises an
  2172. ``EOFError`` exception. When a sequence file is opened, the
  2173. library automatically seeks to frame 0.
  2174. See :py:meth:`~PIL.Image.Image.tell`.
  2175. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the
  2176. number of available frames.
  2177. :param frame: Frame number, starting at 0.
  2178. :exception EOFError: If the call attempts to seek beyond the end
  2179. of the sequence.
  2180. """
  2181. # overridden by file handlers
  2182. if frame != 0:
  2183. msg = "no more images in file"
  2184. raise EOFError(msg)
  2185. def show(self, title: str | None = None) -> None:
  2186. """
  2187. Displays this image. This method is mainly intended for debugging purposes.
  2188. This method calls :py:func:`PIL.ImageShow.show` internally. You can use
  2189. :py:func:`PIL.ImageShow.register` to override its default behaviour.
  2190. The image is first saved to a temporary file. By default, it will be in
  2191. PNG format.
  2192. On Unix, the image is then opened using the **xdg-open**, **display**,
  2193. **gm**, **eog** or **xv** utility, depending on which one can be found.
  2194. On macOS, the image is opened with the native Preview application.
  2195. On Windows, the image is opened with the standard PNG display utility.
  2196. :param title: Optional title to use for the image window, where possible.
  2197. """
  2198. from . import ImageShow
  2199. ImageShow.show(self, title)
  2200. def split(self) -> tuple[Image, ...]:
  2201. """
  2202. Split this image into individual bands. This method returns a
  2203. tuple of individual image bands from an image. For example,
  2204. splitting an "RGB" image creates three new images each
  2205. containing a copy of one of the original bands (red, green,
  2206. blue).
  2207. If you need only one band, :py:meth:`~PIL.Image.Image.getchannel`
  2208. method can be more convenient and faster.
  2209. :returns: A tuple containing bands.
  2210. """
  2211. self.load()
  2212. if self.im.bands == 1:
  2213. return (self.copy(),)
  2214. return tuple(map(self._new, self.im.split()))
  2215. def getchannel(self, channel: int | str) -> Image:
  2216. """
  2217. Returns an image containing a single channel of the source image.
  2218. :param channel: What channel to return. Could be index
  2219. (0 for "R" channel of "RGB") or channel name
  2220. ("A" for alpha channel of "RGBA").
  2221. :returns: An image in "L" mode.
  2222. .. versionadded:: 4.3.0
  2223. """
  2224. self.load()
  2225. if isinstance(channel, str):
  2226. try:
  2227. channel = self.getbands().index(channel)
  2228. except ValueError as e:
  2229. msg = f'The image has no channel "{channel}"'
  2230. raise ValueError(msg) from e
  2231. return self._new(self.im.getband(channel))
  2232. def tell(self) -> int:
  2233. """
  2234. Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.
  2235. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the
  2236. number of available frames.
  2237. :returns: Frame number, starting with 0.
  2238. """
  2239. return 0
  2240. def thumbnail(
  2241. self,
  2242. size: tuple[float, float],
  2243. resample: Resampling = Resampling.BICUBIC,
  2244. reducing_gap: float | None = 2.0,
  2245. ) -> None:
  2246. """
  2247. Make this image into a thumbnail. This method modifies the
  2248. image to contain a thumbnail version of itself, no larger than
  2249. the given size. This method calculates an appropriate thumbnail
  2250. size to preserve the aspect of the image, calls the
  2251. :py:meth:`~PIL.Image.Image.draft` method to configure the file reader
  2252. (where applicable), and finally resizes the image.
  2253. Note that this function modifies the :py:class:`~PIL.Image.Image`
  2254. object in place. If you need to use the full resolution image as well,
  2255. apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original
  2256. image.
  2257. :param size: The requested size in pixels, as a 2-tuple:
  2258. (width, height).
  2259. :param resample: Optional resampling filter. This can be one
  2260. of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`,
  2261. :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`,
  2262. :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`.
  2263. If omitted, it defaults to :py:data:`Resampling.BICUBIC`.
  2264. (was :py:data:`Resampling.NEAREST` prior to version 2.5.0).
  2265. See: :ref:`concept-filters`.
  2266. :param reducing_gap: Apply optimization by resizing the image
  2267. in two steps. First, reducing the image by integer times
  2268. using :py:meth:`~PIL.Image.Image.reduce` or
  2269. :py:meth:`~PIL.Image.Image.draft` for JPEG images.
  2270. Second, resizing using regular resampling. The last step
  2271. changes size no less than by ``reducing_gap`` times.
  2272. ``reducing_gap`` may be None (no first step is performed)
  2273. or should be greater than 1.0. The bigger ``reducing_gap``,
  2274. the closer the result to the fair resampling.
  2275. The smaller ``reducing_gap``, the faster resizing.
  2276. With ``reducing_gap`` greater or equal to 3.0, the result is
  2277. indistinguishable from fair resampling in most cases.
  2278. The default value is 2.0 (very close to fair resampling
  2279. while still being faster in many cases).
  2280. :returns: None
  2281. """
  2282. provided_size = tuple(map(math.floor, size))
  2283. def preserve_aspect_ratio() -> tuple[int, int] | None:
  2284. def round_aspect(number: float, key: Callable[[int], float]) -> int:
  2285. return max(min(math.floor(number), math.ceil(number), key=key), 1)
  2286. x, y = provided_size
  2287. if x >= self.width and y >= self.height:
  2288. return None
  2289. aspect = self.width / self.height
  2290. if x / y >= aspect:
  2291. x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y))
  2292. else:
  2293. y = round_aspect(
  2294. x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n)
  2295. )
  2296. return x, y
  2297. preserved_size = preserve_aspect_ratio()
  2298. if preserved_size is None:
  2299. return
  2300. final_size = preserved_size
  2301. box = None
  2302. if reducing_gap is not None:
  2303. res = self.draft(
  2304. None, (int(size[0] * reducing_gap), int(size[1] * reducing_gap))
  2305. )
  2306. if res is not None:
  2307. box = res[1]
  2308. if self.size != final_size:
  2309. im = self.resize(final_size, resample, box=box, reducing_gap=reducing_gap)
  2310. self.im = im.im
  2311. self._size = final_size
  2312. self._mode = self.im.mode
  2313. self.readonly = 0
  2314. # FIXME: the different transform methods need further explanation
  2315. # instead of bloating the method docs, add a separate chapter.
  2316. def transform(
  2317. self,
  2318. size: tuple[int, int],
  2319. method: Transform | ImageTransformHandler | SupportsGetData,
  2320. data: Sequence[Any] | None = None,
  2321. resample: int = Resampling.NEAREST,
  2322. fill: int = 1,
  2323. fillcolor: float | tuple[float, ...] | str | None = None,
  2324. ) -> Image:
  2325. """
  2326. Transforms this image. This method creates a new image with the
  2327. given size, and the same mode as the original, and copies data
  2328. to the new image using the given transform.
  2329. :param size: The output size in pixels, as a 2-tuple:
  2330. (width, height).
  2331. :param method: The transformation method. This is one of
  2332. :py:data:`Transform.EXTENT` (cut out a rectangular subregion),
  2333. :py:data:`Transform.AFFINE` (affine transform),
  2334. :py:data:`Transform.PERSPECTIVE` (perspective transform),
  2335. :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or
  2336. :py:data:`Transform.MESH` (map a number of source quadrilaterals
  2337. in one operation).
  2338. It may also be an :py:class:`~PIL.Image.ImageTransformHandler`
  2339. object::
  2340. class Example(Image.ImageTransformHandler):
  2341. def transform(self, size, data, resample, fill=1):
  2342. # Return result
  2343. Implementations of :py:class:`~PIL.Image.ImageTransformHandler`
  2344. for some of the :py:class:`Transform` methods are provided
  2345. in :py:mod:`~PIL.ImageTransform`.
  2346. It may also be an object with a ``method.getdata`` method
  2347. that returns a tuple supplying new ``method`` and ``data`` values::
  2348. class Example:
  2349. def getdata(self):
  2350. method = Image.Transform.EXTENT
  2351. data = (0, 0, 100, 100)
  2352. return method, data
  2353. :param data: Extra data to the transformation method.
  2354. :param resample: Optional resampling filter. It can be one of
  2355. :py:data:`Resampling.NEAREST` (use nearest neighbour),
  2356. :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2
  2357. environment), or :py:data:`Resampling.BICUBIC` (cubic spline
  2358. interpolation in a 4x4 environment). If omitted, or if the image
  2359. has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`.
  2360. See: :ref:`concept-filters`.
  2361. :param fill: If ``method`` is an
  2362. :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of
  2363. the arguments passed to it. Otherwise, it is unused.
  2364. :param fillcolor: Optional fill color for the area outside the
  2365. transform in the output image.
  2366. :returns: An :py:class:`~PIL.Image.Image` object.
  2367. """
  2368. if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST:
  2369. return (
  2370. self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
  2371. .transform(size, method, data, resample, fill, fillcolor)
  2372. .convert(self.mode)
  2373. )
  2374. if isinstance(method, ImageTransformHandler):
  2375. return method.transform(size, self, resample=resample, fill=fill)
  2376. if hasattr(method, "getdata"):
  2377. # compatibility w. old-style transform objects
  2378. method, data = method.getdata()
  2379. if data is None:
  2380. msg = "missing method data"
  2381. raise ValueError(msg)
  2382. im = new(self.mode, size, fillcolor)
  2383. if self.mode == "P" and self.palette:
  2384. im.palette = self.palette.copy()
  2385. im.info = self.info.copy()
  2386. if method == Transform.MESH:
  2387. # list of quads
  2388. for box, quad in data:
  2389. im.__transformer(
  2390. box, self, Transform.QUAD, quad, resample, fillcolor is None
  2391. )
  2392. else:
  2393. im.__transformer(
  2394. (0, 0) + size, self, method, data, resample, fillcolor is None
  2395. )
  2396. return im
  2397. def __transformer(
  2398. self,
  2399. box: tuple[int, int, int, int],
  2400. image: Image,
  2401. method: Transform,
  2402. data: Sequence[float],
  2403. resample: int = Resampling.NEAREST,
  2404. fill: bool = True,
  2405. ) -> None:
  2406. w = box[2] - box[0]
  2407. h = box[3] - box[1]
  2408. if method == Transform.AFFINE:
  2409. data = data[:6]
  2410. elif method == Transform.EXTENT:
  2411. # convert extent to an affine transform
  2412. x0, y0, x1, y1 = data
  2413. xs = (x1 - x0) / w
  2414. ys = (y1 - y0) / h
  2415. method = Transform.AFFINE
  2416. data = (xs, 0, x0, 0, ys, y0)
  2417. elif method == Transform.PERSPECTIVE:
  2418. data = data[:8]
  2419. elif method == Transform.QUAD:
  2420. # quadrilateral warp. data specifies the four corners
  2421. # given as NW, SW, SE, and NE.
  2422. nw = data[:2]
  2423. sw = data[2:4]
  2424. se = data[4:6]
  2425. ne = data[6:8]
  2426. x0, y0 = nw
  2427. As = 1.0 / w
  2428. At = 1.0 / h
  2429. data = (
  2430. x0,
  2431. (ne[0] - x0) * As,
  2432. (sw[0] - x0) * At,
  2433. (se[0] - sw[0] - ne[0] + x0) * As * At,
  2434. y0,
  2435. (ne[1] - y0) * As,
  2436. (sw[1] - y0) * At,
  2437. (se[1] - sw[1] - ne[1] + y0) * As * At,
  2438. )
  2439. else:
  2440. msg = "unknown transformation method"
  2441. raise ValueError(msg)
  2442. if resample not in (
  2443. Resampling.NEAREST,
  2444. Resampling.BILINEAR,
  2445. Resampling.BICUBIC,
  2446. ):
  2447. if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS):
  2448. unusable: dict[int, str] = {
  2449. Resampling.BOX: "Image.Resampling.BOX",
  2450. Resampling.HAMMING: "Image.Resampling.HAMMING",
  2451. Resampling.LANCZOS: "Image.Resampling.LANCZOS",
  2452. }
  2453. msg = unusable[resample] + f" ({resample}) cannot be used."
  2454. else:
  2455. msg = f"Unknown resampling filter ({resample})."
  2456. filters = [
  2457. f"{filter[1]} ({filter[0]})"
  2458. for filter in (
  2459. (Resampling.NEAREST, "Image.Resampling.NEAREST"),
  2460. (Resampling.BILINEAR, "Image.Resampling.BILINEAR"),
  2461. (Resampling.BICUBIC, "Image.Resampling.BICUBIC"),
  2462. )
  2463. ]
  2464. msg += f" Use {', '.join(filters[:-1])} or {filters[-1]}"
  2465. raise ValueError(msg)
  2466. image.load()
  2467. self.load()
  2468. if image.mode in ("1", "P"):
  2469. resample = Resampling.NEAREST
  2470. self.im.transform(box, image.im, method, data, resample, fill)
  2471. def transpose(self, method: Transpose) -> Image:
  2472. """
  2473. Transpose image (flip or rotate in 90 degree steps)
  2474. :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`,
  2475. :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`,
  2476. :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`,
  2477. :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`.
  2478. :returns: Returns a flipped or rotated copy of this image.
  2479. """
  2480. self.load()
  2481. return self._new(self.im.transpose(method))
  2482. def effect_spread(self, distance: int) -> Image:
  2483. """
  2484. Randomly spread pixels in an image.
  2485. :param distance: Distance to spread pixels.
  2486. """
  2487. self.load()
  2488. return self._new(self.im.effect_spread(distance))
  2489. def toqimage(self) -> ImageQt.ImageQt:
  2490. """Returns a QImage copy of this image"""
  2491. from . import ImageQt
  2492. if not ImageQt.qt_is_installed:
  2493. msg = "Qt bindings are not installed"
  2494. raise ImportError(msg)
  2495. return ImageQt.toqimage(self)
  2496. def toqpixmap(self) -> ImageQt.QPixmap:
  2497. """Returns a QPixmap copy of this image"""
  2498. from . import ImageQt
  2499. if not ImageQt.qt_is_installed:
  2500. msg = "Qt bindings are not installed"
  2501. raise ImportError(msg)
  2502. return ImageQt.toqpixmap(self)
  2503. # --------------------------------------------------------------------
  2504. # Abstract handlers.
  2505. class ImagePointHandler(abc.ABC):
  2506. """
  2507. Used as a mixin by point transforms
  2508. (for use with :py:meth:`~PIL.Image.Image.point`)
  2509. """
  2510. @abc.abstractmethod
  2511. def point(self, im: Image) -> Image:
  2512. pass
  2513. class ImageTransformHandler(abc.ABC):
  2514. """
  2515. Used as a mixin by geometry transforms
  2516. (for use with :py:meth:`~PIL.Image.Image.transform`)
  2517. """
  2518. @abc.abstractmethod
  2519. def transform(
  2520. self,
  2521. size: tuple[int, int],
  2522. image: Image,
  2523. **options: Any,
  2524. ) -> Image:
  2525. pass
  2526. # --------------------------------------------------------------------
  2527. # Factories
  2528. def _check_size(size: Any) -> None:
  2529. """
  2530. Common check to enforce type and sanity check on size tuples
  2531. :param size: Should be a 2 tuple of (width, height)
  2532. :returns: None, or raises a ValueError
  2533. """
  2534. if not isinstance(size, (list, tuple)):
  2535. msg = "Size must be a list or tuple"
  2536. raise ValueError(msg)
  2537. if len(size) != 2:
  2538. msg = "Size must be a sequence of length 2"
  2539. raise ValueError(msg)
  2540. if size[0] < 0 or size[1] < 0:
  2541. msg = "Width and height must be >= 0"
  2542. raise ValueError(msg)
  2543. def new(
  2544. mode: str,
  2545. size: tuple[int, int] | list[int],
  2546. color: float | tuple[float, ...] | str | None = 0,
  2547. ) -> Image:
  2548. """
  2549. Creates a new image with the given mode and size.
  2550. :param mode: The mode to use for the new image. See:
  2551. :ref:`concept-modes`.
  2552. :param size: A 2-tuple, containing (width, height) in pixels.
  2553. :param color: What color to use for the image. Default is black. If given,
  2554. this should be a single integer or floating point value for single-band
  2555. modes, and a tuple for multi-band modes (one value per band). When
  2556. creating RGB or HSV images, you can also use color strings as supported
  2557. by the ImageColor module. See :ref:`colors` for more information. If the
  2558. color is None, the image is not initialised.
  2559. :returns: An :py:class:`~PIL.Image.Image` object.
  2560. """
  2561. _check_size(size)
  2562. if color is None:
  2563. # don't initialize
  2564. return Image()._new(core.new(mode, size))
  2565. if isinstance(color, str):
  2566. # css3-style specifier
  2567. from . import ImageColor
  2568. color = ImageColor.getcolor(color, mode)
  2569. im = Image()
  2570. if (
  2571. mode == "P"
  2572. and isinstance(color, (list, tuple))
  2573. and all(isinstance(i, int) for i in color)
  2574. ):
  2575. color_ints: tuple[int, ...] = cast(tuple[int, ...], tuple(color))
  2576. if len(color_ints) == 3 or len(color_ints) == 4:
  2577. # RGB or RGBA value for a P image
  2578. from . import ImagePalette
  2579. im.palette = ImagePalette.ImagePalette()
  2580. color = im.palette.getcolor(color_ints)
  2581. return im._new(core.fill(mode, size, color))
  2582. def frombytes(
  2583. mode: str,
  2584. size: tuple[int, int],
  2585. data: bytes | bytearray | SupportsArrayInterface,
  2586. decoder_name: str = "raw",
  2587. *args: Any,
  2588. ) -> Image:
  2589. """
  2590. Creates a copy of an image memory from pixel data in a buffer.
  2591. In its simplest form, this function takes three arguments
  2592. (mode, size, and unpacked pixel data).
  2593. You can also use any pixel decoder supported by PIL. For more
  2594. information on available decoders, see the section
  2595. :ref:`Writing Your Own File Codec <file-codecs>`.
  2596. Note that this function decodes pixel data only, not entire images.
  2597. If you have an entire image in a string, wrap it in a
  2598. :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load
  2599. it.
  2600. :param mode: The image mode. See: :ref:`concept-modes`.
  2601. :param size: The image size.
  2602. :param data: A byte buffer containing raw data for the given mode.
  2603. :param decoder_name: What decoder to use.
  2604. :param args: Additional parameters for the given decoder.
  2605. :returns: An :py:class:`~PIL.Image.Image` object.
  2606. """
  2607. _check_size(size)
  2608. im = new(mode, size)
  2609. if im.width != 0 and im.height != 0:
  2610. decoder_args: Any = args
  2611. if len(decoder_args) == 1 and isinstance(decoder_args[0], tuple):
  2612. # may pass tuple instead of argument list
  2613. decoder_args = decoder_args[0]
  2614. if decoder_name == "raw" and decoder_args == ():
  2615. decoder_args = mode
  2616. im.frombytes(data, decoder_name, decoder_args)
  2617. return im
  2618. def frombuffer(
  2619. mode: str,
  2620. size: tuple[int, int],
  2621. data: bytes | SupportsArrayInterface,
  2622. decoder_name: str = "raw",
  2623. *args: Any,
  2624. ) -> Image:
  2625. """
  2626. Creates an image memory referencing pixel data in a byte buffer.
  2627. This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data
  2628. in the byte buffer, where possible. This means that changes to the
  2629. original buffer object are reflected in this image). Not all modes can
  2630. share memory; supported modes include "L", "RGBX", "RGBA", and "CMYK".
  2631. Note that this function decodes pixel data only, not entire images.
  2632. If you have an entire image file in a string, wrap it in a
  2633. :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load it.
  2634. The default parameters used for the "raw" decoder differs from that used for
  2635. :py:func:`~PIL.Image.frombytes`. This is a bug, and will probably be fixed in a
  2636. future release. The current release issues a warning if you do this; to disable
  2637. the warning, you should provide the full set of parameters. See below for details.
  2638. :param mode: The image mode. See: :ref:`concept-modes`.
  2639. :param size: The image size.
  2640. :param data: A bytes or other buffer object containing raw
  2641. data for the given mode.
  2642. :param decoder_name: What decoder to use.
  2643. :param args: Additional parameters for the given decoder. For the
  2644. default encoder ("raw"), it's recommended that you provide the
  2645. full set of parameters::
  2646. frombuffer(mode, size, data, "raw", mode, 0, 1)
  2647. :returns: An :py:class:`~PIL.Image.Image` object.
  2648. .. versionadded:: 1.1.4
  2649. """
  2650. _check_size(size)
  2651. # may pass tuple instead of argument list
  2652. if len(args) == 1 and isinstance(args[0], tuple):
  2653. args = args[0]
  2654. if decoder_name == "raw":
  2655. if args == ():
  2656. args = mode, 0, 1
  2657. if args[0] in _MAPMODES:
  2658. im = new(mode, (0, 0))
  2659. im = im._new(core.map_buffer(data, size, decoder_name, 0, args))
  2660. if mode == "P":
  2661. from . import ImagePalette
  2662. im.palette = ImagePalette.ImagePalette("RGB", im.im.getpalette("RGB"))
  2663. im.readonly = 1
  2664. return im
  2665. return frombytes(mode, size, data, decoder_name, args)
  2666. class SupportsArrayInterface(Protocol):
  2667. """
  2668. An object that has an ``__array_interface__`` dictionary.
  2669. """
  2670. @property
  2671. def __array_interface__(self) -> dict[str, Any]:
  2672. raise NotImplementedError()
  2673. class SupportsArrowArrayInterface(Protocol):
  2674. """
  2675. An object that has an ``__arrow_c_array__`` method corresponding to the arrow c
  2676. data interface.
  2677. """
  2678. def __arrow_c_array__(
  2679. self, requested_schema: "PyCapsule" = None # type: ignore[name-defined] # noqa: F821, UP037
  2680. ) -> tuple["PyCapsule", "PyCapsule"]: # type: ignore[name-defined] # noqa: F821, UP037
  2681. raise NotImplementedError()
  2682. def fromarray(obj: SupportsArrayInterface, mode: str | None = None) -> Image:
  2683. """
  2684. Creates an image memory from an object exporting the array interface
  2685. (using the buffer protocol)::
  2686. from PIL import Image
  2687. import numpy as np
  2688. a = np.zeros((5, 5))
  2689. im = Image.fromarray(a)
  2690. If ``obj`` is not contiguous, then the ``tobytes`` method is called
  2691. and :py:func:`~PIL.Image.frombuffer` is used.
  2692. In the case of NumPy, be aware that Pillow modes do not always correspond
  2693. to NumPy dtypes. Pillow modes only offer 1-bit pixels, 8-bit pixels,
  2694. 32-bit signed integer pixels, and 32-bit floating point pixels.
  2695. Pillow images can also be converted to arrays::
  2696. from PIL import Image
  2697. import numpy as np
  2698. im = Image.open("hopper.jpg")
  2699. a = np.asarray(im)
  2700. When converting Pillow images to arrays however, only pixel values are
  2701. transferred. This means that P and PA mode images will lose their palette.
  2702. :param obj: Object with array interface
  2703. :param mode: Optional mode to use when reading ``obj``. Since pixel values do not
  2704. contain information about palettes or color spaces, this can be used to place
  2705. grayscale L mode data within a P mode image, or read RGB data as YCbCr for
  2706. example.
  2707. See: :ref:`concept-modes` for general information about modes.
  2708. :returns: An image object.
  2709. .. versionadded:: 1.1.6
  2710. """
  2711. arr = obj.__array_interface__
  2712. shape = arr["shape"]
  2713. ndim = len(shape)
  2714. strides = arr.get("strides", None)
  2715. try:
  2716. typekey = (1, 1) + shape[2:], arr["typestr"]
  2717. except KeyError as e:
  2718. if mode is not None:
  2719. typekey = None
  2720. color_modes: list[str] = []
  2721. else:
  2722. msg = "Cannot handle this data type"
  2723. raise TypeError(msg) from e
  2724. if typekey is not None:
  2725. try:
  2726. typemode, rawmode, color_modes = _fromarray_typemap[typekey]
  2727. except KeyError as e:
  2728. typekey_shape, typestr = typekey
  2729. msg = f"Cannot handle this data type: {typekey_shape}, {typestr}"
  2730. raise TypeError(msg) from e
  2731. if mode is not None:
  2732. if mode != typemode and mode not in color_modes:
  2733. deprecate("'mode' parameter for changing data types", 13)
  2734. rawmode = mode
  2735. else:
  2736. mode = typemode
  2737. if mode in ["1", "L", "I", "P", "F"]:
  2738. ndmax = 2
  2739. elif mode == "RGB":
  2740. ndmax = 3
  2741. else:
  2742. ndmax = 4
  2743. if ndim > ndmax:
  2744. msg = f"Too many dimensions: {ndim} > {ndmax}."
  2745. raise ValueError(msg)
  2746. size = 1 if ndim == 1 else shape[1], shape[0]
  2747. if strides is not None:
  2748. if hasattr(obj, "tobytes"):
  2749. obj = obj.tobytes()
  2750. elif hasattr(obj, "tostring"):
  2751. obj = obj.tostring()
  2752. else:
  2753. msg = "'strides' requires either tobytes() or tostring()"
  2754. raise ValueError(msg)
  2755. return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)
  2756. def fromarrow(
  2757. obj: SupportsArrowArrayInterface, mode: str, size: tuple[int, int]
  2758. ) -> Image:
  2759. """Creates an image with zero-copy shared memory from an object exporting
  2760. the arrow_c_array interface protocol::
  2761. from PIL import Image
  2762. import pyarrow as pa
  2763. arr = pa.array([0]*(5*5*4), type=pa.uint8())
  2764. im = Image.fromarrow(arr, 'RGBA', (5, 5))
  2765. If the data representation of the ``obj`` is not compatible with
  2766. Pillow internal storage, a ValueError is raised.
  2767. Pillow images can also be converted to Arrow objects::
  2768. from PIL import Image
  2769. import pyarrow as pa
  2770. im = Image.open('hopper.jpg')
  2771. arr = pa.array(im)
  2772. As with array support, when converting Pillow images to arrays,
  2773. only pixel values are transferred. This means that P and PA mode
  2774. images will lose their palette.
  2775. :param obj: Object with an arrow_c_array interface
  2776. :param mode: Image mode.
  2777. :param size: Image size. This must match the storage of the arrow object.
  2778. :returns: An Image object
  2779. Note that according to the Arrow spec, both the producer and the
  2780. consumer should consider the exported array to be immutable, as
  2781. unsynchronized updates will potentially cause inconsistent data.
  2782. See: :ref:`arrow-support` for more detailed information
  2783. .. versionadded:: 11.2.1
  2784. """
  2785. if not hasattr(obj, "__arrow_c_array__"):
  2786. msg = "arrow_c_array interface not found"
  2787. raise ValueError(msg)
  2788. (schema_capsule, array_capsule) = obj.__arrow_c_array__()
  2789. _im = core.new_arrow(mode, size, schema_capsule, array_capsule)
  2790. if _im:
  2791. return Image()._new(_im)
  2792. msg = "new_arrow returned None without an exception"
  2793. raise ValueError(msg)
  2794. def fromqimage(im: ImageQt.QImage) -> ImageFile.ImageFile:
  2795. """Creates an image instance from a QImage image"""
  2796. from . import ImageQt
  2797. if not ImageQt.qt_is_installed:
  2798. msg = "Qt bindings are not installed"
  2799. raise ImportError(msg)
  2800. return ImageQt.fromqimage(im)
  2801. def fromqpixmap(im: ImageQt.QPixmap) -> ImageFile.ImageFile:
  2802. """Creates an image instance from a QPixmap image"""
  2803. from . import ImageQt
  2804. if not ImageQt.qt_is_installed:
  2805. msg = "Qt bindings are not installed"
  2806. raise ImportError(msg)
  2807. return ImageQt.fromqpixmap(im)
  2808. _fromarray_typemap = {
  2809. # (shape, typestr) => mode, rawmode, color modes
  2810. # first two members of shape are set to one
  2811. ((1, 1), "|b1"): ("1", "1;8", []),
  2812. ((1, 1), "|u1"): ("L", "L", ["P"]),
  2813. ((1, 1), "|i1"): ("I", "I;8", []),
  2814. ((1, 1), "<u2"): ("I", "I;16", []),
  2815. ((1, 1), ">u2"): ("I", "I;16B", []),
  2816. ((1, 1), "<i2"): ("I", "I;16S", []),
  2817. ((1, 1), ">i2"): ("I", "I;16BS", []),
  2818. ((1, 1), "<u4"): ("I", "I;32", []),
  2819. ((1, 1), ">u4"): ("I", "I;32B", []),
  2820. ((1, 1), "<i4"): ("I", "I;32S", []),
  2821. ((1, 1), ">i4"): ("I", "I;32BS", []),
  2822. ((1, 1), "<f4"): ("F", "F;32F", []),
  2823. ((1, 1), ">f4"): ("F", "F;32BF", []),
  2824. ((1, 1), "<f8"): ("F", "F;64F", []),
  2825. ((1, 1), ">f8"): ("F", "F;64BF", []),
  2826. ((1, 1, 2), "|u1"): ("LA", "LA", ["La", "PA"]),
  2827. ((1, 1, 3), "|u1"): ("RGB", "RGB", ["YCbCr", "LAB", "HSV"]),
  2828. ((1, 1, 4), "|u1"): ("RGBA", "RGBA", ["RGBa", "RGBX", "CMYK"]),
  2829. # shortcuts:
  2830. ((1, 1), f"{_ENDIAN}i4"): ("I", "I", []),
  2831. ((1, 1), f"{_ENDIAN}f4"): ("F", "F", []),
  2832. }
  2833. def _decompression_bomb_check(size: tuple[int, int]) -> None:
  2834. if MAX_IMAGE_PIXELS is None:
  2835. return
  2836. pixels = max(1, size[0]) * max(1, size[1])
  2837. if pixels > 2 * MAX_IMAGE_PIXELS:
  2838. msg = (
  2839. f"Image size ({pixels} pixels) exceeds limit of {2 * MAX_IMAGE_PIXELS} "
  2840. "pixels, could be decompression bomb DOS attack."
  2841. )
  2842. raise DecompressionBombError(msg)
  2843. if pixels > MAX_IMAGE_PIXELS:
  2844. warnings.warn(
  2845. f"Image size ({pixels} pixels) exceeds limit of {MAX_IMAGE_PIXELS} pixels, "
  2846. "could be decompression bomb DOS attack.",
  2847. DecompressionBombWarning,
  2848. )
  2849. def open(
  2850. fp: StrOrBytesPath | IO[bytes],
  2851. mode: Literal["r"] = "r",
  2852. formats: list[str] | tuple[str, ...] | None = None,
  2853. ) -> ImageFile.ImageFile:
  2854. """
  2855. Opens and identifies the given image file.
  2856. This is a lazy operation; this function identifies the file, but
  2857. the file remains open and the actual image data is not read from
  2858. the file until you try to process the data (or call the
  2859. :py:meth:`~PIL.Image.Image.load` method). See
  2860. :py:func:`~PIL.Image.new`. See :ref:`file-handling`.
  2861. :param fp: A filename (string), os.PathLike object or a file object.
  2862. The file object must implement ``file.read``,
  2863. ``file.seek``, and ``file.tell`` methods,
  2864. and be opened in binary mode. The file object will also seek to zero
  2865. before reading.
  2866. :param mode: The mode. If given, this argument must be "r".
  2867. :param formats: A list or tuple of formats to attempt to load the file in.
  2868. This can be used to restrict the set of formats checked.
  2869. Pass ``None`` to try all supported formats. You can print the set of
  2870. available formats by running ``python3 -m PIL`` or using
  2871. the :py:func:`PIL.features.pilinfo` function.
  2872. :returns: An :py:class:`~PIL.Image.Image` object.
  2873. :exception FileNotFoundError: If the file cannot be found.
  2874. :exception PIL.UnidentifiedImageError: If the image cannot be opened and
  2875. identified.
  2876. :exception ValueError: If the ``mode`` is not "r", or if a ``StringIO``
  2877. instance is used for ``fp``.
  2878. :exception TypeError: If ``formats`` is not ``None``, a list or a tuple.
  2879. """
  2880. if mode != "r":
  2881. msg = f"bad mode {repr(mode)}" # type: ignore[unreachable]
  2882. raise ValueError(msg)
  2883. elif isinstance(fp, io.StringIO):
  2884. msg = ( # type: ignore[unreachable]
  2885. "StringIO cannot be used to open an image. "
  2886. "Binary data must be used instead."
  2887. )
  2888. raise ValueError(msg)
  2889. if formats is None:
  2890. formats = ID
  2891. elif not isinstance(formats, (list, tuple)):
  2892. msg = "formats must be a list or tuple" # type: ignore[unreachable]
  2893. raise TypeError(msg)
  2894. exclusive_fp = False
  2895. filename: str | bytes = ""
  2896. if is_path(fp):
  2897. filename = os.fspath(fp)
  2898. fp = builtins.open(filename, "rb")
  2899. exclusive_fp = True
  2900. else:
  2901. fp = cast(IO[bytes], fp)
  2902. try:
  2903. fp.seek(0)
  2904. except (AttributeError, io.UnsupportedOperation):
  2905. fp = io.BytesIO(fp.read())
  2906. exclusive_fp = True
  2907. prefix = fp.read(16)
  2908. preinit()
  2909. warning_messages: list[str] = []
  2910. def _open_core(
  2911. fp: IO[bytes],
  2912. filename: str | bytes,
  2913. prefix: bytes,
  2914. formats: list[str] | tuple[str, ...],
  2915. ) -> ImageFile.ImageFile | None:
  2916. for i in formats:
  2917. i = i.upper()
  2918. if i not in OPEN:
  2919. init()
  2920. try:
  2921. factory, accept = OPEN[i]
  2922. result = not accept or accept(prefix)
  2923. if isinstance(result, str):
  2924. warning_messages.append(result)
  2925. elif result:
  2926. fp.seek(0)
  2927. im = factory(fp, filename)
  2928. _decompression_bomb_check(im.size)
  2929. return im
  2930. except (SyntaxError, IndexError, TypeError, struct.error) as e:
  2931. if WARN_POSSIBLE_FORMATS:
  2932. warning_messages.append(i + " opening failed. " + str(e))
  2933. except BaseException:
  2934. if exclusive_fp:
  2935. fp.close()
  2936. raise
  2937. return None
  2938. im = _open_core(fp, filename, prefix, formats)
  2939. if im is None and formats is ID:
  2940. checked_formats = ID.copy()
  2941. if init():
  2942. im = _open_core(
  2943. fp,
  2944. filename,
  2945. prefix,
  2946. tuple(format for format in formats if format not in checked_formats),
  2947. )
  2948. if im:
  2949. im._exclusive_fp = exclusive_fp
  2950. return im
  2951. if exclusive_fp:
  2952. fp.close()
  2953. for message in warning_messages:
  2954. warnings.warn(message)
  2955. msg = "cannot identify image file %r" % (filename if filename else fp)
  2956. raise UnidentifiedImageError(msg)
  2957. #
  2958. # Image processing.
  2959. def alpha_composite(im1: Image, im2: Image) -> Image:
  2960. """
  2961. Alpha composite im2 over im1.
  2962. :param im1: The first image. Must have mode RGBA or LA.
  2963. :param im2: The second image. Must have the same mode and size as the first image.
  2964. :returns: An :py:class:`~PIL.Image.Image` object.
  2965. """
  2966. im1.load()
  2967. im2.load()
  2968. return im1._new(core.alpha_composite(im1.im, im2.im))
  2969. def blend(im1: Image, im2: Image, alpha: float) -> Image:
  2970. """
  2971. Creates a new image by interpolating between two input images, using
  2972. a constant alpha::
  2973. out = image1 * (1.0 - alpha) + image2 * alpha
  2974. :param im1: The first image.
  2975. :param im2: The second image. Must have the same mode and size as
  2976. the first image.
  2977. :param alpha: The interpolation alpha factor. If alpha is 0.0, a
  2978. copy of the first image is returned. If alpha is 1.0, a copy of
  2979. the second image is returned. There are no restrictions on the
  2980. alpha value. If necessary, the result is clipped to fit into
  2981. the allowed output range.
  2982. :returns: An :py:class:`~PIL.Image.Image` object.
  2983. """
  2984. im1.load()
  2985. im2.load()
  2986. return im1._new(core.blend(im1.im, im2.im, alpha))
  2987. def composite(image1: Image, image2: Image, mask: Image) -> Image:
  2988. """
  2989. Create composite image by blending images using a transparency mask.
  2990. :param image1: The first image.
  2991. :param image2: The second image. Must have the same mode and
  2992. size as the first image.
  2993. :param mask: A mask image. This image can have mode
  2994. "1", "L", or "RGBA", and must have the same size as the
  2995. other two images.
  2996. """
  2997. image = image2.copy()
  2998. image.paste(image1, None, mask)
  2999. return image
  3000. def eval(image: Image, *args: Callable[[int], float]) -> Image:
  3001. """
  3002. Applies the function (which should take one argument) to each pixel
  3003. in the given image. If the image has more than one band, the same
  3004. function is applied to each band. Note that the function is
  3005. evaluated once for each possible pixel value, so you cannot use
  3006. random components or other generators.
  3007. :param image: The input image.
  3008. :param function: A function object, taking one integer argument.
  3009. :returns: An :py:class:`~PIL.Image.Image` object.
  3010. """
  3011. return image.point(args[0])
  3012. def merge(mode: str, bands: Sequence[Image]) -> Image:
  3013. """
  3014. Merge a set of single band images into a new multiband image.
  3015. :param mode: The mode to use for the output image. See:
  3016. :ref:`concept-modes`.
  3017. :param bands: A sequence containing one single-band image for
  3018. each band in the output image. All bands must have the
  3019. same size.
  3020. :returns: An :py:class:`~PIL.Image.Image` object.
  3021. """
  3022. if getmodebands(mode) != len(bands) or "*" in mode:
  3023. msg = "wrong number of bands"
  3024. raise ValueError(msg)
  3025. for band in bands[1:]:
  3026. if band.mode != getmodetype(mode):
  3027. msg = "mode mismatch"
  3028. raise ValueError(msg)
  3029. if band.size != bands[0].size:
  3030. msg = "size mismatch"
  3031. raise ValueError(msg)
  3032. for band in bands:
  3033. band.load()
  3034. return bands[0]._new(core.merge(mode, *[b.im for b in bands]))
  3035. # --------------------------------------------------------------------
  3036. # Plugin registry
  3037. def register_open(
  3038. id: str,
  3039. factory: (
  3040. Callable[[IO[bytes], str | bytes], ImageFile.ImageFile]
  3041. | type[ImageFile.ImageFile]
  3042. ),
  3043. accept: Callable[[bytes], bool | str] | None = None,
  3044. ) -> None:
  3045. """
  3046. Register an image file plugin. This function should not be used
  3047. in application code.
  3048. :param id: An image format identifier.
  3049. :param factory: An image file factory method.
  3050. :param accept: An optional function that can be used to quickly
  3051. reject images having another format.
  3052. """
  3053. id = id.upper()
  3054. if id not in ID:
  3055. ID.append(id)
  3056. OPEN[id] = factory, accept
  3057. def register_mime(id: str, mimetype: str) -> None:
  3058. """
  3059. Registers an image MIME type by populating ``Image.MIME``. This function
  3060. should not be used in application code.
  3061. ``Image.MIME`` provides a mapping from image format identifiers to mime
  3062. formats, but :py:meth:`~PIL.ImageFile.ImageFile.get_format_mimetype` can
  3063. provide a different result for specific images.
  3064. :param id: An image format identifier.
  3065. :param mimetype: The image MIME type for this format.
  3066. """
  3067. MIME[id.upper()] = mimetype
  3068. def register_save(
  3069. id: str, driver: Callable[[Image, IO[bytes], str | bytes], None]
  3070. ) -> None:
  3071. """
  3072. Registers an image save function. This function should not be
  3073. used in application code.
  3074. :param id: An image format identifier.
  3075. :param driver: A function to save images in this format.
  3076. """
  3077. SAVE[id.upper()] = driver
  3078. def register_save_all(
  3079. id: str, driver: Callable[[Image, IO[bytes], str | bytes], None]
  3080. ) -> None:
  3081. """
  3082. Registers an image function to save all the frames
  3083. of a multiframe format. This function should not be
  3084. used in application code.
  3085. :param id: An image format identifier.
  3086. :param driver: A function to save images in this format.
  3087. """
  3088. SAVE_ALL[id.upper()] = driver
  3089. def register_extension(id: str, extension: str) -> None:
  3090. """
  3091. Registers an image extension. This function should not be
  3092. used in application code.
  3093. :param id: An image format identifier.
  3094. :param extension: An extension used for this format.
  3095. """
  3096. EXTENSION[extension.lower()] = id.upper()
  3097. def register_extensions(id: str, extensions: list[str]) -> None:
  3098. """
  3099. Registers image extensions. This function should not be
  3100. used in application code.
  3101. :param id: An image format identifier.
  3102. :param extensions: A list of extensions used for this format.
  3103. """
  3104. for extension in extensions:
  3105. register_extension(id, extension)
  3106. def registered_extensions() -> dict[str, str]:
  3107. """
  3108. Returns a dictionary containing all file extensions belonging
  3109. to registered plugins
  3110. """
  3111. init()
  3112. return EXTENSION
  3113. def register_decoder(name: str, decoder: type[ImageFile.PyDecoder]) -> None:
  3114. """
  3115. Registers an image decoder. This function should not be
  3116. used in application code.
  3117. :param name: The name of the decoder
  3118. :param decoder: An ImageFile.PyDecoder object
  3119. .. versionadded:: 4.1.0
  3120. """
  3121. DECODERS[name] = decoder
  3122. def register_encoder(name: str, encoder: type[ImageFile.PyEncoder]) -> None:
  3123. """
  3124. Registers an image encoder. This function should not be
  3125. used in application code.
  3126. :param name: The name of the encoder
  3127. :param encoder: An ImageFile.PyEncoder object
  3128. .. versionadded:: 4.1.0
  3129. """
  3130. ENCODERS[name] = encoder
  3131. # --------------------------------------------------------------------
  3132. # Simple display support.
  3133. def _show(image: Image, **options: Any) -> None:
  3134. from . import ImageShow
  3135. deprecate("Image._show", 13, "ImageShow.show")
  3136. ImageShow.show(image, **options)
  3137. # --------------------------------------------------------------------
  3138. # Effects
  3139. def effect_mandelbrot(
  3140. size: tuple[int, int], extent: tuple[float, float, float, float], quality: int
  3141. ) -> Image:
  3142. """
  3143. Generate a Mandelbrot set covering the given extent.
  3144. :param size: The requested size in pixels, as a 2-tuple:
  3145. (width, height).
  3146. :param extent: The extent to cover, as a 4-tuple:
  3147. (x0, y0, x1, y1).
  3148. :param quality: Quality.
  3149. """
  3150. return Image()._new(core.effect_mandelbrot(size, extent, quality))
  3151. def effect_noise(size: tuple[int, int], sigma: float) -> Image:
  3152. """
  3153. Generate Gaussian noise centered around 128.
  3154. :param size: The requested size in pixels, as a 2-tuple:
  3155. (width, height).
  3156. :param sigma: Standard deviation of noise.
  3157. """
  3158. return Image()._new(core.effect_noise(size, sigma))
  3159. def linear_gradient(mode: str) -> Image:
  3160. """
  3161. Generate 256x256 linear gradient from black to white, top to bottom.
  3162. :param mode: Input mode.
  3163. """
  3164. return Image()._new(core.linear_gradient(mode))
  3165. def radial_gradient(mode: str) -> Image:
  3166. """
  3167. Generate 256x256 radial gradient from black to white, centre to edge.
  3168. :param mode: Input mode.
  3169. """
  3170. return Image()._new(core.radial_gradient(mode))
  3171. # --------------------------------------------------------------------
  3172. # Resources
  3173. def _apply_env_variables(env: dict[str, str] | None = None) -> None:
  3174. env_dict = env if env is not None else os.environ
  3175. for var_name, setter in [
  3176. ("PILLOW_ALIGNMENT", core.set_alignment),
  3177. ("PILLOW_BLOCK_SIZE", core.set_block_size),
  3178. ("PILLOW_BLOCKS_MAX", core.set_blocks_max),
  3179. ]:
  3180. if var_name not in env_dict:
  3181. continue
  3182. var = env_dict[var_name].lower()
  3183. units = 1
  3184. for postfix, mul in [("k", 1024), ("m", 1024 * 1024)]:
  3185. if var.endswith(postfix):
  3186. units = mul
  3187. var = var[: -len(postfix)]
  3188. try:
  3189. var_int = int(var) * units
  3190. except ValueError:
  3191. warnings.warn(f"{var_name} is not int")
  3192. continue
  3193. try:
  3194. setter(var_int)
  3195. except ValueError as e:
  3196. warnings.warn(f"{var_name}: {e}")
  3197. _apply_env_variables()
  3198. atexit.register(core.clear_cache)
  3199. if TYPE_CHECKING:
  3200. _ExifBase = MutableMapping[int, Any]
  3201. else:
  3202. _ExifBase = MutableMapping
  3203. class Exif(_ExifBase):
  3204. """
  3205. This class provides read and write access to EXIF image data::
  3206. from PIL import Image
  3207. im = Image.open("exif.png")
  3208. exif = im.getexif() # Returns an instance of this class
  3209. Information can be read and written, iterated over or deleted::
  3210. print(exif[274]) # 1
  3211. exif[274] = 2
  3212. for k, v in exif.items():
  3213. print("Tag", k, "Value", v) # Tag 274 Value 2
  3214. del exif[274]
  3215. To access information beyond IFD0, :py:meth:`~PIL.Image.Exif.get_ifd`
  3216. returns a dictionary::
  3217. from PIL import ExifTags
  3218. im = Image.open("exif_gps.jpg")
  3219. exif = im.getexif()
  3220. gps_ifd = exif.get_ifd(ExifTags.IFD.GPSInfo)
  3221. print(gps_ifd)
  3222. Other IFDs include ``ExifTags.IFD.Exif``, ``ExifTags.IFD.MakerNote``,
  3223. ``ExifTags.IFD.Interop`` and ``ExifTags.IFD.IFD1``.
  3224. :py:mod:`~PIL.ExifTags` also has enum classes to provide names for data::
  3225. print(exif[ExifTags.Base.Software]) # PIL
  3226. print(gps_ifd[ExifTags.GPS.GPSDateStamp]) # 1999:99:99 99:99:99
  3227. """
  3228. endian: str | None = None
  3229. bigtiff = False
  3230. _loaded = False
  3231. def __init__(self) -> None:
  3232. self._data: dict[int, Any] = {}
  3233. self._hidden_data: dict[int, Any] = {}
  3234. self._ifds: dict[int, dict[int, Any]] = {}
  3235. self._info: TiffImagePlugin.ImageFileDirectory_v2 | None = None
  3236. self._loaded_exif: bytes | None = None
  3237. def _fixup(self, value: Any) -> Any:
  3238. try:
  3239. if len(value) == 1 and isinstance(value, tuple):
  3240. return value[0]
  3241. except Exception:
  3242. pass
  3243. return value
  3244. def _fixup_dict(self, src_dict: dict[int, Any]) -> dict[int, Any]:
  3245. # Helper function
  3246. # returns a dict with any single item tuples/lists as individual values
  3247. return {k: self._fixup(v) for k, v in src_dict.items()}
  3248. def _get_ifd_dict(
  3249. self, offset: int, group: int | None = None
  3250. ) -> dict[int, Any] | None:
  3251. try:
  3252. # an offset pointer to the location of the nested embedded IFD.
  3253. # It should be a long, but may be corrupted.
  3254. self.fp.seek(offset)
  3255. except (KeyError, TypeError):
  3256. return None
  3257. else:
  3258. from . import TiffImagePlugin
  3259. info = TiffImagePlugin.ImageFileDirectory_v2(self.head, group=group)
  3260. info.load(self.fp)
  3261. return self._fixup_dict(dict(info))
  3262. def _get_head(self) -> bytes:
  3263. version = b"\x2b" if self.bigtiff else b"\x2a"
  3264. if self.endian == "<":
  3265. head = b"II" + version + b"\x00" + o32le(8)
  3266. else:
  3267. head = b"MM\x00" + version + o32be(8)
  3268. if self.bigtiff:
  3269. head += o32le(8) if self.endian == "<" else o32be(8)
  3270. head += b"\x00\x00\x00\x00"
  3271. return head
  3272. def load(self, data: bytes) -> None:
  3273. # Extract EXIF information. This is highly experimental,
  3274. # and is likely to be replaced with something better in a future
  3275. # version.
  3276. # The EXIF record consists of a TIFF file embedded in a JPEG
  3277. # application marker (!).
  3278. if data == self._loaded_exif:
  3279. return
  3280. self._loaded_exif = data
  3281. self._data.clear()
  3282. self._hidden_data.clear()
  3283. self._ifds.clear()
  3284. while data and data.startswith(b"Exif\x00\x00"):
  3285. data = data[6:]
  3286. if not data:
  3287. self._info = None
  3288. return
  3289. self.fp: IO[bytes] = io.BytesIO(data)
  3290. self.head = self.fp.read(8)
  3291. # process dictionary
  3292. from . import TiffImagePlugin
  3293. self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head)
  3294. self.endian = self._info._endian
  3295. self.fp.seek(self._info.next)
  3296. self._info.load(self.fp)
  3297. def load_from_fp(self, fp: IO[bytes], offset: int | None = None) -> None:
  3298. self._loaded_exif = None
  3299. self._data.clear()
  3300. self._hidden_data.clear()
  3301. self._ifds.clear()
  3302. # process dictionary
  3303. from . import TiffImagePlugin
  3304. self.fp = fp
  3305. if offset is not None:
  3306. self.head = self._get_head()
  3307. else:
  3308. self.head = self.fp.read(8)
  3309. self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head)
  3310. if self.endian is None:
  3311. self.endian = self._info._endian
  3312. if offset is None:
  3313. offset = self._info.next
  3314. self.fp.tell()
  3315. self.fp.seek(offset)
  3316. self._info.load(self.fp)
  3317. def _get_merged_dict(self) -> dict[int, Any]:
  3318. merged_dict = dict(self)
  3319. # get EXIF extension
  3320. if ExifTags.IFD.Exif in self:
  3321. ifd = self._get_ifd_dict(self[ExifTags.IFD.Exif], ExifTags.IFD.Exif)
  3322. if ifd:
  3323. merged_dict.update(ifd)
  3324. # GPS
  3325. if ExifTags.IFD.GPSInfo in self:
  3326. merged_dict[ExifTags.IFD.GPSInfo] = self._get_ifd_dict(
  3327. self[ExifTags.IFD.GPSInfo], ExifTags.IFD.GPSInfo
  3328. )
  3329. return merged_dict
  3330. def tobytes(self, offset: int = 8) -> bytes:
  3331. from . import TiffImagePlugin
  3332. head = self._get_head()
  3333. ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)
  3334. for tag, ifd_dict in self._ifds.items():
  3335. if tag not in self:
  3336. ifd[tag] = ifd_dict
  3337. for tag, value in self.items():
  3338. if tag in [
  3339. ExifTags.IFD.Exif,
  3340. ExifTags.IFD.GPSInfo,
  3341. ] and not isinstance(value, dict):
  3342. value = self.get_ifd(tag)
  3343. if (
  3344. tag == ExifTags.IFD.Exif
  3345. and ExifTags.IFD.Interop in value
  3346. and not isinstance(value[ExifTags.IFD.Interop], dict)
  3347. ):
  3348. value = value.copy()
  3349. value[ExifTags.IFD.Interop] = self.get_ifd(ExifTags.IFD.Interop)
  3350. ifd[tag] = value
  3351. return b"Exif\x00\x00" + head + ifd.tobytes(offset)
  3352. def get_ifd(self, tag: int) -> dict[int, Any]:
  3353. if tag not in self._ifds:
  3354. if tag == ExifTags.IFD.IFD1:
  3355. if self._info is not None and self._info.next != 0:
  3356. ifd = self._get_ifd_dict(self._info.next)
  3357. if ifd is not None:
  3358. self._ifds[tag] = ifd
  3359. elif tag in [ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo]:
  3360. offset = self._hidden_data.get(tag, self.get(tag))
  3361. if offset is not None:
  3362. ifd = self._get_ifd_dict(offset, tag)
  3363. if ifd is not None:
  3364. self._ifds[tag] = ifd
  3365. elif tag in [ExifTags.IFD.Interop, ExifTags.IFD.MakerNote]:
  3366. if ExifTags.IFD.Exif not in self._ifds:
  3367. self.get_ifd(ExifTags.IFD.Exif)
  3368. tag_data = self._ifds[ExifTags.IFD.Exif][tag]
  3369. if tag == ExifTags.IFD.MakerNote:
  3370. from .TiffImagePlugin import ImageFileDirectory_v2
  3371. if tag_data.startswith(b"FUJIFILM"):
  3372. ifd_offset = i32le(tag_data, 8)
  3373. ifd_data = tag_data[ifd_offset:]
  3374. makernote = {}
  3375. for i in range(struct.unpack("<H", ifd_data[:2])[0]):
  3376. ifd_tag, typ, count, data = struct.unpack(
  3377. "<HHL4s", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]
  3378. )
  3379. try:
  3380. (
  3381. unit_size,
  3382. handler,
  3383. ) = ImageFileDirectory_v2._load_dispatch[typ]
  3384. except KeyError:
  3385. continue
  3386. size = count * unit_size
  3387. if size > 4:
  3388. (offset,) = struct.unpack("<L", data)
  3389. data = ifd_data[offset - 12 : offset + size - 12]
  3390. else:
  3391. data = data[:size]
  3392. if len(data) != size:
  3393. warnings.warn(
  3394. "Possibly corrupt EXIF MakerNote data. "
  3395. f"Expecting to read {size} bytes but only got "
  3396. f"{len(data)}. Skipping tag {ifd_tag}"
  3397. )
  3398. continue
  3399. if not data:
  3400. continue
  3401. makernote[ifd_tag] = handler(
  3402. ImageFileDirectory_v2(), data, False
  3403. )
  3404. self._ifds[tag] = dict(self._fixup_dict(makernote))
  3405. elif self.get(0x010F) == "Nintendo":
  3406. makernote = {}
  3407. for i in range(struct.unpack(">H", tag_data[:2])[0]):
  3408. ifd_tag, typ, count, data = struct.unpack(
  3409. ">HHL4s", tag_data[i * 12 + 2 : (i + 1) * 12 + 2]
  3410. )
  3411. if ifd_tag == 0x1101:
  3412. # CameraInfo
  3413. (offset,) = struct.unpack(">L", data)
  3414. self.fp.seek(offset)
  3415. camerainfo: dict[str, int | bytes] = {
  3416. "ModelID": self.fp.read(4)
  3417. }
  3418. self.fp.read(4)
  3419. # Seconds since 2000
  3420. camerainfo["TimeStamp"] = i32le(self.fp.read(12))
  3421. self.fp.read(4)
  3422. camerainfo["InternalSerialNumber"] = self.fp.read(4)
  3423. self.fp.read(12)
  3424. parallax = self.fp.read(4)
  3425. handler = ImageFileDirectory_v2._load_dispatch[
  3426. TiffTags.FLOAT
  3427. ][1]
  3428. camerainfo["Parallax"] = handler(
  3429. ImageFileDirectory_v2(), parallax, False
  3430. )[0]
  3431. self.fp.read(4)
  3432. camerainfo["Category"] = self.fp.read(2)
  3433. makernote = {0x1101: camerainfo}
  3434. self._ifds[tag] = makernote
  3435. else:
  3436. # Interop
  3437. ifd = self._get_ifd_dict(tag_data, tag)
  3438. if ifd is not None:
  3439. self._ifds[tag] = ifd
  3440. ifd = self._ifds.setdefault(tag, {})
  3441. if tag == ExifTags.IFD.Exif and self._hidden_data:
  3442. ifd = {
  3443. k: v
  3444. for (k, v) in ifd.items()
  3445. if k not in (ExifTags.IFD.Interop, ExifTags.IFD.MakerNote)
  3446. }
  3447. return ifd
  3448. def hide_offsets(self) -> None:
  3449. for tag in (ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo):
  3450. if tag in self:
  3451. self._hidden_data[tag] = self[tag]
  3452. del self[tag]
  3453. def __str__(self) -> str:
  3454. if self._info is not None:
  3455. # Load all keys into self._data
  3456. for tag in self._info:
  3457. self[tag]
  3458. return str(self._data)
  3459. def __len__(self) -> int:
  3460. keys = set(self._data)
  3461. if self._info is not None:
  3462. keys.update(self._info)
  3463. return len(keys)
  3464. def __getitem__(self, tag: int) -> Any:
  3465. if self._info is not None and tag not in self._data and tag in self._info:
  3466. self._data[tag] = self._fixup(self._info[tag])
  3467. del self._info[tag]
  3468. return self._data[tag]
  3469. def __contains__(self, tag: object) -> bool:
  3470. return tag in self._data or (self._info is not None and tag in self._info)
  3471. def __setitem__(self, tag: int, value: Any) -> None:
  3472. if self._info is not None and tag in self._info:
  3473. del self._info[tag]
  3474. self._data[tag] = value
  3475. def __delitem__(self, tag: int) -> None:
  3476. if self._info is not None and tag in self._info:
  3477. del self._info[tag]
  3478. else:
  3479. del self._data[tag]
  3480. if tag in self._ifds:
  3481. del self._ifds[tag]
  3482. def __iter__(self) -> Iterator[int]:
  3483. keys = set(self._data)
  3484. if self._info is not None:
  3485. keys.update(self._info)
  3486. return iter(keys)