Image.py 150 KB

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