Image.py 119 KB

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