Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Image.py 130KB

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