Image.py 139 KB

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