Image.py 150 KB

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