Image.py 124 KB

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