Image.py 145 KB

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