You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2965 lines
96 KiB

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