Image.py 107 KB

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