Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/PIL/Image.py: 45%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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#
27from __future__ import annotations
29import abc
30import atexit
31import builtins
32import io
33import logging
34import math
35import os
36import re
37import struct
38import sys
39import tempfile
40import warnings
41from collections.abc import MutableMapping
42from enum import IntEnum
43from typing import IO, Protocol, cast
45# VERSION was removed in Pillow 6.0.0.
46# PILLOW_VERSION was removed in Pillow 9.0.0.
47# Use __version__ instead.
48from . import (
49 ExifTags,
50 ImageMode,
51 TiffTags,
52 UnidentifiedImageError,
53 __version__,
54 _plugins,
55)
56from ._binary import i32le, o32be, o32le
57from ._deprecate import deprecate
58from ._util import DeferredError, is_path
60ElementTree: ModuleType | None
61try:
62 from defusedxml import ElementTree
63except ImportError:
64 ElementTree = None
66TYPE_CHECKING = False
67if TYPE_CHECKING:
68 from collections.abc import Callable, Iterator, Sequence
69 from types import ModuleType
70 from typing import Any, Literal
72logger = logging.getLogger(__name__)
75class DecompressionBombWarning(RuntimeWarning):
76 pass
79class DecompressionBombError(Exception):
80 pass
83WARN_POSSIBLE_FORMATS: bool = False
85# Limit to around a quarter gigabyte for a 24-bit (3 bpp) image
86MAX_IMAGE_PIXELS: int | None = int(1024 * 1024 * 1024 // 4 // 3)
89try:
90 # If the _imaging C module is not present, Pillow will not load.
91 # Note that other modules should not refer to _imaging directly;
92 # import Image and use the Image.core variable instead.
93 # Also note that Image.core is not a publicly documented interface,
94 # and should be considered private and subject to change.
95 from . import _imaging as core
97 if __version__ != getattr(core, "PILLOW_VERSION", None):
98 msg = (
99 "The _imaging extension was built for another version of Pillow or PIL:\n"
100 f"Core version: {getattr(core, 'PILLOW_VERSION', None)}\n"
101 f"Pillow version: {__version__}"
102 )
103 raise ImportError(msg)
105except ImportError as v:
106 # Explanations for ways that we know we might have an import error
107 if str(v).startswith("Module use of python"):
108 # The _imaging C module is present, but not compiled for
109 # the right version (windows only). Print a warning, if
110 # possible.
111 warnings.warn(
112 "The _imaging extension was built for another version of Python.",
113 RuntimeWarning,
114 )
115 elif str(v).startswith("The _imaging extension"):
116 warnings.warn(str(v), RuntimeWarning)
117 # Fail here anyway. Don't let people run with a mostly broken Pillow.
118 # see docs/porting.rst
119 raise
122#
123# Constants
126# transpose
127class Transpose(IntEnum):
128 FLIP_LEFT_RIGHT = 0
129 FLIP_TOP_BOTTOM = 1
130 ROTATE_90 = 2
131 ROTATE_180 = 3
132 ROTATE_270 = 4
133 TRANSPOSE = 5
134 TRANSVERSE = 6
137# transforms (also defined in Imaging.h)
138class Transform(IntEnum):
139 AFFINE = 0
140 EXTENT = 1
141 PERSPECTIVE = 2
142 QUAD = 3
143 MESH = 4
146# resampling filters (also defined in Imaging.h)
147class Resampling(IntEnum):
148 NEAREST = 0
149 BOX = 4
150 BILINEAR = 2
151 HAMMING = 5
152 BICUBIC = 3
153 LANCZOS = 1
156_filters_support = {
157 Resampling.BOX: 0.5,
158 Resampling.BILINEAR: 1.0,
159 Resampling.HAMMING: 1.0,
160 Resampling.BICUBIC: 2.0,
161 Resampling.LANCZOS: 3.0,
162}
165# dithers
166class Dither(IntEnum):
167 NONE = 0
168 ORDERED = 1 # Not yet implemented
169 RASTERIZE = 2 # Not yet implemented
170 FLOYDSTEINBERG = 3 # default
173# palettes/quantizers
174class Palette(IntEnum):
175 WEB = 0
176 ADAPTIVE = 1
179class Quantize(IntEnum):
180 MEDIANCUT = 0
181 MAXCOVERAGE = 1
182 FASTOCTREE = 2
183 LIBIMAGEQUANT = 3
186module = sys.modules[__name__]
187for enum in (Transpose, Transform, Resampling, Dither, Palette, Quantize):
188 for item in enum:
189 setattr(module, item.name, item.value)
192if hasattr(core, "DEFAULT_STRATEGY"):
193 DEFAULT_STRATEGY = core.DEFAULT_STRATEGY
194 FILTERED = core.FILTERED
195 HUFFMAN_ONLY = core.HUFFMAN_ONLY
196 RLE = core.RLE
197 FIXED = core.FIXED
200# --------------------------------------------------------------------
201# Registries
203TYPE_CHECKING = False
204if TYPE_CHECKING:
205 import mmap
206 from xml.etree.ElementTree import Element
208 from IPython.lib.pretty import PrettyPrinter
210 from . import ImageFile, ImageFilter, ImagePalette, ImageQt, TiffImagePlugin
211 from ._typing import CapsuleType, NumpyArray, StrOrBytesPath
212ID: list[str] = []
213OPEN: dict[
214 str,
215 tuple[
216 Callable[[IO[bytes], str | bytes], ImageFile.ImageFile],
217 Callable[[bytes], bool | str] | None,
218 ],
219] = {}
220MIME: dict[str, str] = {}
221SAVE: dict[str, Callable[[Image, IO[bytes], str | bytes], None]] = {}
222SAVE_ALL: dict[str, Callable[[Image, IO[bytes], str | bytes], None]] = {}
223EXTENSION: dict[str, str] = {}
224DECODERS: dict[str, type[ImageFile.PyDecoder]] = {}
225ENCODERS: dict[str, type[ImageFile.PyEncoder]] = {}
227# --------------------------------------------------------------------
228# Modes
230_ENDIAN = "<" if sys.byteorder == "little" else ">"
233def _conv_type_shape(im: Image) -> tuple[tuple[int, ...], str]:
234 m = ImageMode.getmode(im.mode)
235 shape: tuple[int, ...] = (im.height, im.width)
236 extra = len(m.bands)
237 if extra != 1:
238 shape += (extra,)
239 return shape, m.typestr
242MODES = [
243 "1",
244 "CMYK",
245 "F",
246 "HSV",
247 "I",
248 "I;16",
249 "I;16B",
250 "I;16L",
251 "I;16N",
252 "L",
253 "LA",
254 "La",
255 "LAB",
256 "P",
257 "PA",
258 "RGB",
259 "RGBA",
260 "RGBa",
261 "RGBX",
262 "YCbCr",
263]
265# raw modes that may be memory mapped. NOTE: if you change this, you
266# may have to modify the stride calculation in map.c too!
267_MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16L", "I;16B")
270def getmodebase(mode: str) -> str:
271 """
272 Gets the "base" mode for given mode. This function returns "L" for
273 images that contain grayscale data, and "RGB" for images that
274 contain color data.
276 :param mode: Input mode.
277 :returns: "L" or "RGB".
278 :exception KeyError: If the input mode was not a standard mode.
279 """
280 return ImageMode.getmode(mode).basemode
283def getmodetype(mode: str) -> str:
284 """
285 Gets the storage type mode. Given a mode, this function returns a
286 single-layer mode suitable for storing individual bands.
288 :param mode: Input mode.
289 :returns: "L", "I", or "F".
290 :exception KeyError: If the input mode was not a standard mode.
291 """
292 return ImageMode.getmode(mode).basetype
295def getmodebandnames(mode: str) -> tuple[str, ...]:
296 """
297 Gets a list of individual band names. Given a mode, this function returns
298 a tuple containing the names of individual bands (use
299 :py:method:`~PIL.Image.getmodetype` to get the mode used to store each
300 individual band.
302 :param mode: Input mode.
303 :returns: A tuple containing band names. The length of the tuple
304 gives the number of bands in an image of the given mode.
305 :exception KeyError: If the input mode was not a standard mode.
306 """
307 return ImageMode.getmode(mode).bands
310def getmodebands(mode: str) -> int:
311 """
312 Gets the number of individual bands for this mode.
314 :param mode: Input mode.
315 :returns: The number of bands in this mode.
316 :exception KeyError: If the input mode was not a standard mode.
317 """
318 return len(ImageMode.getmode(mode).bands)
321# --------------------------------------------------------------------
322# Helpers
324_initialized = 0
326# Mapping from file extension to plugin module name for lazy importing
327_EXTENSION_PLUGIN: dict[str, str] = {
328 # Common formats (preinit)
329 ".bmp": "BmpImagePlugin",
330 ".dib": "BmpImagePlugin",
331 ".gif": "GifImagePlugin",
332 ".jfif": "JpegImagePlugin",
333 ".jpe": "JpegImagePlugin",
334 ".jpg": "JpegImagePlugin",
335 ".jpeg": "JpegImagePlugin",
336 ".pbm": "PpmImagePlugin",
337 ".pgm": "PpmImagePlugin",
338 ".pnm": "PpmImagePlugin",
339 ".ppm": "PpmImagePlugin",
340 ".pfm": "PpmImagePlugin",
341 ".png": "PngImagePlugin",
342 ".apng": "PngImagePlugin",
343 # Less common formats (init)
344 ".avif": "AvifImagePlugin",
345 ".avifs": "AvifImagePlugin",
346 ".blp": "BlpImagePlugin",
347 ".bufr": "BufrStubImagePlugin",
348 ".cur": "CurImagePlugin",
349 ".dcx": "DcxImagePlugin",
350 ".dds": "DdsImagePlugin",
351 ".ps": "EpsImagePlugin",
352 ".eps": "EpsImagePlugin",
353 ".fit": "FitsImagePlugin",
354 ".fits": "FitsImagePlugin",
355 ".fli": "FliImagePlugin",
356 ".flc": "FliImagePlugin",
357 ".fpx": "FpxImagePlugin",
358 ".ftc": "FtexImagePlugin",
359 ".ftu": "FtexImagePlugin",
360 ".gbr": "GbrImagePlugin",
361 ".grib": "GribStubImagePlugin",
362 ".h5": "Hdf5StubImagePlugin",
363 ".hdf": "Hdf5StubImagePlugin",
364 ".icns": "IcnsImagePlugin",
365 ".ico": "IcoImagePlugin",
366 ".im": "ImImagePlugin",
367 ".iim": "IptcImagePlugin",
368 ".jp2": "Jpeg2KImagePlugin",
369 ".j2k": "Jpeg2KImagePlugin",
370 ".jpc": "Jpeg2KImagePlugin",
371 ".jpf": "Jpeg2KImagePlugin",
372 ".jpx": "Jpeg2KImagePlugin",
373 ".j2c": "Jpeg2KImagePlugin",
374 ".mic": "MicImagePlugin",
375 ".mpg": "MpegImagePlugin",
376 ".mpeg": "MpegImagePlugin",
377 ".mpo": "MpoImagePlugin",
378 ".msp": "MspImagePlugin",
379 ".palm": "PalmImagePlugin",
380 ".pcd": "PcdImagePlugin",
381 ".pcx": "PcxImagePlugin",
382 ".pdf": "PdfImagePlugin",
383 ".pxr": "PixarImagePlugin",
384 ".psd": "PsdImagePlugin",
385 ".qoi": "QoiImagePlugin",
386 ".bw": "SgiImagePlugin",
387 ".rgb": "SgiImagePlugin",
388 ".rgba": "SgiImagePlugin",
389 ".sgi": "SgiImagePlugin",
390 ".ras": "SunImagePlugin",
391 ".tga": "TgaImagePlugin",
392 ".icb": "TgaImagePlugin",
393 ".vda": "TgaImagePlugin",
394 ".vst": "TgaImagePlugin",
395 ".tif": "TiffImagePlugin",
396 ".tiff": "TiffImagePlugin",
397 ".webp": "WebPImagePlugin",
398 ".wmf": "WmfImagePlugin",
399 ".emf": "WmfImagePlugin",
400 ".xbm": "XbmImagePlugin",
401 ".xpm": "XpmImagePlugin",
402}
405def _import_plugin_for_extension(ext: str | bytes) -> bool:
406 """Import only the plugin needed for a specific file extension."""
407 if not ext:
408 return False
410 if isinstance(ext, bytes):
411 ext = ext.decode()
412 ext = ext.lower()
413 if ext in EXTENSION:
414 return True
416 plugin = _EXTENSION_PLUGIN.get(ext)
417 if plugin is None:
418 return False
420 try:
421 logger.debug("Importing %s", plugin)
422 __import__(f"{__spec__.parent}.{plugin}", globals(), locals(), [])
423 return True
424 except ImportError as e:
425 logger.debug("Image: failed to import %s: %s", plugin, e)
426 return False
429def preinit() -> None:
430 """
431 Explicitly loads BMP, GIF, JPEG, PPM and PNG file format drivers.
433 It is called when opening or saving images.
434 """
436 global _initialized
437 if _initialized >= 1:
438 return
440 try:
441 from . import BmpImagePlugin
443 assert BmpImagePlugin
444 except ImportError:
445 pass
446 try:
447 from . import GifImagePlugin
449 assert GifImagePlugin
450 except ImportError:
451 pass
452 try:
453 from . import JpegImagePlugin
455 assert JpegImagePlugin
456 except ImportError:
457 pass
458 try:
459 from . import PpmImagePlugin
461 assert PpmImagePlugin
462 except ImportError:
463 pass
464 try:
465 from . import PngImagePlugin
467 assert PngImagePlugin
468 except ImportError:
469 pass
471 _initialized = 1
474def init() -> bool:
475 """
476 Explicitly initializes the Python Imaging Library. This function
477 loads all available file format drivers.
479 It is called when opening or saving images if :py:meth:`~preinit()` is
480 insufficient, and by :py:meth:`~PIL.features.pilinfo`.
481 """
483 global _initialized
484 if _initialized >= 2:
485 return False
487 for plugin in _plugins:
488 try:
489 logger.debug("Importing %s", plugin)
490 __import__(f"{__spec__.parent}.{plugin}", globals(), locals(), [])
491 except ImportError as e:
492 logger.debug("Image: failed to import %s: %s", plugin, e)
494 if OPEN or SAVE:
495 _initialized = 2
496 return True
497 return False
500# --------------------------------------------------------------------
501# Codec factories (used by tobytes/frombytes and ImageFile.load)
504def _getdecoder(
505 mode: str, decoder_name: str, args: Any, extra: tuple[Any, ...] = ()
506) -> core.ImagingDecoder | ImageFile.PyDecoder:
507 # tweak arguments
508 if args is None:
509 args = ()
510 elif not isinstance(args, tuple):
511 args = (args,)
513 try:
514 decoder = DECODERS[decoder_name]
515 except KeyError:
516 pass
517 else:
518 return decoder(mode, *args + extra)
520 try:
521 # get decoder
522 decoder = getattr(core, f"{decoder_name}_decoder")
523 except AttributeError as e:
524 msg = f"decoder {decoder_name} not available"
525 raise OSError(msg) from e
526 return decoder(mode, *args + extra)
529def _getencoder(
530 mode: str, encoder_name: str, args: Any, extra: tuple[Any, ...] = ()
531) -> core.ImagingEncoder | ImageFile.PyEncoder:
532 # tweak arguments
533 if args is None:
534 args = ()
535 elif not isinstance(args, tuple):
536 args = (args,)
538 try:
539 encoder = ENCODERS[encoder_name]
540 except KeyError:
541 pass
542 else:
543 return encoder(mode, *args + extra)
545 try:
546 # get encoder
547 encoder = getattr(core, f"{encoder_name}_encoder")
548 except AttributeError as e:
549 msg = f"encoder {encoder_name} not available"
550 raise OSError(msg) from e
551 return encoder(mode, *args + extra)
554# --------------------------------------------------------------------
555# Simple expression analyzer
558class ImagePointTransform:
559 """
560 Used with :py:meth:`~PIL.Image.Image.point` for single band images with more than
561 8 bits, this represents an affine transformation, where the value is multiplied by
562 ``scale`` and ``offset`` is added.
563 """
565 def __init__(self, scale: float, offset: float) -> None:
566 self.scale = scale
567 self.offset = offset
569 def __neg__(self) -> ImagePointTransform:
570 return ImagePointTransform(-self.scale, -self.offset)
572 def __add__(self, other: ImagePointTransform | float) -> ImagePointTransform:
573 if isinstance(other, ImagePointTransform):
574 return ImagePointTransform(
575 self.scale + other.scale, self.offset + other.offset
576 )
577 return ImagePointTransform(self.scale, self.offset + other)
579 __radd__ = __add__
581 def __sub__(self, other: ImagePointTransform | float) -> ImagePointTransform:
582 return self + -other
584 def __rsub__(self, other: ImagePointTransform | float) -> ImagePointTransform:
585 return other + -self
587 def __mul__(self, other: ImagePointTransform | float) -> ImagePointTransform:
588 if isinstance(other, ImagePointTransform):
589 return NotImplemented
590 return ImagePointTransform(self.scale * other, self.offset * other)
592 __rmul__ = __mul__
594 def __truediv__(self, other: ImagePointTransform | float) -> ImagePointTransform:
595 if isinstance(other, ImagePointTransform):
596 return NotImplemented
597 return ImagePointTransform(self.scale / other, self.offset / other)
600def _getscaleoffset(
601 expr: Callable[[ImagePointTransform], ImagePointTransform | float],
602) -> tuple[float, float]:
603 a = expr(ImagePointTransform(1, 0))
604 return (a.scale, a.offset) if isinstance(a, ImagePointTransform) else (0, a)
607# --------------------------------------------------------------------
608# Implementation wrapper
611class SupportsGetData(Protocol):
612 def getdata(
613 self,
614 ) -> tuple[Transform, Sequence[int]]: ...
617class Image:
618 """
619 This class represents an image object. To create
620 :py:class:`~PIL.Image.Image` objects, use the appropriate factory
621 functions. There's hardly ever any reason to call the Image constructor
622 directly.
624 * :py:func:`~PIL.Image.open`
625 * :py:func:`~PIL.Image.new`
626 * :py:func:`~PIL.Image.frombytes`
627 """
629 format: str | None = None
630 format_description: str | None = None
631 _close_exclusive_fp_after_loading = True
633 def __init__(self) -> None:
634 # FIXME: take "new" parameters / other image?
635 self._im: core.ImagingCore | DeferredError | None = None
636 self._mode = ""
637 self._size = (0, 0)
638 self.palette: ImagePalette.ImagePalette | None = None
639 self.info: dict[str | tuple[int, int], Any] = {}
640 self.readonly = 0
641 self._exif: Exif | None = None
643 @property
644 def im(self) -> core.ImagingCore:
645 if isinstance(self._im, DeferredError):
646 raise self._im.ex
647 assert self._im is not None
648 return self._im
650 @im.setter
651 def im(self, im: core.ImagingCore) -> None:
652 self._im = im
654 @property
655 def width(self) -> int:
656 return self.size[0]
658 @property
659 def height(self) -> int:
660 return self.size[1]
662 @property
663 def size(self) -> tuple[int, int]:
664 return self._size
666 @property
667 def mode(self) -> str:
668 return self._mode
670 @property
671 def readonly(self) -> int:
672 return (self._im and self._im.readonly) or self._readonly
674 @readonly.setter
675 def readonly(self, readonly: int) -> None:
676 self._readonly = readonly
678 def _new(self, im: core.ImagingCore) -> Image:
679 new = Image()
680 new.im = im
681 new._mode = im.mode
682 new._size = im.size
683 if im.mode in ("P", "PA"):
684 if self.palette:
685 new.palette = self.palette.copy()
686 else:
687 from . import ImagePalette
689 new.palette = ImagePalette.ImagePalette()
690 new.info = self.info.copy()
691 return new
693 # Context manager support
694 def __enter__(self) -> Image:
695 return self
697 def __exit__(self, *args: object) -> None:
698 pass
700 def close(self) -> None:
701 """
702 This operation will destroy the image core and release its memory.
703 The image data will be unusable afterward.
705 This function is required to close images that have multiple frames or
706 have not had their file read and closed by the
707 :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for
708 more information.
709 """
710 if getattr(self, "map", None):
711 if sys.platform == "win32" and hasattr(sys, "pypy_version_info"):
712 self.map.close()
713 self.map: mmap.mmap | None = None
715 # Instead of simply setting to None, we're setting up a
716 # deferred error that will better explain that the core image
717 # object is gone.
718 self._im = DeferredError(ValueError("Operation on closed image"))
720 def _copy(self) -> None:
721 self.load()
722 self.im = self.im.copy()
723 self.readonly = 0
725 def _ensure_mutable(self) -> None:
726 if self.readonly:
727 self._copy()
728 else:
729 self.load()
731 def _dump(
732 self, file: str | None = None, format: str | None = None, **options: Any
733 ) -> str:
734 suffix = ""
735 if format:
736 suffix = f".{format}"
738 if not file:
739 f, filename = tempfile.mkstemp(suffix)
740 os.close(f)
741 else:
742 filename = file
743 if not filename.endswith(suffix):
744 filename = filename + suffix
746 self.load()
748 if not format or format == "PPM":
749 self.im.save_ppm(filename)
750 else:
751 self.save(filename, format, **options)
753 return filename
755 def __eq__(self, other: object) -> bool:
756 if self.__class__ is not other.__class__:
757 return False
758 assert isinstance(other, Image)
759 return (
760 self.mode == other.mode
761 and self.size == other.size
762 and self.info == other.info
763 and self.getpalette() == other.getpalette()
764 and self.tobytes() == other.tobytes()
765 )
767 def __repr__(self) -> str:
768 return (
769 f"<{self.__class__.__module__}.{self.__class__.__name__} "
770 f"image mode={self.mode} size={self.size[0]}x{self.size[1]} "
771 f"at 0x{id(self):X}>"
772 )
774 def _repr_pretty_(self, p: PrettyPrinter, cycle: bool) -> None:
775 """IPython plain text display support"""
777 # Same as __repr__ but without unpredictable id(self),
778 # to keep Jupyter notebook `text/plain` output stable.
779 p.text(
780 f"<{self.__class__.__module__}.{self.__class__.__name__} "
781 f"image mode={self.mode} size={self.size[0]}x{self.size[1]}>"
782 )
784 def _repr_image(self, image_format: str, **kwargs: Any) -> bytes | None:
785 """Helper function for iPython display hook.
787 :param image_format: Image format.
788 :returns: image as bytes, saved into the given format.
789 """
790 b = io.BytesIO()
791 try:
792 self.save(b, image_format, **kwargs)
793 except Exception:
794 return None
795 return b.getvalue()
797 def _repr_png_(self) -> bytes | None:
798 """iPython display hook support for PNG format.
800 :returns: PNG version of the image as bytes
801 """
802 return self._repr_image("PNG", compress_level=1)
804 def _repr_jpeg_(self) -> bytes | None:
805 """iPython display hook support for JPEG format.
807 :returns: JPEG version of the image as bytes
808 """
809 return self._repr_image("JPEG")
811 @property
812 def __array_interface__(self) -> dict[str, str | bytes | int | tuple[int, ...]]:
813 # numpy array interface support
814 new: dict[str, str | bytes | int | tuple[int, ...]] = {"version": 3}
815 if self.mode == "1":
816 # Binary images need to be extended from bits to bytes
817 # See: https://github.com/python-pillow/Pillow/issues/350
818 new["data"] = self.tobytes("raw", "L")
819 else:
820 new["data"] = self.tobytes()
821 new["shape"], new["typestr"] = _conv_type_shape(self)
822 return new
824 def __arrow_c_schema__(self) -> object:
825 self.load()
826 return self.im.__arrow_c_schema__()
828 def __arrow_c_array__(
829 self, requested_schema: object | None = None
830 ) -> tuple[object, object]:
831 self.load()
832 return (self.im.__arrow_c_schema__(), self.im.__arrow_c_array__())
834 def __getstate__(self) -> list[Any]:
835 im_data = self.tobytes() # load image first
836 return [self.info, self.mode, self.size, self.getpalette(), im_data]
838 def __setstate__(self, state: list[Any]) -> None:
839 Image.__init__(self)
840 info, mode, size, palette, data = state[:5]
841 self.info = info
842 self._mode = mode
843 self._size = size
844 self.im = core.new(mode, size)
845 if mode in ("L", "LA", "P", "PA") and palette:
846 self.putpalette(palette)
847 self.frombytes(data)
849 def tobytes(self, encoder_name: str = "raw", *args: Any) -> bytes:
850 """
851 Return image as a bytes object.
853 .. warning::
855 This method returns raw image data derived from Pillow's internal
856 storage. For compressed image data (e.g. PNG, JPEG) use
857 :meth:`~.save`, with a BytesIO parameter for in-memory data.
859 :param encoder_name: What encoder to use.
861 The default is to use the standard "raw" encoder.
862 To see how this packs pixel data into the returned
863 bytes, see :file:`libImaging/Pack.c`.
865 A list of C encoders can be seen under codecs
866 section of the function array in
867 :file:`_imaging.c`. Python encoders are registered
868 within the relevant plugins.
869 :param args: Extra arguments to the encoder.
870 :returns: A :py:class:`bytes` object.
871 """
873 encoder_args: Any = args
874 if len(encoder_args) == 1 and isinstance(encoder_args[0], tuple):
875 # may pass tuple instead of argument list
876 encoder_args = encoder_args[0]
878 if encoder_name == "raw" and encoder_args == ():
879 encoder_args = self.mode
881 self.load()
883 if self.width == 0 or self.height == 0:
884 return b""
886 # unpack data
887 e = _getencoder(self.mode, encoder_name, encoder_args)
888 e.setimage(self.im)
890 from . import ImageFile
892 bufsize = max(ImageFile.MAXBLOCK, self.size[0] * 4) # see RawEncode.c
894 output = []
895 while True:
896 bytes_consumed, errcode, data = e.encode(bufsize)
897 output.append(data)
898 if errcode:
899 break
900 if errcode < 0:
901 msg = f"encoder error {errcode} in tobytes"
902 raise RuntimeError(msg)
904 return b"".join(output)
906 def tobitmap(self, name: str = "image") -> bytes:
907 """
908 Returns the image converted to an X11 bitmap.
910 .. note:: This method only works for mode "1" images.
912 :param name: The name prefix to use for the bitmap variables.
913 :returns: A string containing an X11 bitmap.
914 :raises ValueError: If the mode is not "1"
915 """
917 self.load()
918 if self.mode != "1":
919 msg = "not a bitmap"
920 raise ValueError(msg)
921 data = self.tobytes("xbm")
922 return b"".join(
923 [
924 f"#define {name}_width {self.size[0]}\n".encode("ascii"),
925 f"#define {name}_height {self.size[1]}\n".encode("ascii"),
926 f"static char {name}_bits[] = {{\n".encode("ascii"),
927 data,
928 b"};",
929 ]
930 )
932 def frombytes(
933 self,
934 data: bytes | bytearray | SupportsArrayInterface,
935 decoder_name: str = "raw",
936 *args: Any,
937 ) -> None:
938 """
939 Loads this image with pixel data from a bytes object.
941 This method is similar to the :py:func:`~PIL.Image.frombytes` function,
942 but loads data into this image instead of creating a new image object.
943 """
945 if self.width == 0 or self.height == 0:
946 return
948 decoder_args: Any = args
949 if len(decoder_args) == 1 and isinstance(decoder_args[0], tuple):
950 # may pass tuple instead of argument list
951 decoder_args = decoder_args[0]
953 # default format
954 if decoder_name == "raw" and decoder_args == ():
955 decoder_args = self.mode
957 # unpack data
958 d = _getdecoder(self.mode, decoder_name, decoder_args)
959 d.setimage(self.im)
960 s = d.decode(data)
962 if s[0] >= 0:
963 msg = "not enough image data"
964 raise ValueError(msg)
965 if s[1] != 0:
966 msg = "cannot decode image data"
967 raise ValueError(msg)
969 def load(self) -> core.PixelAccess | None:
970 """
971 Allocates storage for the image and loads the pixel data. In
972 normal cases, you don't need to call this method, since the
973 Image class automatically loads an opened image when it is
974 accessed for the first time.
976 If the file associated with the image was opened by Pillow, then this
977 method will close it. The exception to this is if the image has
978 multiple frames, in which case the file will be left open for seek
979 operations. See :ref:`file-handling` for more information.
981 :returns: An image access object.
982 :rtype: :py:class:`.PixelAccess`
983 """
984 if self._im is not None and self.palette and self.palette.dirty:
985 # realize palette
986 mode, arr = self.palette.getdata()
987 self.im.putpalette(self.palette.mode, mode, arr)
988 self.palette.dirty = 0
989 self.palette.rawmode = None
990 if "transparency" in self.info and mode in ("LA", "PA"):
991 if isinstance(self.info["transparency"], int):
992 self.im.putpalettealpha(self.info["transparency"], 0)
993 else:
994 self.im.putpalettealphas(self.info["transparency"])
995 self.palette.mode = "RGBA"
996 elif self.palette.mode != mode:
997 # If the palette rawmode is different to the mode,
998 # then update the Python palette data
999 self.palette.palette = self.im.getpalette(
1000 self.palette.mode, self.palette.mode
1001 )
1003 if self._im is not None:
1004 return self.im.pixel_access(self.readonly)
1005 return None
1007 def verify(self) -> None:
1008 """
1009 Verifies the contents of a file. For data read from a file, this
1010 method attempts to determine if the file is broken, without
1011 actually decoding the image data. If this method finds any
1012 problems, it raises suitable exceptions. If you need to load
1013 the image after using this method, you must reopen the image
1014 file.
1015 """
1016 pass
1018 def convert(
1019 self,
1020 mode: str | None = None,
1021 matrix: tuple[float, ...] | None = None,
1022 dither: Dither | None = None,
1023 palette: Palette = Palette.WEB,
1024 colors: int = 256,
1025 ) -> Image:
1026 """
1027 Returns a converted copy of this image. For the "P" mode, this
1028 method translates pixels through the palette. If mode is
1029 omitted, a mode is chosen so that all information in the image
1030 and the palette can be represented without a palette.
1032 This supports all possible conversions between "L", "RGB" and "CMYK". The
1033 ``matrix`` argument only supports "L" and "RGB".
1035 When translating a color image to grayscale (mode "L"),
1036 the library uses the ITU-R 601-2 luma transform::
1038 L = R * 299/1000 + G * 587/1000 + B * 114/1000
1040 The default method of converting a grayscale ("L") or "RGB"
1041 image into a bilevel (mode "1") image uses Floyd-Steinberg
1042 dither to approximate the original image luminosity levels. If
1043 dither is ``None``, all values larger than 127 are set to 255 (white),
1044 all other values to 0 (black). To use other thresholds, use the
1045 :py:meth:`~PIL.Image.Image.point` method.
1047 When converting from "RGBA" to "P" without a ``matrix`` argument,
1048 this passes the operation to :py:meth:`~PIL.Image.Image.quantize`,
1049 and ``dither`` and ``palette`` are ignored.
1051 When converting from "PA", if an "RGBA" palette is present, the alpha
1052 channel from the image will be used instead of the values from the palette.
1054 :param mode: The requested mode. See: :ref:`concept-modes`.
1055 :param matrix: An optional conversion matrix. If given, this
1056 should be 4- or 12-tuple containing floating point values.
1057 :param dither: Dithering method, used when converting from
1058 mode "RGB" to "P" or from "RGB" or "L" to "1".
1059 Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG`
1060 (default). Note that this is not used when ``matrix`` is supplied.
1061 :param palette: Palette to use when converting from mode "RGB"
1062 to "P". Available palettes are :data:`Palette.WEB` or
1063 :data:`Palette.ADAPTIVE`.
1064 :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE`
1065 palette. Defaults to 256.
1066 :rtype: :py:class:`~PIL.Image.Image`
1067 :returns: An :py:class:`~PIL.Image.Image` object.
1068 """
1070 self.load()
1072 has_transparency = "transparency" in self.info
1073 if not mode and self.mode == "P":
1074 # determine default mode
1075 if self.palette:
1076 mode = self.palette.mode
1077 else:
1078 mode = "RGB"
1079 if mode == "RGB" and has_transparency:
1080 mode = "RGBA"
1081 if not mode or (mode == self.mode and not matrix):
1082 return self.copy()
1084 if matrix:
1085 # matrix conversion
1086 if mode not in ("L", "RGB"):
1087 msg = "illegal conversion"
1088 raise ValueError(msg)
1089 im = self.im.convert_matrix(mode, matrix)
1090 new_im = self._new(im)
1091 if has_transparency and self.im.bands == 3:
1092 transparency = new_im.info["transparency"]
1094 def convert_transparency(
1095 m: tuple[float, ...], v: tuple[int, int, int]
1096 ) -> int:
1097 value = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5
1098 return max(0, min(255, int(value)))
1100 if mode == "L":
1101 transparency = convert_transparency(matrix, transparency)
1102 elif len(mode) == 3:
1103 transparency = tuple(
1104 convert_transparency(matrix[i * 4 : i * 4 + 4], transparency)
1105 for i in range(len(transparency))
1106 )
1107 new_im.info["transparency"] = transparency
1108 return new_im
1110 if self.mode == "RGBA":
1111 if mode == "P":
1112 return self.quantize(colors)
1113 elif mode == "PA":
1114 r, g, b, a = self.split()
1115 rgb = merge("RGB", (r, g, b))
1116 p = rgb.quantize(colors)
1117 return merge("PA", (p, a))
1119 trns = None
1120 delete_trns = False
1121 # transparency handling
1122 if has_transparency:
1123 if (self.mode in ("1", "L", "I", "I;16") and mode in ("LA", "RGBA")) or (
1124 self.mode == "RGB" and mode in ("La", "LA", "RGBa", "RGBA")
1125 ):
1126 # Use transparent conversion to promote from transparent
1127 # color to an alpha channel.
1128 new_im = self._new(
1129 self.im.convert_transparent(mode, self.info["transparency"])
1130 )
1131 del new_im.info["transparency"]
1132 return new_im
1133 elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"):
1134 t = self.info["transparency"]
1135 if isinstance(t, bytes):
1136 # Dragons. This can't be represented by a single color
1137 warnings.warn(
1138 "Palette images with Transparency expressed in bytes should be "
1139 "converted to RGBA images"
1140 )
1141 delete_trns = True
1142 else:
1143 # get the new transparency color.
1144 # use existing conversions
1145 trns_im = new(self.mode, (1, 1))
1146 if self.mode == "P":
1147 assert self.palette is not None
1148 trns_im.putpalette(self.palette, self.palette.mode)
1149 if isinstance(t, tuple):
1150 err = "Couldn't allocate a palette color for transparency"
1151 assert trns_im.palette is not None
1152 try:
1153 t = trns_im.palette.getcolor(t, self)
1154 except ValueError as e:
1155 if str(e) == "cannot allocate more than 256 colors":
1156 # If all 256 colors are in use,
1157 # then there is no need for transparency
1158 t = None
1159 else:
1160 raise ValueError(err) from e
1161 if t is None:
1162 trns = None
1163 else:
1164 trns_im.putpixel((0, 0), t)
1166 if mode in ("L", "RGB"):
1167 trns_im = trns_im.convert(mode)
1168 else:
1169 # can't just retrieve the palette number, got to do it
1170 # after quantization.
1171 trns_im = trns_im.convert("RGB")
1172 trns = trns_im.getpixel((0, 0))
1174 elif self.mode == "P" and mode in ("LA", "PA", "RGBA"):
1175 t = self.info["transparency"]
1176 delete_trns = True
1178 if isinstance(t, bytes):
1179 self.im.putpalettealphas(t)
1180 elif isinstance(t, int):
1181 self.im.putpalettealpha(t, 0)
1182 else:
1183 msg = "Transparency for P mode should be bytes or int"
1184 raise ValueError(msg)
1186 if mode == "P" and palette == Palette.ADAPTIVE:
1187 im = self.im.quantize(colors)
1188 new_im = self._new(im)
1189 from . import ImagePalette
1191 new_im.palette = ImagePalette.ImagePalette(
1192 "RGB", new_im.im.getpalette("RGB")
1193 )
1194 if delete_trns:
1195 # This could possibly happen if we requantize to fewer colors.
1196 # The transparency would be totally off in that case.
1197 del new_im.info["transparency"]
1198 if trns is not None:
1199 try:
1200 new_im.info["transparency"] = new_im.palette.getcolor(
1201 cast(tuple[int, ...], trns), # trns was converted to RGB
1202 new_im,
1203 )
1204 except Exception:
1205 # if we can't make a transparent color, don't leave the old
1206 # transparency hanging around to mess us up.
1207 del new_im.info["transparency"]
1208 warnings.warn("Couldn't allocate palette entry for transparency")
1209 return new_im
1211 if "LAB" in (self.mode, mode):
1212 im = self
1213 if mode == "LAB":
1214 if im.mode not in ("RGB", "RGBA", "RGBX"):
1215 im = im.convert("RGBA")
1216 other_mode = im.mode
1217 else:
1218 other_mode = mode
1219 if other_mode in ("RGB", "RGBA", "RGBX"):
1220 from . import ImageCms
1222 srgb = ImageCms.createProfile("sRGB")
1223 lab = ImageCms.createProfile("LAB")
1224 profiles = [lab, srgb] if im.mode == "LAB" else [srgb, lab]
1225 transform = ImageCms.buildTransform(
1226 profiles[0], profiles[1], im.mode, mode
1227 )
1228 return transform.apply(im)
1230 # colorspace conversion
1231 if dither is None:
1232 dither = Dither.FLOYDSTEINBERG
1234 try:
1235 im = self.im.convert(mode, dither)
1236 except ValueError:
1237 try:
1238 # normalize source image and try again
1239 modebase = getmodebase(self.mode)
1240 if modebase == self.mode:
1241 raise
1242 im = self.im.convert(modebase)
1243 im = im.convert(mode, dither)
1244 except KeyError as e:
1245 msg = "illegal conversion"
1246 raise ValueError(msg) from e
1248 new_im = self._new(im)
1249 if mode in ("P", "PA") and palette != Palette.ADAPTIVE:
1250 from . import ImagePalette
1252 new_im.palette = ImagePalette.ImagePalette("RGB", im.getpalette("RGB"))
1253 if delete_trns:
1254 # crash fail if we leave a bytes transparency in an rgb/l mode.
1255 del new_im.info["transparency"]
1256 if trns is not None:
1257 if new_im.mode == "P" and new_im.palette:
1258 try:
1259 new_im.info["transparency"] = new_im.palette.getcolor(
1260 cast(tuple[int, ...], trns), new_im # trns was converted to RGB
1261 )
1262 except ValueError as e:
1263 del new_im.info["transparency"]
1264 if str(e) != "cannot allocate more than 256 colors":
1265 # If all 256 colors are in use,
1266 # then there is no need for transparency
1267 warnings.warn(
1268 "Couldn't allocate palette entry for transparency"
1269 )
1270 else:
1271 new_im.info["transparency"] = trns
1272 return new_im
1274 def quantize(
1275 self,
1276 colors: int = 256,
1277 method: int | None = None,
1278 kmeans: int = 0,
1279 palette: Image | None = None,
1280 dither: Dither = Dither.FLOYDSTEINBERG,
1281 ) -> Image:
1282 """
1283 Convert the image to 'P' mode with the specified number
1284 of colors.
1286 :param colors: The desired number of colors, <= 256
1287 :param method: :data:`Quantize.MEDIANCUT` (median cut),
1288 :data:`Quantize.MAXCOVERAGE` (maximum coverage),
1289 :data:`Quantize.FASTOCTREE` (fast octree),
1290 :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support
1291 using :py:func:`PIL.features.check_feature` with
1292 ``feature="libimagequant"``).
1294 By default, :data:`Quantize.MEDIANCUT` will be used.
1296 The exception to this is RGBA images. :data:`Quantize.MEDIANCUT`
1297 and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so
1298 :data:`Quantize.FASTOCTREE` is used by default instead.
1299 :param kmeans: Integer greater than or equal to zero.
1300 :param palette: Quantize to the palette of given
1301 :py:class:`PIL.Image.Image`.
1302 :param dither: Dithering method, used when converting from
1303 mode "RGB" to "P" or from "RGB" or "L" to "1".
1304 Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG`
1305 (default).
1306 :returns: A new image
1307 """
1309 self.load()
1311 if method is None:
1312 # defaults:
1313 method = Quantize.MEDIANCUT
1314 if self.mode == "RGBA":
1315 method = Quantize.FASTOCTREE
1317 if self.mode == "RGBA" and method not in (
1318 Quantize.FASTOCTREE,
1319 Quantize.LIBIMAGEQUANT,
1320 ):
1321 # Caller specified an invalid mode.
1322 msg = (
1323 "Fast Octree (method == 2) and libimagequant (method == 3) "
1324 "are the only valid methods for quantizing RGBA images"
1325 )
1326 raise ValueError(msg)
1328 if palette:
1329 # use palette from reference image
1330 palette.load()
1331 if palette.mode != "P":
1332 msg = "bad mode for palette image"
1333 raise ValueError(msg)
1334 if self.mode not in {"RGB", "L"}:
1335 msg = "only RGB or L mode images can be quantized to a palette"
1336 raise ValueError(msg)
1337 im = self.im.convert("P", dither, palette.im)
1338 new_im = self._new(im)
1339 assert palette.palette is not None
1340 new_im.palette = palette.palette.copy()
1341 return new_im
1343 if kmeans < 0:
1344 msg = "kmeans must not be negative"
1345 raise ValueError(msg)
1347 im = self._new(self.im.quantize(colors, method, kmeans))
1349 from . import ImagePalette
1351 mode = im.im.getpalettemode()
1352 palette_data = im.im.getpalette(mode, mode)[: colors * len(mode)]
1353 im.palette = ImagePalette.ImagePalette(mode, palette_data)
1355 return im
1357 def copy(self) -> Image:
1358 """
1359 Copies this image. Use this method if you wish to paste things
1360 into an image, but still retain the original.
1362 :rtype: :py:class:`~PIL.Image.Image`
1363 :returns: An :py:class:`~PIL.Image.Image` object.
1364 """
1365 self.load()
1366 return self._new(self.im.copy())
1368 __copy__ = copy
1370 def crop(self, box: tuple[float, float, float, float] | None = None) -> Image:
1371 """
1372 Returns a rectangular region from this image. The box is a
1373 4-tuple defining the left, upper, right, and lower pixel
1374 coordinate. See :ref:`coordinate-system`.
1376 Note: Prior to Pillow 3.4.0, this was a lazy operation.
1378 :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
1379 :rtype: :py:class:`~PIL.Image.Image`
1380 :returns: An :py:class:`~PIL.Image.Image` object.
1381 """
1383 if box is None:
1384 return self.copy()
1386 if box[2] < box[0]:
1387 msg = "Coordinate 'right' is less than 'left'"
1388 raise ValueError(msg)
1389 elif box[3] < box[1]:
1390 msg = "Coordinate 'lower' is less than 'upper'"
1391 raise ValueError(msg)
1393 self.load()
1394 return self._new(self._crop(self.im, box))
1396 def _crop(
1397 self, im: core.ImagingCore, box: tuple[float, float, float, float]
1398 ) -> core.ImagingCore:
1399 """
1400 Returns a rectangular region from the core image object im.
1402 This is equivalent to calling im.crop((x0, y0, x1, y1)), but
1403 includes additional sanity checks.
1405 :param im: a core image object
1406 :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
1407 :returns: A core image object.
1408 """
1410 x0, y0, x1, y1 = map(int, map(round, box))
1412 absolute_values = (abs(x1 - x0), abs(y1 - y0))
1414 _decompression_bomb_check(absolute_values)
1416 return im.crop((x0, y0, x1, y1))
1418 def draft(
1419 self, mode: str | None, size: tuple[int, int] | None
1420 ) -> tuple[str, tuple[int, int, float, float]] | None:
1421 """
1422 Configures the image file loader so it returns a version of the
1423 image that as closely as possible matches the given mode and
1424 size. For example, you can use this method to convert a color
1425 JPEG to grayscale while loading it.
1427 If any changes are made, returns a tuple with the chosen ``mode`` and
1428 ``box`` with coordinates of the original image within the altered one.
1430 Note that this method modifies the :py:class:`~PIL.Image.Image` object
1431 in place. If the image has already been loaded, this method has no
1432 effect.
1434 Note: This method is not implemented for most images. It is
1435 currently implemented only for JPEG and MPO images.
1437 :param mode: The requested mode.
1438 :param size: The requested size in pixels, as a 2-tuple:
1439 (width, height).
1440 """
1441 pass
1443 def filter(self, filter: ImageFilter.Filter | type[ImageFilter.Filter]) -> Image:
1444 """
1445 Filters this image using the given filter. For a list of
1446 available filters, see the :py:mod:`~PIL.ImageFilter` module.
1448 :param filter: Filter kernel.
1449 :returns: An :py:class:`~PIL.Image.Image` object."""
1451 from . import ImageFilter
1453 self.load()
1455 if callable(filter):
1456 filter = filter()
1457 if not hasattr(filter, "filter"):
1458 msg = "filter argument should be ImageFilter.Filter instance or class"
1459 raise TypeError(msg)
1461 multiband = isinstance(filter, ImageFilter.MultibandFilter)
1462 if self.im.bands == 1 or multiband:
1463 return self._new(filter.filter(self.im))
1465 ims = [
1466 self._new(filter.filter(self.im.getband(c))) for c in range(self.im.bands)
1467 ]
1468 return merge(self.mode, ims)
1470 def getbands(self) -> tuple[str, ...]:
1471 """
1472 Returns a tuple containing the name of each band in this image.
1473 For example, ``getbands`` on an RGB image returns ("R", "G", "B").
1475 :returns: A tuple containing band names.
1476 :rtype: tuple
1477 """
1478 return ImageMode.getmode(self.mode).bands
1480 def getbbox(self, *, alpha_only: bool = True) -> tuple[int, int, int, int] | None:
1481 """
1482 Calculates the bounding box of the non-zero regions in the
1483 image.
1485 :param alpha_only: Optional flag, defaulting to ``True``.
1486 If ``True`` and the image has an alpha channel, trim transparent pixels.
1487 Otherwise, trim pixels when all channels are zero.
1488 Keyword-only argument.
1489 :returns: The bounding box is returned as a 4-tuple defining the
1490 left, upper, right, and lower pixel coordinate. See
1491 :ref:`coordinate-system`. If the image is completely empty, this
1492 method returns None.
1494 """
1496 self.load()
1497 return self.im.getbbox(alpha_only)
1499 def getcolors(
1500 self, maxcolors: int = 256
1501 ) -> list[tuple[int, tuple[int, ...]]] | list[tuple[int, float]] | None:
1502 """
1503 Returns a list of colors used in this image.
1505 The colors will be in the image's mode. For example, an RGB image will
1506 return a tuple of (red, green, blue) color values, and a P image will
1507 return the index of the color in the palette.
1509 :param maxcolors: Maximum number of colors. If this number is
1510 exceeded, this method returns None. The default limit is
1511 256 colors.
1512 :returns: An unsorted list of (count, pixel) values.
1513 """
1515 self.load()
1516 if self.mode in ("1", "L", "P"):
1517 h = self.im.histogram()
1518 out: list[tuple[int, float]] = [(h[i], i) for i in range(256) if h[i]]
1519 if len(out) > maxcolors:
1520 return None
1521 return out
1522 return self.im.getcolors(maxcolors)
1524 def getdata(self, band: int | None = None) -> core.ImagingCore:
1525 """
1526 Returns the contents of this image as a sequence object
1527 containing pixel values. The sequence object is flattened, so
1528 that values for line one follow directly after the values of
1529 line zero, and so on.
1531 Note that the sequence object returned by this method is an
1532 internal PIL data type, which only supports certain sequence
1533 operations. To convert it to an ordinary sequence (e.g. for
1534 printing), use ``list(im.getdata())``.
1536 :param band: What band to return. The default is to return
1537 all bands. To return a single band, pass in the index
1538 value (e.g. 0 to get the "R" band from an "RGB" image).
1539 :returns: A sequence-like object.
1540 """
1541 deprecate("Image.Image.getdata", 14, "get_flattened_data")
1543 self.load()
1544 if band is not None:
1545 return self.im.getband(band)
1546 return self.im # could be abused
1548 def get_flattened_data(
1549 self, band: int | None = None
1550 ) -> tuple[tuple[int, ...], ...] | tuple[float, ...]:
1551 """
1552 Returns the contents of this image as a tuple containing pixel values.
1553 The sequence object is flattened, so that values for line one follow
1554 directly after the values of line zero, and so on.
1556 :param band: What band to return. The default is to return
1557 all bands. To return a single band, pass in the index
1558 value (e.g. 0 to get the "R" band from an "RGB" image).
1559 :returns: A tuple containing pixel values.
1560 """
1561 self.load()
1562 if band is not None:
1563 return tuple(self.im.getband(band))
1564 return tuple(self.im)
1566 def getextrema(self) -> tuple[float, float] | tuple[tuple[int, int], ...]:
1567 """
1568 Gets the minimum and maximum pixel values for each band in
1569 the image.
1571 :returns: For a single-band image, a 2-tuple containing the
1572 minimum and maximum pixel value. For a multi-band image,
1573 a tuple containing one 2-tuple for each band.
1574 """
1576 self.load()
1577 if self.im.bands > 1:
1578 return tuple(self.im.getband(i).getextrema() for i in range(self.im.bands))
1579 return self.im.getextrema()
1581 def getxmp(self) -> dict[str, Any]:
1582 """
1583 Returns a dictionary containing the XMP tags.
1584 Requires defusedxml to be installed.
1586 :returns: XMP tags in a dictionary.
1587 """
1589 def get_name(tag: str) -> str:
1590 return re.sub("^{[^}]+}", "", tag)
1592 def get_value(element: Element) -> str | dict[str, Any] | None:
1593 value: dict[str, Any] = {get_name(k): v for k, v in element.attrib.items()}
1594 children = list(element)
1595 if children:
1596 for child in children:
1597 name = get_name(child.tag)
1598 child_value = get_value(child)
1599 if name in value:
1600 if not isinstance(value[name], list):
1601 value[name] = [value[name]]
1602 value[name].append(child_value)
1603 else:
1604 value[name] = child_value
1605 elif value:
1606 if element.text:
1607 value["text"] = element.text
1608 else:
1609 return element.text
1610 return value
1612 if ElementTree is None:
1613 warnings.warn("XMP data cannot be read without defusedxml dependency")
1614 return {}
1615 if "xmp" not in self.info:
1616 return {}
1617 root = ElementTree.fromstring(self.info["xmp"].rstrip(b"\x00 "))
1618 return {get_name(root.tag): get_value(root)}
1620 def getexif(self) -> Exif:
1621 """
1622 Gets EXIF data from the image.
1624 :returns: an :py:class:`~PIL.Image.Exif` object.
1625 """
1626 if self._exif is None:
1627 self._exif = Exif()
1628 elif self._exif._loaded:
1629 return self._exif
1630 self._exif._loaded = True
1632 exif_info = self.info.get("exif")
1633 if exif_info is None:
1634 if "Raw profile type exif" in self.info:
1635 exif_info = bytes.fromhex(
1636 "".join(self.info["Raw profile type exif"].split("\n")[3:])
1637 )
1638 elif hasattr(self, "tag_v2"):
1639 from . import TiffImagePlugin
1641 assert isinstance(self, TiffImagePlugin.TiffImageFile)
1642 self._exif.bigtiff = self.tag_v2._bigtiff
1643 self._exif.endian = self.tag_v2._endian
1645 assert self.fp is not None
1646 self._exif.load_from_fp(self.fp, self.tag_v2._offset)
1647 if exif_info is not None:
1648 self._exif.load(exif_info)
1650 # XMP tags
1651 if ExifTags.Base.Orientation not in self._exif:
1652 xmp_tags = self.info.get("XML:com.adobe.xmp")
1653 pattern: str | bytes = r'tiff:Orientation(="|>)([0-9])'
1654 if not xmp_tags and (xmp_tags := self.info.get("xmp")):
1655 pattern = rb'tiff:Orientation(="|>)([0-9])'
1656 if xmp_tags:
1657 match = re.search(pattern, xmp_tags)
1658 if match:
1659 self._exif[ExifTags.Base.Orientation] = int(match[2])
1661 return self._exif
1663 def _reload_exif(self) -> None:
1664 if self._exif is None or not self._exif._loaded:
1665 return
1666 self._exif._loaded = False
1667 self.getexif()
1669 def get_child_images(self) -> list[ImageFile.ImageFile]:
1670 from . import ImageFile
1672 deprecate("Image.Image.get_child_images", 13)
1673 return ImageFile.ImageFile.get_child_images(self) # type: ignore[arg-type]
1675 def getim(self) -> CapsuleType:
1676 """
1677 Returns a capsule that points to the internal image memory.
1679 :returns: A capsule object.
1680 """
1682 self.load()
1683 return self.im.ptr
1685 def getpalette(self, rawmode: str | None = "RGB") -> list[int] | None:
1686 """
1687 Returns the image palette as a list.
1689 :param rawmode: The mode in which to return the palette. ``None`` will
1690 return the palette in its current mode.
1692 .. versionadded:: 9.1.0
1694 :returns: A list of color values [r, g, b, ...], or None if the
1695 image has no palette.
1696 """
1698 self.load()
1699 try:
1700 mode = self.im.getpalettemode()
1701 except ValueError:
1702 return None # no palette
1703 if rawmode is None:
1704 rawmode = mode
1705 return list(self.im.getpalette(mode, rawmode))
1707 @property
1708 def has_transparency_data(self) -> bool:
1709 """
1710 Determine if an image has transparency data, whether in the form of an
1711 alpha channel, a palette with an alpha channel, or a "transparency" key
1712 in the info dictionary.
1714 Note the image might still appear solid, if all of the values shown
1715 within are opaque.
1717 :returns: A boolean.
1718 """
1719 if (
1720 self.mode in ("LA", "La", "PA", "RGBA", "RGBa")
1721 or "transparency" in self.info
1722 ):
1723 return True
1724 if self.mode == "P":
1725 assert self.palette is not None
1726 return self.palette.mode.endswith("A")
1727 return False
1729 def apply_transparency(self) -> None:
1730 """
1731 If a P mode image has a "transparency" key in the info dictionary,
1732 remove the key and instead apply the transparency to the palette.
1733 Otherwise, the image is unchanged.
1734 """
1735 if self.mode != "P" or "transparency" not in self.info:
1736 return
1738 from . import ImagePalette
1740 palette = self.getpalette("RGBA")
1741 assert palette is not None
1742 transparency = self.info["transparency"]
1743 if isinstance(transparency, bytes):
1744 for i, alpha in enumerate(transparency):
1745 palette[i * 4 + 3] = alpha
1746 else:
1747 palette[transparency * 4 + 3] = 0
1748 self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette))
1749 self.palette.dirty = 1
1751 del self.info["transparency"]
1753 def getpixel(
1754 self, xy: tuple[int, int] | list[int]
1755 ) -> float | tuple[int, ...] | None:
1756 """
1757 Returns the pixel value at a given position.
1759 :param xy: The coordinate, given as (x, y). See
1760 :ref:`coordinate-system`.
1761 :returns: The pixel value. If the image is a multi-layer image,
1762 this method returns a tuple.
1763 """
1765 self.load()
1766 return self.im.getpixel(tuple(xy))
1768 def getprojection(self) -> tuple[list[int], list[int]]:
1769 """
1770 Get projection to x and y axes
1772 :returns: Two sequences, indicating where there are non-zero
1773 pixels along the X-axis and the Y-axis, respectively.
1774 """
1776 self.load()
1777 x, y = self.im.getprojection()
1778 return list(x), list(y)
1780 def histogram(
1781 self, mask: Image | None = None, extrema: tuple[float, float] | None = None
1782 ) -> list[int]:
1783 """
1784 Returns a histogram for the image. The histogram is returned as a
1785 list of pixel counts, one for each pixel value in the source
1786 image. Counts are grouped into 256 bins for each band, even if
1787 the image has more than 8 bits per band. If the image has more
1788 than one band, the histograms for all bands are concatenated (for
1789 example, the histogram for an "RGB" image contains 768 values).
1791 A bilevel image (mode "1") is treated as a grayscale ("L") image
1792 by this method.
1794 If a mask is provided, the method returns a histogram for those
1795 parts of the image where the mask image is non-zero. The mask
1796 image must have the same size as the image, and be either a
1797 bi-level image (mode "1") or a grayscale image ("L").
1799 :param mask: An optional mask.
1800 :param extrema: An optional tuple of manually-specified extrema.
1801 :returns: A list containing pixel counts.
1802 """
1803 self.load()
1804 if mask:
1805 mask.load()
1806 return self.im.histogram((0, 0), mask.im)
1807 if self.mode in ("I", "F"):
1808 return self.im.histogram(
1809 extrema if extrema is not None else self.getextrema()
1810 )
1811 return self.im.histogram()
1813 def entropy(
1814 self, mask: Image | None = None, extrema: tuple[float, float] | None = None
1815 ) -> float:
1816 """
1817 Calculates and returns the entropy for the image.
1819 A bilevel image (mode "1") is treated as a grayscale ("L")
1820 image by this method.
1822 If a mask is provided, the method employs the histogram for
1823 those parts of the image where the mask image is non-zero.
1824 The mask image must have the same size as the image, and be
1825 either a bi-level image (mode "1") or a grayscale image ("L").
1827 :param mask: An optional mask.
1828 :param extrema: An optional tuple of manually-specified extrema.
1829 :returns: A float value representing the image entropy
1830 """
1831 self.load()
1832 if mask:
1833 mask.load()
1834 return self.im.entropy((0, 0), mask.im)
1835 if self.mode in ("I", "F"):
1836 return self.im.entropy(
1837 extrema if extrema is not None else self.getextrema()
1838 )
1839 return self.im.entropy()
1841 def paste(
1842 self,
1843 im: Image | str | float | tuple[float, ...],
1844 box: Image | tuple[int, int, int, int] | tuple[int, int] | None = None,
1845 mask: Image | None = None,
1846 ) -> None:
1847 """
1848 Pastes another image into this image. The box argument is either
1849 a 2-tuple giving the upper left corner, a 4-tuple defining the
1850 left, upper, right, and lower pixel coordinate, or None (same as
1851 (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size
1852 of the pasted image must match the size of the region.
1854 If the modes don't match, the pasted image is converted to the mode of
1855 this image (see the :py:meth:`~PIL.Image.Image.convert` method for
1856 details).
1858 Instead of an image, the source can be a integer or tuple
1859 containing pixel values. The method then fills the region
1860 with the given color. When creating RGB images, you can
1861 also use color strings as supported by the ImageColor module. See
1862 :ref:`colors` for more information.
1864 If a mask is given, this method updates only the regions
1865 indicated by the mask. You can use either "1", "L", "LA", "RGBA"
1866 or "RGBa" images (if present, the alpha band is used as mask).
1867 Where the mask is 255, the given image is copied as is. Where
1868 the mask is 0, the current value is preserved. Intermediate
1869 values will mix the two images together, including their alpha
1870 channels if they have them.
1872 See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to
1873 combine images with respect to their alpha channels.
1875 :param im: Source image or pixel value (integer, float or tuple).
1876 :param box: An optional 4-tuple giving the region to paste into.
1877 If a 2-tuple is used instead, it's treated as the upper left
1878 corner. If omitted or None, the source is pasted into the
1879 upper left corner.
1881 If an image is given as the second argument and there is no
1882 third, the box defaults to (0, 0), and the second argument
1883 is interpreted as a mask image.
1884 :param mask: An optional mask image.
1885 """
1887 if isinstance(box, Image):
1888 if mask is not None:
1889 msg = "If using second argument as mask, third argument must be None"
1890 raise ValueError(msg)
1891 # abbreviated paste(im, mask) syntax
1892 mask = box
1893 box = None
1895 if box is None:
1896 box = (0, 0)
1898 if len(box) == 2:
1899 # upper left corner given; get size from image or mask
1900 if isinstance(im, Image):
1901 size = im.size
1902 elif isinstance(mask, Image):
1903 size = mask.size
1904 else:
1905 # FIXME: use self.size here?
1906 msg = "cannot determine region size; use 4-item box"
1907 raise ValueError(msg)
1908 box += (box[0] + size[0], box[1] + size[1])
1910 source: core.ImagingCore | str | float | tuple[float, ...]
1911 if isinstance(im, str):
1912 from . import ImageColor
1914 source = ImageColor.getcolor(im, self.mode)
1915 elif isinstance(im, Image):
1916 im.load()
1917 if self.mode != im.mode:
1918 if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"):
1919 # should use an adapter for this!
1920 im = im.convert(self.mode)
1921 source = im.im
1922 else:
1923 source = im
1925 self._ensure_mutable()
1927 if mask:
1928 mask.load()
1929 self.im.paste(source, box, mask.im)
1930 else:
1931 self.im.paste(source, box)
1933 def alpha_composite(
1934 self, im: Image, dest: Sequence[int] = (0, 0), source: Sequence[int] = (0, 0)
1935 ) -> None:
1936 """'In-place' analog of Image.alpha_composite. Composites an image
1937 onto this image.
1939 :param im: image to composite over this one
1940 :param dest: Optional 2 tuple (left, top) specifying the upper
1941 left corner in this (destination) image.
1942 :param source: Optional 2 (left, top) tuple for the upper left
1943 corner in the overlay source image, or 4 tuple (left, top, right,
1944 bottom) for the bounds of the source rectangle
1946 Performance Note: Not currently implemented in-place in the core layer.
1947 """
1949 if not isinstance(source, (list, tuple)):
1950 msg = "Source must be a list or tuple"
1951 raise ValueError(msg)
1952 if not isinstance(dest, (list, tuple)):
1953 msg = "Destination must be a list or tuple"
1954 raise ValueError(msg)
1956 if len(source) == 4:
1957 overlay_crop_box = tuple(source)
1958 elif len(source) == 2:
1959 overlay_crop_box = tuple(source) + im.size
1960 else:
1961 msg = "Source must be a sequence of length 2 or 4"
1962 raise ValueError(msg)
1964 if not len(dest) == 2:
1965 msg = "Destination must be a sequence of length 2"
1966 raise ValueError(msg)
1967 if min(source) < 0:
1968 msg = "Source must be non-negative"
1969 raise ValueError(msg)
1971 # over image, crop if it's not the whole image.
1972 if overlay_crop_box == (0, 0) + im.size:
1973 overlay = im
1974 else:
1975 overlay = im.crop(overlay_crop_box)
1977 # target for the paste
1978 box = tuple(dest) + (dest[0] + overlay.width, dest[1] + overlay.height)
1980 # destination image. don't copy if we're using the whole image.
1981 if box == (0, 0) + self.size:
1982 background = self
1983 else:
1984 background = self.crop(box)
1986 result = alpha_composite(background, overlay)
1987 self.paste(result, box)
1989 def point(
1990 self,
1991 lut: (
1992 Sequence[float]
1993 | NumpyArray
1994 | Callable[[int], float]
1995 | Callable[[ImagePointTransform], ImagePointTransform | float]
1996 | ImagePointHandler
1997 ),
1998 mode: str | None = None,
1999 ) -> Image:
2000 """
2001 Maps this image through a lookup table or function.
2003 :param lut: A lookup table, containing 256 (or 65536 if
2004 self.mode=="I" and mode == "L") values per band in the
2005 image. A function can be used instead, it should take a
2006 single argument. The function is called once for each
2007 possible pixel value, and the resulting table is applied to
2008 all bands of the image.
2010 It may also be an :py:class:`~PIL.Image.ImagePointHandler`
2011 object::
2013 class Example(Image.ImagePointHandler):
2014 def point(self, im: Image) -> Image:
2015 # Return result
2016 :param mode: Output mode (default is same as input). This can only be used if
2017 the source image has mode "L" or "P", and the output has mode "1" or the
2018 source image mode is "I" and the output mode is "L".
2019 :returns: An :py:class:`~PIL.Image.Image` object.
2020 """
2022 self.load()
2024 if isinstance(lut, ImagePointHandler):
2025 return lut.point(self)
2027 if callable(lut):
2028 # if it isn't a list, it should be a function
2029 if self.mode in ("I", "I;16", "F"):
2030 # check if the function can be used with point_transform
2031 # UNDONE wiredfool -- I think this prevents us from ever doing
2032 # a gamma function point transform on > 8bit images.
2033 scale, offset = _getscaleoffset(lut) # type: ignore[arg-type]
2034 return self._new(self.im.point_transform(scale, offset))
2035 # for other modes, convert the function to a table
2036 flatLut = [lut(i) for i in range(256)] * self.im.bands # type: ignore[arg-type]
2037 else:
2038 flatLut = lut
2040 if self.mode == "F":
2041 # FIXME: _imaging returns a confusing error message for this case
2042 msg = "point operation not supported for this mode"
2043 raise ValueError(msg)
2045 if mode != "F":
2046 flatLut = [round(i) for i in flatLut]
2047 return self._new(self.im.point(flatLut, mode))
2049 def putalpha(self, alpha: Image | int) -> None:
2050 """
2051 Adds or replaces the alpha layer in this image. If the image
2052 does not have an alpha layer, it's converted to "LA" or "RGBA".
2053 The new layer must be either "L" or "1".
2055 :param alpha: The new alpha layer. This can either be an "L" or "1"
2056 image having the same size as this image, or an integer.
2057 """
2059 self._ensure_mutable()
2061 if self.mode not in ("LA", "PA", "RGBA"):
2062 # attempt to promote self to a matching alpha mode
2063 try:
2064 mode = getmodebase(self.mode) + "A"
2065 try:
2066 self.im.setmode(mode)
2067 except (AttributeError, ValueError) as e:
2068 # do things the hard way
2069 im = self.im.convert(mode)
2070 if im.mode not in ("LA", "PA", "RGBA"):
2071 msg = "alpha channel could not be added"
2072 raise ValueError(msg) from e # sanity check
2073 self.im = im
2074 self._mode = self.im.mode
2075 except KeyError as e:
2076 msg = "illegal image mode"
2077 raise ValueError(msg) from e
2079 if self.mode in ("LA", "PA"):
2080 band = 1
2081 else:
2082 band = 3
2084 if isinstance(alpha, Image):
2085 # alpha layer
2086 if alpha.mode not in ("1", "L"):
2087 msg = "illegal image mode"
2088 raise ValueError(msg)
2089 alpha.load()
2090 if alpha.mode == "1":
2091 alpha = alpha.convert("L")
2092 else:
2093 # constant alpha
2094 try:
2095 self.im.fillband(band, alpha)
2096 except (AttributeError, ValueError):
2097 # do things the hard way
2098 alpha = new("L", self.size, alpha)
2099 else:
2100 return
2102 self.im.putband(alpha.im, band)
2104 def putdata(
2105 self,
2106 data: Sequence[float] | Sequence[Sequence[int]] | core.ImagingCore | NumpyArray,
2107 scale: float = 1.0,
2108 offset: float = 0.0,
2109 ) -> None:
2110 """
2111 Copies pixel data from a flattened sequence object into the image. The
2112 values should start at the upper left corner (0, 0), continue to the
2113 end of the line, followed directly by the first value of the second
2114 line, and so on. Data will be read until either the image or the
2115 sequence ends. The scale and offset values are used to adjust the
2116 sequence values: **pixel = value*scale + offset**.
2118 :param data: A flattened sequence object. See :ref:`colors` for more
2119 information about values.
2120 :param scale: An optional scale value. The default is 1.0.
2121 :param offset: An optional offset value. The default is 0.0.
2122 """
2124 self._ensure_mutable()
2126 self.im.putdata(data, scale, offset)
2128 def putpalette(
2129 self,
2130 data: ImagePalette.ImagePalette | bytes | Sequence[int],
2131 rawmode: str = "RGB",
2132 ) -> None:
2133 """
2134 Attaches a palette to this image. The image must be a "P", "PA", "L"
2135 or "LA" image.
2137 The palette sequence must contain at most 256 colors, made up of one
2138 integer value for each channel in the raw mode.
2139 For example, if the raw mode is "RGB", then it can contain at most 768
2140 values, made up of red, green and blue values for the corresponding pixel
2141 index in the 256 colors.
2142 If the raw mode is "RGBA", then it can contain at most 1024 values,
2143 containing red, green, blue and alpha values.
2145 Alternatively, an 8-bit string may be used instead of an integer sequence.
2147 :param data: A palette sequence (either a list or a string).
2148 :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode
2149 that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L").
2150 """
2151 from . import ImagePalette
2153 if self.mode not in ("L", "LA", "P", "PA"):
2154 msg = "illegal image mode"
2155 raise ValueError(msg)
2156 if isinstance(data, ImagePalette.ImagePalette):
2157 if data.rawmode is not None:
2158 palette = ImagePalette.raw(data.rawmode, data.palette)
2159 else:
2160 palette = ImagePalette.ImagePalette(palette=data.palette)
2161 palette.dirty = 1
2162 else:
2163 if not isinstance(data, bytes):
2164 data = bytes(data)
2165 palette = ImagePalette.raw(rawmode, data)
2166 self._mode = "PA" if "A" in self.mode else "P"
2167 self.palette = palette
2168 self.palette.mode = "RGBA" if "A" in rawmode else "RGB"
2169 self.load() # install new palette
2171 def putpixel(
2172 self, xy: tuple[int, int], value: float | tuple[int, ...] | list[int]
2173 ) -> None:
2174 """
2175 Modifies the pixel at the given position. The color is given as
2176 a single numerical value for single-band images, and a tuple for
2177 multi-band images. In addition to this, RGB and RGBA tuples are
2178 accepted for P and PA images. See :ref:`colors` for more information.
2180 Note that this method is relatively slow. For more extensive changes,
2181 use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`
2182 module instead.
2184 See:
2186 * :py:meth:`~PIL.Image.Image.paste`
2187 * :py:meth:`~PIL.Image.Image.putdata`
2188 * :py:mod:`~PIL.ImageDraw`
2190 :param xy: The pixel coordinate, given as (x, y). See
2191 :ref:`coordinate-system`.
2192 :param value: The pixel value.
2193 """
2195 self._ensure_mutable()
2197 if (
2198 self.mode in ("P", "PA")
2199 and isinstance(value, (list, tuple))
2200 and len(value) in [3, 4]
2201 ):
2202 # RGB or RGBA value for a P or PA image
2203 if self.mode == "PA":
2204 alpha = value[3] if len(value) == 4 else 255
2205 value = value[:3]
2206 assert self.palette is not None
2207 palette_index = self.palette.getcolor(tuple(value), self)
2208 value = (palette_index, alpha) if self.mode == "PA" else palette_index
2209 return self.im.putpixel(xy, value)
2211 def remap_palette(
2212 self, dest_map: list[int], source_palette: bytes | bytearray | None = None
2213 ) -> Image:
2214 """
2215 Rewrites the image to reorder the palette.
2217 :param dest_map: A list of indexes into the original palette.
2218 e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))``
2219 is the identity transform.
2220 :param source_palette: Bytes or None.
2221 :returns: An :py:class:`~PIL.Image.Image` object.
2223 """
2224 from . import ImagePalette
2226 if self.mode not in ("L", "P"):
2227 msg = "illegal image mode"
2228 raise ValueError(msg)
2230 bands = 3
2231 palette_mode = "RGB"
2232 if source_palette is None:
2233 if self.mode == "P":
2234 self.load()
2235 palette_mode = self.im.getpalettemode()
2236 if palette_mode == "RGBA":
2237 bands = 4
2238 source_palette = self.im.getpalette(palette_mode, palette_mode)
2239 else: # L-mode
2240 source_palette = bytearray(i // 3 for i in range(768))
2241 elif len(source_palette) > 768:
2242 bands = 4
2243 palette_mode = "RGBA"
2245 palette_bytes = b""
2246 new_positions = [0] * 256
2248 # pick only the used colors from the palette
2249 for i, oldPosition in enumerate(dest_map):
2250 palette_bytes += source_palette[
2251 oldPosition * bands : oldPosition * bands + bands
2252 ]
2253 new_positions[oldPosition] = i
2255 # replace the palette color id of all pixel with the new id
2257 # Palette images are [0..255], mapped through a 1 or 3
2258 # byte/color map. We need to remap the whole image
2259 # from palette 1 to palette 2. New_positions is
2260 # an array of indexes into palette 1. Palette 2 is
2261 # palette 1 with any holes removed.
2263 # We're going to leverage the convert mechanism to use the
2264 # C code to remap the image from palette 1 to palette 2,
2265 # by forcing the source image into 'L' mode and adding a
2266 # mapping 'L' mode palette, then converting back to 'L'
2267 # sans palette thus converting the image bytes, then
2268 # assigning the optimized RGB palette.
2270 # perf reference, 9500x4000 gif, w/~135 colors
2271 # 14 sec prepatch, 1 sec postpatch with optimization forced.
2273 mapping_palette = bytearray(new_positions)
2275 m_im = self.copy()
2276 m_im._mode = "P"
2278 m_im.palette = ImagePalette.ImagePalette(
2279 palette_mode, palette=mapping_palette * bands
2280 )
2281 # possibly set palette dirty, then
2282 # m_im.putpalette(mapping_palette, 'L') # converts to 'P'
2283 # or just force it.
2284 # UNDONE -- this is part of the general issue with palettes
2285 m_im.im.putpalette(palette_mode, palette_mode + ";L", m_im.palette.tobytes())
2287 m_im = m_im.convert("L")
2289 m_im.putpalette(palette_bytes, palette_mode)
2290 m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes)
2292 if "transparency" in self.info:
2293 try:
2294 m_im.info["transparency"] = dest_map.index(self.info["transparency"])
2295 except ValueError:
2296 if "transparency" in m_im.info:
2297 del m_im.info["transparency"]
2299 return m_im
2301 def _get_safe_box(
2302 self,
2303 size: tuple[int, int],
2304 resample: Resampling,
2305 box: tuple[float, float, float, float],
2306 ) -> tuple[int, int, int, int]:
2307 """Expands the box so it includes adjacent pixels
2308 that may be used by resampling with the given resampling filter.
2309 """
2310 filter_support = _filters_support[resample] - 0.5
2311 scale_x = (box[2] - box[0]) / size[0]
2312 scale_y = (box[3] - box[1]) / size[1]
2313 support_x = filter_support * scale_x
2314 support_y = filter_support * scale_y
2316 return (
2317 max(0, int(box[0] - support_x)),
2318 max(0, int(box[1] - support_y)),
2319 min(self.size[0], math.ceil(box[2] + support_x)),
2320 min(self.size[1], math.ceil(box[3] + support_y)),
2321 )
2323 def resize(
2324 self,
2325 size: tuple[int, int] | list[int] | NumpyArray,
2326 resample: int | None = None,
2327 box: tuple[float, float, float, float] | None = None,
2328 reducing_gap: float | None = None,
2329 ) -> Image:
2330 """
2331 Returns a resized copy of this image.
2333 :param size: The requested size in pixels, as a tuple or array:
2334 (width, height).
2335 :param resample: An optional resampling filter. This can be
2336 one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`,
2337 :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`,
2338 :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`.
2339 If the image has mode "1" or "P", it is always set to
2340 :py:data:`Resampling.NEAREST`. Otherwise, the default filter is
2341 :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`.
2342 :param box: An optional 4-tuple of floats providing
2343 the source image region to be scaled.
2344 The values must be within (0, 0, width, height) rectangle.
2345 If omitted or None, the entire source is used.
2346 :param reducing_gap: Apply optimization by resizing the image
2347 in two steps. First, reducing the image by integer times
2348 using :py:meth:`~PIL.Image.Image.reduce`.
2349 Second, resizing using regular resampling. The last step
2350 changes size no less than by ``reducing_gap`` times.
2351 ``reducing_gap`` may be None (no first step is performed)
2352 or should be greater than 1.0. The bigger ``reducing_gap``,
2353 the closer the result to the fair resampling.
2354 The smaller ``reducing_gap``, the faster resizing.
2355 With ``reducing_gap`` greater or equal to 3.0, the result is
2356 indistinguishable from fair resampling in most cases.
2357 The default value is None (no optimization).
2358 :returns: An :py:class:`~PIL.Image.Image` object.
2359 """
2361 if resample is None:
2362 resample = Resampling.BICUBIC
2363 elif resample not in (
2364 Resampling.NEAREST,
2365 Resampling.BILINEAR,
2366 Resampling.BICUBIC,
2367 Resampling.LANCZOS,
2368 Resampling.BOX,
2369 Resampling.HAMMING,
2370 ):
2371 msg = f"Unknown resampling filter ({resample})."
2373 filters = [
2374 f"{filter[1]} ({filter[0]})"
2375 for filter in (
2376 (Resampling.NEAREST, "Image.Resampling.NEAREST"),
2377 (Resampling.LANCZOS, "Image.Resampling.LANCZOS"),
2378 (Resampling.BILINEAR, "Image.Resampling.BILINEAR"),
2379 (Resampling.BICUBIC, "Image.Resampling.BICUBIC"),
2380 (Resampling.BOX, "Image.Resampling.BOX"),
2381 (Resampling.HAMMING, "Image.Resampling.HAMMING"),
2382 )
2383 ]
2384 msg += f" Use {', '.join(filters[:-1])} or {filters[-1]}"
2385 raise ValueError(msg)
2387 if reducing_gap is not None and reducing_gap < 1.0:
2388 msg = "reducing_gap must be 1.0 or greater"
2389 raise ValueError(msg)
2391 if box is None:
2392 box = (0, 0) + self.size
2394 size = tuple(size)
2395 if self.size == size and box == (0, 0) + self.size:
2396 return self.copy()
2398 if self.mode in ("1", "P"):
2399 resample = Resampling.NEAREST
2401 if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST:
2402 im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
2403 im = im.resize(size, resample, box)
2404 return im.convert(self.mode)
2406 self.load()
2408 if reducing_gap is not None and resample != Resampling.NEAREST:
2409 factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1
2410 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1
2411 if factor_x > 1 or factor_y > 1:
2412 reduce_box = self._get_safe_box(size, cast(Resampling, resample), box)
2413 factor = (factor_x, factor_y)
2414 self = (
2415 self.reduce(factor, box=reduce_box)
2416 if callable(self.reduce)
2417 else Image.reduce(self, factor, box=reduce_box)
2418 )
2419 box = (
2420 (box[0] - reduce_box[0]) / factor_x,
2421 (box[1] - reduce_box[1]) / factor_y,
2422 (box[2] - reduce_box[0]) / factor_x,
2423 (box[3] - reduce_box[1]) / factor_y,
2424 )
2426 return self._new(self.im.resize(size, resample, box))
2428 def reduce(
2429 self,
2430 factor: int | tuple[int, int],
2431 box: tuple[int, int, int, int] | None = None,
2432 ) -> Image:
2433 """
2434 Returns a copy of the image reduced ``factor`` times.
2435 If the size of the image is not dividable by ``factor``,
2436 the resulting size will be rounded up.
2438 :param factor: A greater than 0 integer or tuple of two integers
2439 for width and height separately.
2440 :param box: An optional 4-tuple of ints providing
2441 the source image region to be reduced.
2442 The values must be within ``(0, 0, width, height)`` rectangle.
2443 If omitted or ``None``, the entire source is used.
2444 """
2445 if not isinstance(factor, (list, tuple)):
2446 factor = (factor, factor)
2448 if box is None:
2449 box = (0, 0) + self.size
2451 if factor == (1, 1) and box == (0, 0) + self.size:
2452 return self.copy()
2454 if self.mode in ["LA", "RGBA"]:
2455 im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
2456 im = im.reduce(factor, box)
2457 return im.convert(self.mode)
2459 self.load()
2461 return self._new(self.im.reduce(factor, box))
2463 def rotate(
2464 self,
2465 angle: float,
2466 resample: Resampling = Resampling.NEAREST,
2467 expand: int | bool = False,
2468 center: tuple[float, float] | None = None,
2469 translate: tuple[int, int] | None = None,
2470 fillcolor: float | tuple[float, ...] | str | None = None,
2471 ) -> Image:
2472 """
2473 Returns a rotated copy of this image. This method returns a
2474 copy of this image, rotated the given number of degrees counter
2475 clockwise around its centre.
2477 :param angle: In degrees counter clockwise.
2478 :param resample: An optional resampling filter. This can be
2479 one of :py:data:`Resampling.NEAREST` (use nearest neighbour),
2480 :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2
2481 environment), or :py:data:`Resampling.BICUBIC` (cubic spline
2482 interpolation in a 4x4 environment). If omitted, or if the image has
2483 mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`.
2484 See :ref:`concept-filters`.
2485 :param expand: Optional expansion flag. If true, expands the output
2486 image to make it large enough to hold the entire rotated image.
2487 If false or omitted, make the output image the same size as the
2488 input image. Note that the expand flag assumes rotation around
2489 the center and no translation.
2490 :param center: Optional center of rotation (a 2-tuple). Origin is
2491 the upper left corner. Default is the center of the image.
2492 :param translate: An optional post-rotate translation (a 2-tuple).
2493 :param fillcolor: An optional color for area outside the rotated image.
2494 :returns: An :py:class:`~PIL.Image.Image` object.
2495 """
2497 angle = angle % 360.0
2499 # Fast paths regardless of filter, as long as we're not
2500 # translating or changing the center.
2501 if not (center or translate):
2502 if angle == 0:
2503 return self.copy()
2504 if angle == 180:
2505 return self.transpose(Transpose.ROTATE_180)
2506 if angle in (90, 270) and (expand or self.width == self.height):
2507 return self.transpose(
2508 Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270
2509 )
2511 # Calculate the affine matrix. Note that this is the reverse
2512 # transformation (from destination image to source) because we
2513 # want to interpolate the (discrete) destination pixel from
2514 # the local area around the (floating) source pixel.
2516 # The matrix we actually want (note that it operates from the right):
2517 # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx)
2518 # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy)
2519 # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1)
2521 # The reverse matrix is thus:
2522 # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx)
2523 # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty)
2524 # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1)
2526 # In any case, the final translation may be updated at the end to
2527 # compensate for the expand flag.
2529 w, h = self.size
2531 if translate is None:
2532 post_trans = (0, 0)
2533 else:
2534 post_trans = translate
2535 if center is None:
2536 center = (w / 2, h / 2)
2538 angle = -math.radians(angle)
2539 matrix = [
2540 round(math.cos(angle), 15),
2541 round(math.sin(angle), 15),
2542 0.0,
2543 round(-math.sin(angle), 15),
2544 round(math.cos(angle), 15),
2545 0.0,
2546 ]
2548 def transform(x: float, y: float, matrix: list[float]) -> tuple[float, float]:
2549 a, b, c, d, e, f = matrix
2550 return a * x + b * y + c, d * x + e * y + f
2552 matrix[2], matrix[5] = transform(
2553 -center[0] - post_trans[0], -center[1] - post_trans[1], matrix
2554 )
2555 matrix[2] += center[0]
2556 matrix[5] += center[1]
2558 if expand:
2559 # calculate output size
2560 xx = []
2561 yy = []
2562 for x, y in ((0, 0), (w, 0), (w, h), (0, h)):
2563 transformed_x, transformed_y = transform(x, y, matrix)
2564 xx.append(transformed_x)
2565 yy.append(transformed_y)
2566 nw = math.ceil(max(xx)) - math.floor(min(xx))
2567 nh = math.ceil(max(yy)) - math.floor(min(yy))
2569 # We multiply a translation matrix from the right. Because of its
2570 # special form, this is the same as taking the image of the
2571 # translation vector as new translation vector.
2572 matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix)
2573 w, h = nw, nh
2575 return self.transform(
2576 (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor
2577 )
2579 def save(
2580 self, fp: StrOrBytesPath | IO[bytes], format: str | None = None, **params: Any
2581 ) -> None:
2582 """
2583 Saves this image under the given filename. If no format is
2584 specified, the format to use is determined from the filename
2585 extension, if possible.
2587 Keyword options can be used to provide additional instructions
2588 to the writer. If a writer doesn't recognise an option, it is
2589 silently ignored. The available options are described in the
2590 :doc:`image format documentation
2591 <../handbook/image-file-formats>` for each writer.
2593 You can use a file object instead of a filename. In this case,
2594 you must always specify the format. The file object must
2595 implement the ``seek``, ``tell``, and ``write``
2596 methods, and be opened in binary mode.
2598 :param fp: A filename (string), os.PathLike object or file object.
2599 :param format: Optional format override. If omitted, the
2600 format to use is determined from the filename extension.
2601 If a file object was used instead of a filename, this
2602 parameter should always be used.
2603 :param params: Extra parameters to the image writer. These can also be
2604 set on the image itself through ``encoderinfo``. This is useful when
2605 saving multiple images::
2607 # Saving XMP data to a single image
2608 from PIL import Image
2609 red = Image.new("RGB", (1, 1), "#f00")
2610 red.save("out.mpo", xmp=b"test")
2612 # Saving XMP data to the second frame of an image
2613 from PIL import Image
2614 black = Image.new("RGB", (1, 1))
2615 red = Image.new("RGB", (1, 1), "#f00")
2616 red.encoderinfo = {"xmp": b"test"}
2617 black.save("out.mpo", save_all=True, append_images=[red])
2618 :returns: None
2619 :exception ValueError: If the output format could not be determined
2620 from the file name. Use the format option to solve this.
2621 :exception OSError: If the file could not be written. The file
2622 may have been created, and may contain partial data.
2623 """
2625 filename: str | bytes = ""
2626 open_fp = False
2627 if is_path(fp):
2628 filename = os.fspath(fp)
2629 open_fp = True
2630 elif fp == sys.stdout:
2631 try:
2632 fp = sys.stdout.buffer
2633 except AttributeError:
2634 pass
2635 if not filename and hasattr(fp, "name") and is_path(fp.name):
2636 # only set the name for metadata purposes
2637 filename = os.fspath(fp.name)
2639 if format:
2640 preinit()
2641 else:
2642 filename_ext = os.path.splitext(filename)[1].lower()
2643 ext = (
2644 filename_ext.decode()
2645 if isinstance(filename_ext, bytes)
2646 else filename_ext
2647 )
2649 # Try importing only the plugin for this extension first
2650 if not _import_plugin_for_extension(ext):
2651 preinit()
2653 if ext not in EXTENSION:
2654 init()
2655 try:
2656 format = EXTENSION[ext]
2657 except KeyError as e:
2658 msg = f"unknown file extension: {ext}"
2659 raise ValueError(msg) from e
2661 from . import ImageFile
2663 # may mutate self!
2664 if isinstance(self, ImageFile.ImageFile) and os.path.abspath(
2665 filename
2666 ) == os.path.abspath(self.filename):
2667 self._ensure_mutable()
2668 else:
2669 self.load()
2671 save_all = params.pop("save_all", None)
2672 self._default_encoderinfo = params
2673 encoderinfo = getattr(self, "encoderinfo", {})
2674 self._attach_default_encoderinfo(self)
2675 self.encoderconfig: tuple[Any, ...] = ()
2677 if format.upper() not in SAVE:
2678 init()
2679 if save_all or (
2680 save_all is None
2681 and params.get("append_images")
2682 and format.upper() in SAVE_ALL
2683 ):
2684 save_handler = SAVE_ALL[format.upper()]
2685 else:
2686 save_handler = SAVE[format.upper()]
2688 created = False
2689 if open_fp:
2690 created = not os.path.exists(filename)
2691 if params.get("append", False):
2692 # Open also for reading ("+"), because TIFF save_all
2693 # writer needs to go back and edit the written data.
2694 fp = builtins.open(filename, "r+b")
2695 else:
2696 fp = builtins.open(filename, "w+b")
2697 else:
2698 fp = cast(IO[bytes], fp)
2700 try:
2701 save_handler(self, fp, filename)
2702 except Exception:
2703 if open_fp:
2704 fp.close()
2705 if created:
2706 try:
2707 os.remove(filename)
2708 except PermissionError:
2709 pass
2710 raise
2711 finally:
2712 self.encoderinfo = encoderinfo
2713 if open_fp:
2714 fp.close()
2716 def _attach_default_encoderinfo(self, im: Image) -> dict[str, Any]:
2717 encoderinfo = getattr(self, "encoderinfo", {})
2718 self.encoderinfo = {**im._default_encoderinfo, **encoderinfo}
2719 return encoderinfo
2721 def seek(self, frame: int) -> None:
2722 """
2723 Seeks to the given frame in this sequence file. If you seek
2724 beyond the end of the sequence, the method raises an
2725 ``EOFError`` exception. When a sequence file is opened, the
2726 library automatically seeks to frame 0.
2728 See :py:meth:`~PIL.Image.Image.tell`.
2730 If defined, :attr:`~PIL.Image.Image.n_frames` refers to the
2731 number of available frames.
2733 :param frame: Frame number, starting at 0.
2734 :exception EOFError: If the call attempts to seek beyond the end
2735 of the sequence.
2736 """
2738 # overridden by file handlers
2739 if frame != 0:
2740 msg = "no more images in file"
2741 raise EOFError(msg)
2743 def show(self, title: str | None = None) -> None:
2744 """
2745 Displays this image. This method is mainly intended for debugging purposes.
2747 This method calls :py:func:`PIL.ImageShow.show` internally. You can use
2748 :py:func:`PIL.ImageShow.register` to override its default behaviour.
2750 The image is first saved to a temporary file. By default, it will be in
2751 PNG format.
2753 On Unix, the image is then opened using the **xdg-open**, **display**,
2754 **gm**, **eog** or **xv** utility, depending on which one can be found.
2756 On macOS, the image is opened with the native Preview application.
2758 On Windows, the image is opened with the standard PNG display utility.
2760 :param title: Optional title to use for the image window, where possible.
2761 """
2763 from . import ImageShow
2765 ImageShow.show(self, title)
2767 def split(self) -> tuple[Image, ...]:
2768 """
2769 Split this image into individual bands. This method returns a
2770 tuple of individual image bands from an image. For example,
2771 splitting an "RGB" image creates three new images each
2772 containing a copy of one of the original bands (red, green,
2773 blue).
2775 If you need only one band, :py:meth:`~PIL.Image.Image.getchannel`
2776 method can be more convenient and faster.
2778 :returns: A tuple containing bands.
2779 """
2781 self.load()
2782 if self.im.bands == 1:
2783 return (self.copy(),)
2784 return tuple(map(self._new, self.im.split()))
2786 def getchannel(self, channel: int | str) -> Image:
2787 """
2788 Returns an image containing a single channel of the source image.
2790 :param channel: What channel to return. Could be index
2791 (0 for "R" channel of "RGB") or channel name
2792 ("A" for alpha channel of "RGBA").
2793 :returns: An image in "L" mode.
2795 .. versionadded:: 4.3.0
2796 """
2797 self.load()
2799 if isinstance(channel, str):
2800 try:
2801 channel = self.getbands().index(channel)
2802 except ValueError as e:
2803 msg = f'The image has no channel "{channel}"'
2804 raise ValueError(msg) from e
2806 return self._new(self.im.getband(channel))
2808 def tell(self) -> int:
2809 """
2810 Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.
2812 If defined, :attr:`~PIL.Image.Image.n_frames` refers to the
2813 number of available frames.
2815 :returns: Frame number, starting with 0.
2816 """
2817 return 0
2819 def thumbnail(
2820 self,
2821 size: tuple[float, float],
2822 resample: Resampling = Resampling.BICUBIC,
2823 reducing_gap: float | None = 2.0,
2824 ) -> None:
2825 """
2826 Make this image into a thumbnail. This method modifies the
2827 image to contain a thumbnail version of itself, no larger than
2828 the given size. This method calculates an appropriate thumbnail
2829 size to preserve the aspect of the image, calls the
2830 :py:meth:`~PIL.Image.Image.draft` method to configure the file reader
2831 (where applicable), and finally resizes the image.
2833 Note that this function modifies the :py:class:`~PIL.Image.Image`
2834 object in place. If you need to use the full resolution image as well,
2835 apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original
2836 image.
2838 :param size: The requested size in pixels, as a 2-tuple:
2839 (width, height).
2840 :param resample: Optional resampling filter. This can be one
2841 of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`,
2842 :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`,
2843 :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`.
2844 If omitted, it defaults to :py:data:`Resampling.BICUBIC`.
2845 (was :py:data:`Resampling.NEAREST` prior to version 2.5.0).
2846 See: :ref:`concept-filters`.
2847 :param reducing_gap: Apply optimization by resizing the image
2848 in two steps. First, reducing the image by integer times
2849 using :py:meth:`~PIL.Image.Image.reduce` or
2850 :py:meth:`~PIL.Image.Image.draft` for JPEG images.
2851 Second, resizing using regular resampling. The last step
2852 changes size no less than by ``reducing_gap`` times.
2853 ``reducing_gap`` may be None (no first step is performed)
2854 or should be greater than 1.0. The bigger ``reducing_gap``,
2855 the closer the result to the fair resampling.
2856 The smaller ``reducing_gap``, the faster resizing.
2857 With ``reducing_gap`` greater or equal to 3.0, the result is
2858 indistinguishable from fair resampling in most cases.
2859 The default value is 2.0 (very close to fair resampling
2860 while still being faster in many cases).
2861 :returns: None
2862 """
2864 provided_size = tuple(map(math.floor, size))
2866 def preserve_aspect_ratio() -> tuple[int, int] | None:
2867 def round_aspect(number: float, key: Callable[[int], float]) -> int:
2868 return max(min(math.floor(number), math.ceil(number), key=key), 1)
2870 x, y = provided_size
2871 if x >= self.width and y >= self.height:
2872 return None
2874 aspect = self.width / self.height
2875 if x / y >= aspect:
2876 x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y))
2877 else:
2878 y = round_aspect(
2879 x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n)
2880 )
2881 return x, y
2883 preserved_size = preserve_aspect_ratio()
2884 if preserved_size is None:
2885 return
2886 final_size = preserved_size
2888 box = None
2889 if reducing_gap is not None:
2890 res = self.draft(
2891 None, (int(size[0] * reducing_gap), int(size[1] * reducing_gap))
2892 )
2893 if res is not None:
2894 box = res[1]
2896 if self.size != final_size:
2897 im = self.resize(final_size, resample, box=box, reducing_gap=reducing_gap)
2899 self.im = im.im
2900 self._size = final_size
2901 self._mode = self.im.mode
2903 self.readonly = 0
2905 # FIXME: the different transform methods need further explanation
2906 # instead of bloating the method docs, add a separate chapter.
2907 def transform(
2908 self,
2909 size: tuple[int, int],
2910 method: Transform | ImageTransformHandler | SupportsGetData,
2911 data: Sequence[Any] | None = None,
2912 resample: int = Resampling.NEAREST,
2913 fill: int = 1,
2914 fillcolor: float | tuple[float, ...] | str | None = None,
2915 ) -> Image:
2916 """
2917 Transforms this image. This method creates a new image with the
2918 given size, and the same mode as the original, and copies data
2919 to the new image using the given transform.
2921 :param size: The output size in pixels, as a 2-tuple:
2922 (width, height).
2923 :param method: The transformation method. This is one of
2924 :py:data:`Transform.EXTENT` (cut out a rectangular subregion),
2925 :py:data:`Transform.AFFINE` (affine transform),
2926 :py:data:`Transform.PERSPECTIVE` (perspective transform),
2927 :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or
2928 :py:data:`Transform.MESH` (map a number of source quadrilaterals
2929 in one operation).
2931 It may also be an :py:class:`~PIL.Image.ImageTransformHandler`
2932 object::
2934 class Example(Image.ImageTransformHandler):
2935 def transform(self, size, data, resample, fill=1):
2936 # Return result
2938 Implementations of :py:class:`~PIL.Image.ImageTransformHandler`
2939 for some of the :py:class:`Transform` methods are provided
2940 in :py:mod:`~PIL.ImageTransform`.
2942 It may also be an object with a ``method.getdata`` method
2943 that returns a tuple supplying new ``method`` and ``data`` values::
2945 class Example:
2946 def getdata(self):
2947 method = Image.Transform.EXTENT
2948 data = (0, 0, 100, 100)
2949 return method, data
2950 :param data: Extra data to the transformation method.
2951 :param resample: Optional resampling filter. It can be one of
2952 :py:data:`Resampling.NEAREST` (use nearest neighbour),
2953 :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2
2954 environment), or :py:data:`Resampling.BICUBIC` (cubic spline
2955 interpolation in a 4x4 environment). If omitted, or if the image
2956 has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`.
2957 See: :ref:`concept-filters`.
2958 :param fill: If ``method`` is an
2959 :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of
2960 the arguments passed to it. Otherwise, it is unused.
2961 :param fillcolor: Optional fill color for the area outside the
2962 transform in the output image.
2963 :returns: An :py:class:`~PIL.Image.Image` object.
2964 """
2966 if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST:
2967 return (
2968 self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
2969 .transform(size, method, data, resample, fill, fillcolor)
2970 .convert(self.mode)
2971 )
2973 if isinstance(method, ImageTransformHandler):
2974 return method.transform(size, self, resample=resample, fill=fill)
2976 if hasattr(method, "getdata"):
2977 # compatibility w. old-style transform objects
2978 method, data = method.getdata()
2980 if data is None:
2981 msg = "missing method data"
2982 raise ValueError(msg)
2984 im = new(self.mode, size, fillcolor)
2985 if self.mode == "P" and self.palette:
2986 im.palette = self.palette.copy()
2987 im.info = self.info.copy()
2988 if method == Transform.MESH:
2989 # list of quads
2990 for box, quad in data:
2991 im.__transformer(
2992 box, self, Transform.QUAD, quad, resample, fillcolor is None
2993 )
2994 else:
2995 im.__transformer(
2996 (0, 0) + size, self, method, data, resample, fillcolor is None
2997 )
2999 return im
3001 def __transformer(
3002 self,
3003 box: tuple[int, int, int, int],
3004 image: Image,
3005 method: Transform,
3006 data: Sequence[float],
3007 resample: int = Resampling.NEAREST,
3008 fill: bool = True,
3009 ) -> None:
3010 w = box[2] - box[0]
3011 h = box[3] - box[1]
3013 if method == Transform.AFFINE:
3014 data = data[:6]
3016 elif method == Transform.EXTENT:
3017 # convert extent to an affine transform
3018 x0, y0, x1, y1 = data
3019 xs = (x1 - x0) / w
3020 ys = (y1 - y0) / h
3021 method = Transform.AFFINE
3022 data = (xs, 0, x0, 0, ys, y0)
3024 elif method == Transform.PERSPECTIVE:
3025 data = data[:8]
3027 elif method == Transform.QUAD:
3028 # quadrilateral warp. data specifies the four corners
3029 # given as NW, SW, SE, and NE.
3030 nw = data[:2]
3031 sw = data[2:4]
3032 se = data[4:6]
3033 ne = data[6:8]
3034 x0, y0 = nw
3035 As = 1.0 / w
3036 At = 1.0 / h
3037 data = (
3038 x0,
3039 (ne[0] - x0) * As,
3040 (sw[0] - x0) * At,
3041 (se[0] - sw[0] - ne[0] + x0) * As * At,
3042 y0,
3043 (ne[1] - y0) * As,
3044 (sw[1] - y0) * At,
3045 (se[1] - sw[1] - ne[1] + y0) * As * At,
3046 )
3048 else:
3049 msg = "unknown transformation method"
3050 raise ValueError(msg)
3052 if resample not in (
3053 Resampling.NEAREST,
3054 Resampling.BILINEAR,
3055 Resampling.BICUBIC,
3056 ):
3057 if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS):
3058 unusable: dict[int, str] = {
3059 Resampling.BOX: "Image.Resampling.BOX",
3060 Resampling.HAMMING: "Image.Resampling.HAMMING",
3061 Resampling.LANCZOS: "Image.Resampling.LANCZOS",
3062 }
3063 msg = unusable[resample] + f" ({resample}) cannot be used."
3064 else:
3065 msg = f"Unknown resampling filter ({resample})."
3067 filters = [
3068 f"{filter[1]} ({filter[0]})"
3069 for filter in (
3070 (Resampling.NEAREST, "Image.Resampling.NEAREST"),
3071 (Resampling.BILINEAR, "Image.Resampling.BILINEAR"),
3072 (Resampling.BICUBIC, "Image.Resampling.BICUBIC"),
3073 )
3074 ]
3075 msg += f" Use {', '.join(filters[:-1])} or {filters[-1]}"
3076 raise ValueError(msg)
3078 image.load()
3080 self.load()
3082 if image.mode in ("1", "P"):
3083 resample = Resampling.NEAREST
3085 self.im.transform(box, image.im, method, data, resample, fill)
3087 def transpose(self, method: Transpose) -> Image:
3088 """
3089 Transpose image (flip or rotate in 90 degree steps)
3091 :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`,
3092 :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`,
3093 :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`,
3094 :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`.
3095 :returns: Returns a flipped or rotated copy of this image.
3096 """
3098 self.load()
3099 return self._new(self.im.transpose(method))
3101 def effect_spread(self, distance: int) -> Image:
3102 """
3103 Randomly spread pixels in an image.
3105 :param distance: Distance to spread pixels.
3106 """
3107 self.load()
3108 return self._new(self.im.effect_spread(distance))
3110 def toqimage(self) -> ImageQt.ImageQt:
3111 """Returns a QImage copy of this image"""
3112 from . import ImageQt
3114 if not ImageQt.qt_is_installed:
3115 msg = "Qt bindings are not installed"
3116 raise ImportError(msg)
3117 return ImageQt.toqimage(self)
3119 def toqpixmap(self) -> ImageQt.QPixmap:
3120 """Returns a QPixmap copy of this image"""
3121 from . import ImageQt
3123 if not ImageQt.qt_is_installed:
3124 msg = "Qt bindings are not installed"
3125 raise ImportError(msg)
3126 return ImageQt.toqpixmap(self)
3129# --------------------------------------------------------------------
3130# Abstract handlers.
3133class ImagePointHandler(abc.ABC):
3134 """
3135 Used as a mixin by point transforms
3136 (for use with :py:meth:`~PIL.Image.Image.point`)
3137 """
3139 @abc.abstractmethod
3140 def point(self, im: Image) -> Image:
3141 pass
3144class ImageTransformHandler(abc.ABC):
3145 """
3146 Used as a mixin by geometry transforms
3147 (for use with :py:meth:`~PIL.Image.Image.transform`)
3148 """
3150 @abc.abstractmethod
3151 def transform(
3152 self,
3153 size: tuple[int, int],
3154 image: Image,
3155 **options: Any,
3156 ) -> Image:
3157 pass
3160# --------------------------------------------------------------------
3161# Factories
3164def _check_size(size: Any) -> None:
3165 """
3166 Common check to enforce type and sanity check on size tuples
3168 :param size: Should be a 2 tuple of (width, height)
3169 :returns: None, or raises a ValueError
3170 """
3172 if not isinstance(size, (list, tuple)):
3173 msg = "Size must be a list or tuple"
3174 raise ValueError(msg)
3175 if len(size) != 2:
3176 msg = "Size must be a sequence of length 2"
3177 raise ValueError(msg)
3178 if size[0] < 0 or size[1] < 0:
3179 msg = "Width and height must be >= 0"
3180 raise ValueError(msg)
3183def new(
3184 mode: str,
3185 size: tuple[int, int] | list[int],
3186 color: float | tuple[float, ...] | str | None = 0,
3187) -> Image:
3188 """
3189 Creates a new image with the given mode and size.
3191 :param mode: The mode to use for the new image. See:
3192 :ref:`concept-modes`.
3193 :param size: A 2-tuple, containing (width, height) in pixels.
3194 :param color: What color to use for the image. Default is black. If given,
3195 this should be a single integer or floating point value for single-band
3196 modes, and a tuple for multi-band modes (one value per band). When
3197 creating RGB or HSV images, you can also use color strings as supported
3198 by the ImageColor module. See :ref:`colors` for more information. If the
3199 color is None, the image is not initialised.
3200 :returns: An :py:class:`~PIL.Image.Image` object.
3201 """
3203 _check_size(size)
3205 if color is None:
3206 # don't initialize
3207 return Image()._new(core.new(mode, size))
3209 if isinstance(color, str):
3210 # css3-style specifier
3212 from . import ImageColor
3214 color = ImageColor.getcolor(color, mode)
3216 im = Image()
3217 if (
3218 mode == "P"
3219 and isinstance(color, (list, tuple))
3220 and all(isinstance(i, int) for i in color)
3221 ):
3222 color_ints: tuple[int, ...] = cast(tuple[int, ...], tuple(color))
3223 if len(color_ints) == 3 or len(color_ints) == 4:
3224 # RGB or RGBA value for a P image
3225 from . import ImagePalette
3227 im.palette = ImagePalette.ImagePalette()
3228 color = im.palette.getcolor(color_ints)
3229 return im._new(core.fill(mode, size, color))
3232def frombytes(
3233 mode: str,
3234 size: tuple[int, int],
3235 data: bytes | bytearray | SupportsArrayInterface,
3236 decoder_name: str = "raw",
3237 *args: Any,
3238) -> Image:
3239 """
3240 Creates a copy of an image memory from pixel data in a buffer.
3242 In its simplest form, this function takes three arguments
3243 (mode, size, and unpacked pixel data).
3245 You can also use any pixel decoder supported by PIL. For more
3246 information on available decoders, see the section
3247 :ref:`Writing Your Own File Codec <file-codecs>`.
3249 Note that this function decodes pixel data only, not entire images.
3250 If you have an entire image in a string, wrap it in a
3251 :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load
3252 it.
3254 :param mode: The image mode. See: :ref:`concept-modes`.
3255 :param size: The image size.
3256 :param data: A byte buffer containing raw data for the given mode.
3257 :param decoder_name: What decoder to use.
3258 :param args: Additional parameters for the given decoder.
3259 :returns: An :py:class:`~PIL.Image.Image` object.
3260 """
3262 _check_size(size)
3264 im = new(mode, size)
3265 if im.width != 0 and im.height != 0:
3266 decoder_args: Any = args
3267 if len(decoder_args) == 1 and isinstance(decoder_args[0], tuple):
3268 # may pass tuple instead of argument list
3269 decoder_args = decoder_args[0]
3271 if decoder_name == "raw" and decoder_args == ():
3272 decoder_args = mode
3274 im.frombytes(data, decoder_name, decoder_args)
3275 return im
3278def frombuffer(
3279 mode: str,
3280 size: tuple[int, int],
3281 data: bytes | SupportsArrayInterface,
3282 decoder_name: str = "raw",
3283 *args: Any,
3284) -> Image:
3285 """
3286 Creates an image memory referencing pixel data in a byte buffer.
3288 This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data
3289 in the byte buffer, where possible. This means that changes to the
3290 original buffer object are reflected in this image). Not all modes can
3291 share memory; supported modes include "L", "RGBX", "RGBA", and "CMYK".
3293 Note that this function decodes pixel data only, not entire images.
3294 If you have an entire image file in a string, wrap it in a
3295 :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load it.
3297 The default parameters used for the "raw" decoder differs from that used for
3298 :py:func:`~PIL.Image.frombytes`. This is a bug, and will probably be fixed in a
3299 future release. The current release issues a warning if you do this; to disable
3300 the warning, you should provide the full set of parameters. See below for details.
3302 :param mode: The image mode. See: :ref:`concept-modes`.
3303 :param size: The image size.
3304 :param data: A bytes or other buffer object containing raw
3305 data for the given mode.
3306 :param decoder_name: What decoder to use.
3307 :param args: Additional parameters for the given decoder. For the
3308 default encoder ("raw"), it's recommended that you provide the
3309 full set of parameters::
3311 frombuffer(mode, size, data, "raw", mode, 0, 1)
3313 :returns: An :py:class:`~PIL.Image.Image` object.
3315 .. versionadded:: 1.1.4
3316 """
3318 _check_size(size)
3320 # may pass tuple instead of argument list
3321 if len(args) == 1 and isinstance(args[0], tuple):
3322 args = args[0]
3324 if decoder_name == "raw":
3325 if args == ():
3326 args = mode, 0, 1
3327 if args[0] in _MAPMODES:
3328 im = new(mode, (0, 0))
3329 im = im._new(core.map_buffer(data, size, decoder_name, 0, args))
3330 if mode == "P":
3331 from . import ImagePalette
3333 im.palette = ImagePalette.ImagePalette("RGB", im.im.getpalette("RGB"))
3334 im.readonly = 1
3335 return im
3337 return frombytes(mode, size, data, decoder_name, args)
3340class SupportsArrayInterface(Protocol):
3341 """
3342 An object that has an ``__array_interface__`` dictionary.
3343 """
3345 @property
3346 def __array_interface__(self) -> dict[str, Any]:
3347 raise NotImplementedError()
3350class SupportsArrowArrayInterface(Protocol):
3351 """
3352 An object that has an ``__arrow_c_array__`` method corresponding to the arrow c
3353 data interface.
3354 """
3356 def __arrow_c_array__(
3357 self, requested_schema: "PyCapsule" = None # type: ignore[name-defined] # noqa: F821, UP037
3358 ) -> tuple["PyCapsule", "PyCapsule"]: # type: ignore[name-defined] # noqa: F821, UP037
3359 raise NotImplementedError()
3362def fromarray(obj: SupportsArrayInterface, mode: str | None = None) -> Image:
3363 """
3364 Creates an image memory from an object exporting the array interface
3365 (using the buffer protocol)::
3367 from PIL import Image
3368 import numpy as np
3369 a = np.zeros((5, 5))
3370 im = Image.fromarray(a)
3372 If ``obj`` is not contiguous, then the ``tobytes`` method is called
3373 and :py:func:`~PIL.Image.frombuffer` is used.
3375 In the case of NumPy, be aware that Pillow modes do not always correspond
3376 to NumPy dtypes. Pillow modes only offer 1-bit pixels, 8-bit pixels,
3377 32-bit signed integer pixels, and 32-bit floating point pixels.
3379 Pillow images can also be converted to arrays::
3381 from PIL import Image
3382 import numpy as np
3383 im = Image.open("hopper.jpg")
3384 a = np.asarray(im)
3386 When converting Pillow images to arrays however, only pixel values are
3387 transferred. This means that P and PA mode images will lose their palette.
3389 :param obj: Object with array interface
3390 :param mode: Optional mode to use when reading ``obj``. Since pixel values do not
3391 contain information about palettes or color spaces, this can be used to place
3392 grayscale L mode data within a P mode image, or read RGB data as YCbCr for
3393 example.
3395 See: :ref:`concept-modes` for general information about modes.
3396 :returns: An image object.
3398 .. versionadded:: 1.1.6
3399 """
3400 arr = obj.__array_interface__
3401 shape = arr["shape"]
3402 ndim = len(shape)
3403 strides = arr.get("strides", None)
3404 try:
3405 typekey = (1, 1) + shape[2:], arr["typestr"]
3406 except KeyError as e:
3407 if mode is not None:
3408 typekey = None
3409 color_modes: list[str] = []
3410 else:
3411 msg = "Cannot handle this data type"
3412 raise TypeError(msg) from e
3413 if typekey is not None:
3414 try:
3415 typemode, rawmode, color_modes = _fromarray_typemap[typekey]
3416 except KeyError as e:
3417 typekey_shape, typestr = typekey
3418 msg = f"Cannot handle this data type: {typekey_shape}, {typestr}"
3419 raise TypeError(msg) from e
3420 if mode is not None:
3421 if mode != typemode and mode not in color_modes:
3422 deprecate("'mode' parameter for changing data types", 13)
3423 rawmode = mode
3424 else:
3425 mode = typemode
3426 if mode in ["1", "L", "I", "P", "F"]:
3427 ndmax = 2
3428 elif mode == "RGB":
3429 ndmax = 3
3430 else:
3431 ndmax = 4
3432 if ndim > ndmax:
3433 msg = f"Too many dimensions: {ndim} > {ndmax}."
3434 raise ValueError(msg)
3436 size = 1 if ndim == 1 else shape[1], shape[0]
3437 if strides is not None:
3438 if hasattr(obj, "tobytes"):
3439 obj = obj.tobytes()
3440 elif hasattr(obj, "tostring"):
3441 obj = obj.tostring()
3442 else:
3443 msg = "'strides' requires either tobytes() or tostring()"
3444 raise ValueError(msg)
3446 return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)
3449def fromarrow(
3450 obj: SupportsArrowArrayInterface, mode: str, size: tuple[int, int]
3451) -> Image:
3452 """Creates an image with zero-copy shared memory from an object exporting
3453 the arrow_c_array interface protocol::
3455 from PIL import Image
3456 import pyarrow as pa
3457 arr = pa.array([0]*(5*5*4), type=pa.uint8())
3458 im = Image.fromarrow(arr, 'RGBA', (5, 5))
3460 If the data representation of the ``obj`` is not compatible with
3461 Pillow internal storage, a ValueError is raised.
3463 Pillow images can also be converted to Arrow objects::
3465 from PIL import Image
3466 import pyarrow as pa
3467 im = Image.open('hopper.jpg')
3468 arr = pa.array(im)
3470 As with array support, when converting Pillow images to arrays,
3471 only pixel values are transferred. This means that P and PA mode
3472 images will lose their palette.
3474 :param obj: Object with an arrow_c_array interface
3475 :param mode: Image mode.
3476 :param size: Image size. This must match the storage of the arrow object.
3477 :returns: An Image object
3479 Note that according to the Arrow spec, both the producer and the
3480 consumer should consider the exported array to be immutable, as
3481 unsynchronized updates will potentially cause inconsistent data.
3483 See: :ref:`arrow-support` for more detailed information
3485 .. versionadded:: 11.2.1
3487 """
3488 if not hasattr(obj, "__arrow_c_array__"):
3489 msg = "arrow_c_array interface not found"
3490 raise ValueError(msg)
3492 schema_capsule, array_capsule = obj.__arrow_c_array__()
3493 _im = core.new_arrow(mode, size, schema_capsule, array_capsule)
3494 if _im:
3495 return Image()._new(_im)
3497 msg = "new_arrow returned None without an exception"
3498 raise ValueError(msg)
3501def fromqimage(im: ImageQt.QImage) -> ImageFile.ImageFile:
3502 """Creates an image instance from a QImage image"""
3503 from . import ImageQt
3505 if not ImageQt.qt_is_installed:
3506 msg = "Qt bindings are not installed"
3507 raise ImportError(msg)
3508 return ImageQt.fromqimage(im)
3511def fromqpixmap(im: ImageQt.QPixmap) -> ImageFile.ImageFile:
3512 """Creates an image instance from a QPixmap image"""
3513 from . import ImageQt
3515 if not ImageQt.qt_is_installed:
3516 msg = "Qt bindings are not installed"
3517 raise ImportError(msg)
3518 return ImageQt.fromqpixmap(im)
3521_fromarray_typemap = {
3522 # (shape, typestr) => mode, rawmode, color modes
3523 # first two members of shape are set to one
3524 ((1, 1), "|b1"): ("1", "1;8", []),
3525 ((1, 1), "|u1"): ("L", "L", ["P"]),
3526 ((1, 1), "|i1"): ("I", "I;8", []),
3527 ((1, 1), "<u2"): ("I", "I;16", []),
3528 ((1, 1), ">u2"): ("I", "I;16B", []),
3529 ((1, 1), "<i2"): ("I", "I;16S", []),
3530 ((1, 1), ">i2"): ("I", "I;16BS", []),
3531 ((1, 1), "<u4"): ("I", "I;32", []),
3532 ((1, 1), ">u4"): ("I", "I;32B", []),
3533 ((1, 1), "<i4"): ("I", "I;32S", []),
3534 ((1, 1), ">i4"): ("I", "I;32BS", []),
3535 ((1, 1), "<f4"): ("F", "F;32F", []),
3536 ((1, 1), ">f4"): ("F", "F;32BF", []),
3537 ((1, 1), "<f8"): ("F", "F;64F", []),
3538 ((1, 1), ">f8"): ("F", "F;64BF", []),
3539 ((1, 1, 2), "|u1"): ("LA", "LA", ["La", "PA"]),
3540 ((1, 1, 3), "|u1"): ("RGB", "RGB", ["YCbCr", "LAB", "HSV"]),
3541 ((1, 1, 4), "|u1"): ("RGBA", "RGBA", ["RGBa", "RGBX", "CMYK"]),
3542 # shortcuts:
3543 ((1, 1), f"{_ENDIAN}i4"): ("I", "I", []),
3544 ((1, 1), f"{_ENDIAN}f4"): ("F", "F", []),
3545}
3548def _decompression_bomb_check(size: tuple[int, int]) -> None:
3549 if MAX_IMAGE_PIXELS is None:
3550 return
3552 pixels = max(1, size[0]) * max(1, size[1])
3554 if pixels > 2 * MAX_IMAGE_PIXELS:
3555 msg = (
3556 f"Image size ({pixels} pixels) exceeds limit of {2 * MAX_IMAGE_PIXELS} "
3557 "pixels, could be decompression bomb DOS attack."
3558 )
3559 raise DecompressionBombError(msg)
3561 if pixels > MAX_IMAGE_PIXELS:
3562 warnings.warn(
3563 f"Image size ({pixels} pixels) exceeds limit of {MAX_IMAGE_PIXELS} pixels, "
3564 "could be decompression bomb DOS attack.",
3565 DecompressionBombWarning,
3566 )
3569def open(
3570 fp: StrOrBytesPath | IO[bytes],
3571 mode: Literal["r"] = "r",
3572 formats: list[str] | tuple[str, ...] | None = None,
3573) -> ImageFile.ImageFile:
3574 """
3575 Opens and identifies the given image file.
3577 This is a lazy operation; this function identifies the file, but
3578 the file remains open and the actual image data is not read from
3579 the file until you try to process the data (or call the
3580 :py:meth:`~PIL.Image.Image.load` method). See
3581 :py:func:`~PIL.Image.new`. See :ref:`file-handling`.
3583 :param fp: A filename (string), os.PathLike object or a file object.
3584 The file object must implement ``file.read``,
3585 ``file.seek``, and ``file.tell`` methods,
3586 and be opened in binary mode. The file object will also seek to zero
3587 before reading.
3588 :param mode: The mode. If given, this argument must be "r".
3589 :param formats: A list or tuple of formats to attempt to load the file in.
3590 This can be used to restrict the set of formats checked.
3591 Pass ``None`` to try all supported formats. You can print the set of
3592 available formats by running ``python3 -m PIL`` or using
3593 the :py:func:`PIL.features.pilinfo` function.
3594 :returns: An :py:class:`~PIL.Image.Image` object.
3595 :exception FileNotFoundError: If the file cannot be found.
3596 :exception PIL.UnidentifiedImageError: If the image cannot be opened and
3597 identified.
3598 :exception ValueError: If the ``mode`` is not "r", or if a ``StringIO``
3599 instance is used for ``fp``.
3600 :exception TypeError: If ``formats`` is not ``None``, a list or a tuple.
3601 """
3603 if mode != "r":
3604 msg = f"bad mode {repr(mode)}" # type: ignore[unreachable]
3605 raise ValueError(msg)
3606 elif isinstance(fp, io.StringIO):
3607 msg = ( # type: ignore[unreachable]
3608 "StringIO cannot be used to open an image. "
3609 "Binary data must be used instead."
3610 )
3611 raise ValueError(msg)
3613 if formats is None:
3614 formats = ID
3615 elif not isinstance(formats, (list, tuple)):
3616 msg = "formats must be a list or tuple" # type: ignore[unreachable]
3617 raise TypeError(msg)
3619 exclusive_fp = False
3620 filename: str | bytes = ""
3621 if is_path(fp):
3622 filename = os.fspath(fp)
3623 fp = builtins.open(filename, "rb")
3624 exclusive_fp = True
3625 else:
3626 fp = cast(IO[bytes], fp)
3628 try:
3629 fp.seek(0)
3630 except (AttributeError, io.UnsupportedOperation):
3631 fp = io.BytesIO(fp.read())
3632 exclusive_fp = True
3634 prefix = fp.read(16)
3636 # Try to import just the plugin needed for this file extension
3637 # before falling back to preinit() which imports common plugins
3638 ext = os.path.splitext(filename)[1] if filename else ""
3639 if not _import_plugin_for_extension(ext):
3640 preinit()
3642 warning_messages: list[str] = []
3644 def _open_core(
3645 fp: IO[bytes],
3646 filename: str | bytes,
3647 prefix: bytes,
3648 formats: list[str] | tuple[str, ...],
3649 ) -> ImageFile.ImageFile | None:
3650 for i in formats:
3651 i = i.upper()
3652 if i not in OPEN:
3653 init()
3654 try:
3655 factory, accept = OPEN[i]
3656 result = not accept or accept(prefix)
3657 if isinstance(result, str):
3658 warning_messages.append(result)
3659 elif result:
3660 fp.seek(0)
3661 im = factory(fp, filename)
3662 _decompression_bomb_check(im.size)
3663 return im
3664 except (SyntaxError, IndexError, TypeError, struct.error) as e:
3665 if WARN_POSSIBLE_FORMATS:
3666 warning_messages.append(i + " opening failed. " + str(e))
3667 except BaseException:
3668 if exclusive_fp:
3669 fp.close()
3670 raise
3671 return None
3673 im = _open_core(fp, filename, prefix, formats)
3675 if im is None and formats is ID:
3676 # Try preinit (few common plugins) then init (all plugins)
3677 for loader in (preinit, init):
3678 checked_formats = ID.copy()
3679 loader()
3680 if formats != checked_formats:
3681 im = _open_core(
3682 fp,
3683 filename,
3684 prefix,
3685 tuple(f for f in formats if f not in checked_formats),
3686 )
3687 if im is not None:
3688 break
3690 if im:
3691 im._exclusive_fp = exclusive_fp
3692 return im
3694 if exclusive_fp:
3695 fp.close()
3696 for message in warning_messages:
3697 warnings.warn(message)
3698 msg = "cannot identify image file %r" % (filename if filename else fp)
3699 raise UnidentifiedImageError(msg)
3702#
3703# Image processing.
3706def alpha_composite(im1: Image, im2: Image) -> Image:
3707 """
3708 Alpha composite im2 over im1.
3710 :param im1: The first image. Must have mode RGBA or LA.
3711 :param im2: The second image. Must have the same mode and size as the first image.
3712 :returns: An :py:class:`~PIL.Image.Image` object.
3713 """
3715 im1.load()
3716 im2.load()
3717 return im1._new(core.alpha_composite(im1.im, im2.im))
3720def blend(im1: Image, im2: Image, alpha: float) -> Image:
3721 """
3722 Creates a new image by interpolating between two input images, using
3723 a constant alpha::
3725 out = image1 * (1.0 - alpha) + image2 * alpha
3727 :param im1: The first image.
3728 :param im2: The second image. Must have the same mode and size as
3729 the first image.
3730 :param alpha: The interpolation alpha factor. If alpha is 0.0, a
3731 copy of the first image is returned. If alpha is 1.0, a copy of
3732 the second image is returned. There are no restrictions on the
3733 alpha value. If necessary, the result is clipped to fit into
3734 the allowed output range.
3735 :returns: An :py:class:`~PIL.Image.Image` object.
3736 """
3738 im1.load()
3739 im2.load()
3740 return im1._new(core.blend(im1.im, im2.im, alpha))
3743def composite(image1: Image, image2: Image, mask: Image) -> Image:
3744 """
3745 Create composite image by blending images using a transparency mask.
3747 :param image1: The first image.
3748 :param image2: The second image. Must have the same mode and
3749 size as the first image.
3750 :param mask: A mask image. This image can have mode
3751 "1", "L", or "RGBA", and must have the same size as the
3752 other two images.
3753 """
3755 image = image2.copy()
3756 image.paste(image1, None, mask)
3757 return image
3760def eval(image: Image, *args: Callable[[int], float]) -> Image:
3761 """
3762 Applies the function (which should take one argument) to each pixel
3763 in the given image. If the image has more than one band, the same
3764 function is applied to each band. Note that the function is
3765 evaluated once for each possible pixel value, so you cannot use
3766 random components or other generators.
3768 :param image: The input image.
3769 :param function: A function object, taking one integer argument.
3770 :returns: An :py:class:`~PIL.Image.Image` object.
3771 """
3773 return image.point(args[0])
3776def merge(mode: str, bands: Sequence[Image]) -> Image:
3777 """
3778 Merge a set of single band images into a new multiband image.
3780 :param mode: The mode to use for the output image. See:
3781 :ref:`concept-modes`.
3782 :param bands: A sequence containing one single-band image for
3783 each band in the output image. All bands must have the
3784 same size.
3785 :returns: An :py:class:`~PIL.Image.Image` object.
3786 """
3788 if getmodebands(mode) != len(bands) or "*" in mode:
3789 msg = "wrong number of bands"
3790 raise ValueError(msg)
3791 for band in bands[1:]:
3792 if band.mode != getmodetype(mode):
3793 msg = "mode mismatch"
3794 raise ValueError(msg)
3795 if band.size != bands[0].size:
3796 msg = "size mismatch"
3797 raise ValueError(msg)
3798 for band in bands:
3799 band.load()
3800 return bands[0]._new(core.merge(mode, *[b.im for b in bands]))
3803# --------------------------------------------------------------------
3804# Plugin registry
3807def register_open(
3808 id: str,
3809 factory: (
3810 Callable[[IO[bytes], str | bytes], ImageFile.ImageFile]
3811 | type[ImageFile.ImageFile]
3812 ),
3813 accept: Callable[[bytes], bool | str] | None = None,
3814) -> None:
3815 """
3816 Register an image file plugin. This function should not be used
3817 in application code.
3819 :param id: An image format identifier.
3820 :param factory: An image file factory method.
3821 :param accept: An optional function that can be used to quickly
3822 reject images having another format.
3823 """
3824 id = id.upper()
3825 if id not in ID:
3826 ID.append(id)
3827 OPEN[id] = factory, accept
3830def register_mime(id: str, mimetype: str) -> None:
3831 """
3832 Registers an image MIME type by populating ``Image.MIME``. This function
3833 should not be used in application code.
3835 ``Image.MIME`` provides a mapping from image format identifiers to mime
3836 formats, but :py:meth:`~PIL.ImageFile.ImageFile.get_format_mimetype` can
3837 provide a different result for specific images.
3839 :param id: An image format identifier.
3840 :param mimetype: The image MIME type for this format.
3841 """
3842 MIME[id.upper()] = mimetype
3845def register_save(
3846 id: str, driver: Callable[[Image, IO[bytes], str | bytes], None]
3847) -> None:
3848 """
3849 Registers an image save function. This function should not be
3850 used in application code.
3852 :param id: An image format identifier.
3853 :param driver: A function to save images in this format.
3854 """
3855 SAVE[id.upper()] = driver
3858def register_save_all(
3859 id: str, driver: Callable[[Image, IO[bytes], str | bytes], None]
3860) -> None:
3861 """
3862 Registers an image function to save all the frames
3863 of a multiframe format. This function should not be
3864 used in application code.
3866 :param id: An image format identifier.
3867 :param driver: A function to save images in this format.
3868 """
3869 SAVE_ALL[id.upper()] = driver
3872def register_extension(id: str, extension: str) -> None:
3873 """
3874 Registers an image extension. This function should not be
3875 used in application code.
3877 :param id: An image format identifier.
3878 :param extension: An extension used for this format.
3879 """
3880 EXTENSION[extension.lower()] = id.upper()
3883def register_extensions(id: str, extensions: list[str]) -> None:
3884 """
3885 Registers image extensions. This function should not be
3886 used in application code.
3888 :param id: An image format identifier.
3889 :param extensions: A list of extensions used for this format.
3890 """
3891 for extension in extensions:
3892 register_extension(id, extension)
3895def registered_extensions() -> dict[str, str]:
3896 """
3897 Returns a dictionary containing all file extensions belonging
3898 to registered plugins
3899 """
3900 init()
3901 return EXTENSION
3904def register_decoder(name: str, decoder: type[ImageFile.PyDecoder]) -> None:
3905 """
3906 Registers an image decoder. This function should not be
3907 used in application code.
3909 :param name: The name of the decoder
3910 :param decoder: An ImageFile.PyDecoder object
3912 .. versionadded:: 4.1.0
3913 """
3914 DECODERS[name] = decoder
3917def register_encoder(name: str, encoder: type[ImageFile.PyEncoder]) -> None:
3918 """
3919 Registers an image encoder. This function should not be
3920 used in application code.
3922 :param name: The name of the encoder
3923 :param encoder: An ImageFile.PyEncoder object
3925 .. versionadded:: 4.1.0
3926 """
3927 ENCODERS[name] = encoder
3930# --------------------------------------------------------------------
3931# Simple display support.
3934def _show(image: Image, **options: Any) -> None:
3935 from . import ImageShow
3937 deprecate("Image._show", 13, "ImageShow.show")
3938 ImageShow.show(image, **options)
3941# --------------------------------------------------------------------
3942# Effects
3945def effect_mandelbrot(
3946 size: tuple[int, int], extent: tuple[float, float, float, float], quality: int
3947) -> Image:
3948 """
3949 Generate a Mandelbrot set covering the given extent.
3951 :param size: The requested size in pixels, as a 2-tuple:
3952 (width, height).
3953 :param extent: The extent to cover, as a 4-tuple:
3954 (x0, y0, x1, y1).
3955 :param quality: Quality.
3956 """
3957 return Image()._new(core.effect_mandelbrot(size, extent, quality))
3960def effect_noise(size: tuple[int, int], sigma: float) -> Image:
3961 """
3962 Generate Gaussian noise centered around 128.
3964 :param size: The requested size in pixels, as a 2-tuple:
3965 (width, height).
3966 :param sigma: Standard deviation of noise.
3967 """
3968 return Image()._new(core.effect_noise(size, sigma))
3971def linear_gradient(mode: str) -> Image:
3972 """
3973 Generate 256x256 linear gradient from black to white, top to bottom.
3975 :param mode: Input mode.
3976 """
3977 return Image()._new(core.linear_gradient(mode))
3980def radial_gradient(mode: str) -> Image:
3981 """
3982 Generate 256x256 radial gradient from black to white, centre to edge.
3984 :param mode: Input mode.
3985 """
3986 return Image()._new(core.radial_gradient(mode))
3989# --------------------------------------------------------------------
3990# Resources
3993def _apply_env_variables(env: dict[str, str] | None = None) -> None:
3994 env_dict = env if env is not None else os.environ
3996 for var_name, setter in [
3997 ("PILLOW_ALIGNMENT", core.set_alignment),
3998 ("PILLOW_BLOCK_SIZE", core.set_block_size),
3999 ("PILLOW_BLOCKS_MAX", core.set_blocks_max),
4000 ]:
4001 if var_name not in env_dict:
4002 continue
4004 var = env_dict[var_name].lower()
4006 units = 1
4007 for postfix, mul in [("k", 1024), ("m", 1024 * 1024)]:
4008 if var.endswith(postfix):
4009 units = mul
4010 var = var[: -len(postfix)]
4012 try:
4013 var_int = int(var) * units
4014 except ValueError:
4015 warnings.warn(f"{var_name} is not int")
4016 continue
4018 try:
4019 setter(var_int)
4020 except ValueError as e:
4021 warnings.warn(f"{var_name}: {e}")
4024_apply_env_variables()
4025atexit.register(core.clear_cache)
4028if TYPE_CHECKING:
4029 _ExifBase = MutableMapping[int, Any]
4030else:
4031 _ExifBase = MutableMapping
4034class Exif(_ExifBase):
4035 """
4036 This class provides read and write access to EXIF image data::
4038 from PIL import Image
4039 im = Image.open("exif.png")
4040 exif = im.getexif() # Returns an instance of this class
4042 Information can be read and written, iterated over or deleted::
4044 print(exif[274]) # 1
4045 exif[274] = 2
4046 for k, v in exif.items():
4047 print("Tag", k, "Value", v) # Tag 274 Value 2
4048 del exif[274]
4050 To access information beyond IFD0, :py:meth:`~PIL.Image.Exif.get_ifd`
4051 returns a dictionary::
4053 from PIL import ExifTags
4054 im = Image.open("exif_gps.jpg")
4055 exif = im.getexif()
4056 gps_ifd = exif.get_ifd(ExifTags.IFD.GPSInfo)
4057 print(gps_ifd)
4059 Other IFDs include ``ExifTags.IFD.Exif``, ``ExifTags.IFD.MakerNote``,
4060 ``ExifTags.IFD.Interop`` and ``ExifTags.IFD.IFD1``.
4062 :py:mod:`~PIL.ExifTags` also has enum classes to provide names for data::
4064 print(exif[ExifTags.Base.Software]) # PIL
4065 print(gps_ifd[ExifTags.GPS.GPSDateStamp]) # 1999:99:99 99:99:99
4066 """
4068 endian: str | None = None
4069 bigtiff = False
4070 _loaded = False
4072 def __init__(self) -> None:
4073 self._data: dict[int, Any] = {}
4074 self._hidden_data: dict[int, Any] = {}
4075 self._ifds: dict[int, dict[int, Any]] = {}
4076 self._info: TiffImagePlugin.ImageFileDirectory_v2 | None = None
4077 self._loaded_exif: bytes | None = None
4079 def _fixup(self, value: Any) -> Any:
4080 try:
4081 if len(value) == 1 and isinstance(value, tuple):
4082 return value[0]
4083 except Exception:
4084 pass
4085 return value
4087 def _fixup_dict(self, src_dict: dict[int, Any]) -> dict[int, Any]:
4088 # Helper function
4089 # returns a dict with any single item tuples/lists as individual values
4090 return {k: self._fixup(v) for k, v in src_dict.items()}
4092 def _get_ifd_dict(
4093 self, offset: int, group: int | None = None
4094 ) -> dict[int, Any] | None:
4095 try:
4096 # an offset pointer to the location of the nested embedded IFD.
4097 # It should be a long, but may be corrupted.
4098 self.fp.seek(offset)
4099 except (KeyError, TypeError):
4100 return None
4101 else:
4102 from . import TiffImagePlugin
4104 info = TiffImagePlugin.ImageFileDirectory_v2(self.head, group=group)
4105 info.load(self.fp)
4106 return self._fixup_dict(dict(info))
4108 def _get_head(self) -> bytes:
4109 version = b"\x2b" if self.bigtiff else b"\x2a"
4110 if self.endian == "<":
4111 head = b"II" + version + b"\x00" + o32le(8)
4112 else:
4113 head = b"MM\x00" + version + o32be(8)
4114 if self.bigtiff:
4115 head += o32le(8) if self.endian == "<" else o32be(8)
4116 head += b"\x00\x00\x00\x00"
4117 return head
4119 def load(self, data: bytes) -> None:
4120 # Extract EXIF information. This is highly experimental,
4121 # and is likely to be replaced with something better in a future
4122 # version.
4124 # The EXIF record consists of a TIFF file embedded in a JPEG
4125 # application marker (!).
4126 if data == self._loaded_exif:
4127 return
4128 self._loaded_exif = data
4129 self._data.clear()
4130 self._hidden_data.clear()
4131 self._ifds.clear()
4132 while data and data.startswith(b"Exif\x00\x00"):
4133 data = data[6:]
4134 if not data:
4135 self._info = None
4136 return
4138 self.fp: IO[bytes] = io.BytesIO(data)
4139 self.head = self.fp.read(8)
4140 # process dictionary
4141 from . import TiffImagePlugin
4143 self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head)
4144 self.endian = self._info._endian
4145 self.fp.seek(self._info.next)
4146 self._info.load(self.fp)
4148 def load_from_fp(self, fp: IO[bytes], offset: int | None = None) -> None:
4149 self._loaded_exif = None
4150 self._data.clear()
4151 self._hidden_data.clear()
4152 self._ifds.clear()
4154 # process dictionary
4155 from . import TiffImagePlugin
4157 self.fp = fp
4158 if offset is not None:
4159 self.head = self._get_head()
4160 else:
4161 self.head = self.fp.read(8)
4162 self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head)
4163 if self.endian is None:
4164 self.endian = self._info._endian
4165 if offset is None:
4166 offset = self._info.next
4167 self.fp.tell()
4168 self.fp.seek(offset)
4169 self._info.load(self.fp)
4171 def _get_merged_dict(self) -> dict[int, Any]:
4172 merged_dict = dict(self)
4174 # get EXIF extension
4175 if ExifTags.IFD.Exif in self:
4176 ifd = self._get_ifd_dict(self[ExifTags.IFD.Exif], ExifTags.IFD.Exif)
4177 if ifd:
4178 merged_dict.update(ifd)
4180 # GPS
4181 if ExifTags.IFD.GPSInfo in self:
4182 merged_dict[ExifTags.IFD.GPSInfo] = self._get_ifd_dict(
4183 self[ExifTags.IFD.GPSInfo], ExifTags.IFD.GPSInfo
4184 )
4186 return merged_dict
4188 def tobytes(self, offset: int = 8) -> bytes:
4189 from . import TiffImagePlugin
4191 head = self._get_head()
4192 ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)
4193 for tag, ifd_dict in self._ifds.items():
4194 if tag not in self:
4195 ifd[tag] = ifd_dict
4196 for tag, value in self.items():
4197 if tag in [
4198 ExifTags.IFD.Exif,
4199 ExifTags.IFD.GPSInfo,
4200 ] and not isinstance(value, dict):
4201 value = self.get_ifd(tag)
4202 if (
4203 tag == ExifTags.IFD.Exif
4204 and ExifTags.IFD.Interop in value
4205 and not isinstance(value[ExifTags.IFD.Interop], dict)
4206 ):
4207 value = value.copy()
4208 value[ExifTags.IFD.Interop] = self.get_ifd(ExifTags.IFD.Interop)
4209 ifd[tag] = value
4210 return b"Exif\x00\x00" + head + ifd.tobytes(offset)
4212 def get_ifd(self, tag: int) -> dict[int, Any]:
4213 if tag not in self._ifds:
4214 if tag == ExifTags.IFD.IFD1:
4215 if self._info is not None and self._info.next != 0:
4216 ifd = self._get_ifd_dict(self._info.next)
4217 if ifd is not None:
4218 self._ifds[tag] = ifd
4219 elif tag in [ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo]:
4220 offset = self._hidden_data.get(tag, self.get(tag))
4221 if offset is not None:
4222 ifd = self._get_ifd_dict(offset, tag)
4223 if ifd is not None:
4224 self._ifds[tag] = ifd
4225 elif tag in [ExifTags.IFD.Interop, ExifTags.IFD.MakerNote]:
4226 if ExifTags.IFD.Exif not in self._ifds:
4227 self.get_ifd(ExifTags.IFD.Exif)
4228 tag_data = self._ifds[ExifTags.IFD.Exif][tag]
4229 if tag == ExifTags.IFD.MakerNote:
4230 from .TiffImagePlugin import ImageFileDirectory_v2
4232 if tag_data.startswith(b"FUJIFILM"):
4233 ifd_offset = i32le(tag_data, 8)
4234 ifd_data = tag_data[ifd_offset:]
4236 makernote = {}
4237 for i in range(struct.unpack("<H", ifd_data[:2])[0]):
4238 ifd_tag, typ, count, data = struct.unpack(
4239 "<HHL4s", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]
4240 )
4241 try:
4242 (
4243 unit_size,
4244 handler,
4245 ) = ImageFileDirectory_v2._load_dispatch[typ]
4246 except KeyError:
4247 continue
4248 size = count * unit_size
4249 if size > 4:
4250 (offset,) = struct.unpack("<L", data)
4251 data = ifd_data[offset - 12 : offset + size - 12]
4252 else:
4253 data = data[:size]
4255 if len(data) != size:
4256 warnings.warn(
4257 "Possibly corrupt EXIF MakerNote data. "
4258 f"Expecting to read {size} bytes but only got "
4259 f"{len(data)}. Skipping tag {ifd_tag}"
4260 )
4261 continue
4263 if not data:
4264 continue
4266 makernote[ifd_tag] = handler(
4267 ImageFileDirectory_v2(), data, False
4268 )
4269 self._ifds[tag] = dict(self._fixup_dict(makernote))
4270 elif self.get(0x010F) == "Nintendo":
4271 makernote = {}
4272 for i in range(struct.unpack(">H", tag_data[:2])[0]):
4273 ifd_tag, typ, count, data = struct.unpack(
4274 ">HHL4s", tag_data[i * 12 + 2 : (i + 1) * 12 + 2]
4275 )
4276 if ifd_tag == 0x1101:
4277 # CameraInfo
4278 (offset,) = struct.unpack(">L", data)
4279 self.fp.seek(offset)
4281 camerainfo: dict[str, int | bytes] = {
4282 "ModelID": self.fp.read(4)
4283 }
4285 self.fp.read(4)
4286 # Seconds since 2000
4287 camerainfo["TimeStamp"] = i32le(self.fp.read(12))
4289 self.fp.read(4)
4290 camerainfo["InternalSerialNumber"] = self.fp.read(4)
4292 self.fp.read(12)
4293 parallax = self.fp.read(4)
4294 handler = ImageFileDirectory_v2._load_dispatch[
4295 TiffTags.FLOAT
4296 ][1]
4297 camerainfo["Parallax"] = handler(
4298 ImageFileDirectory_v2(), parallax, False
4299 )[0]
4301 self.fp.read(4)
4302 camerainfo["Category"] = self.fp.read(2)
4304 makernote = {0x1101: camerainfo}
4305 self._ifds[tag] = makernote
4306 else:
4307 # Interop
4308 ifd = self._get_ifd_dict(tag_data, tag)
4309 if ifd is not None:
4310 self._ifds[tag] = ifd
4311 ifd = self._ifds.setdefault(tag, {})
4312 if tag == ExifTags.IFD.Exif and self._hidden_data:
4313 ifd = {
4314 k: v
4315 for (k, v) in ifd.items()
4316 if k not in (ExifTags.IFD.Interop, ExifTags.IFD.MakerNote)
4317 }
4318 return ifd
4320 def hide_offsets(self) -> None:
4321 for tag in (ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo):
4322 if tag in self:
4323 self._hidden_data[tag] = self[tag]
4324 del self[tag]
4326 def __str__(self) -> str:
4327 if self._info is not None:
4328 # Load all keys into self._data
4329 for tag in self._info:
4330 self[tag]
4332 return str(self._data)
4334 def __len__(self) -> int:
4335 keys = set(self._data)
4336 if self._info is not None:
4337 keys.update(self._info)
4338 return len(keys)
4340 def __getitem__(self, tag: int) -> Any:
4341 if self._info is not None and tag not in self._data and tag in self._info:
4342 self._data[tag] = self._fixup(self._info[tag])
4343 del self._info[tag]
4344 return self._data[tag]
4346 def __contains__(self, tag: object) -> bool:
4347 return tag in self._data or (self._info is not None and tag in self._info)
4349 def __setitem__(self, tag: int, value: Any) -> None:
4350 if self._info is not None and tag in self._info:
4351 del self._info[tag]
4352 self._data[tag] = value
4354 def __delitem__(self, tag: int) -> None:
4355 if self._info is not None and tag in self._info:
4356 del self._info[tag]
4357 else:
4358 del self._data[tag]
4359 if tag in self._ifds:
4360 del self._ifds[tag]
4362 def __iter__(self) -> Iterator[int]:
4363 keys = set(self._data)
4364 if self._info is not None:
4365 keys.update(self._info)
4366 return iter(keys)