Image.py 113 KB

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