Image.py 143 KB

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