Image.py 145 KB

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