Image.py 131 KB

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