id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
174,033
from struct import pack, unpack_from def unpack_from(__format: _FmtType, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ... The provided code snippet includes necessary dependencies for implementing the `si16be` function. Write a Python function `def si16be(c, o=0)` to solve the following problem: Converts a 2-bytes (16 bits) string to a signed integer, big endian. :param c: string containing bytes to convert :param o: offset of bytes to convert in string Here is the function: def si16be(c, o=0): """ Converts a 2-bytes (16 bits) string to a signed integer, big endian. :param c: string containing bytes to convert :param o: offset of bytes to convert in string """ return unpack_from(">h", c, o)[0]
Converts a 2-bytes (16 bits) string to a signed integer, big endian. :param c: string containing bytes to convert :param o: offset of bytes to convert in string
174,034
from struct import pack, unpack_from def unpack_from(__format: _FmtType, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ... The provided code snippet includes necessary dependencies for implementing the `i32le` function. Write a Python function `def i32le(c, o=0)` to solve the following problem: Converts a 4-bytes (32 bits) string to an unsigned integer. :param c: string containing bytes to convert :param o: offset of bytes to convert in string Here is the function: def i32le(c, o=0): """ Converts a 4-bytes (32 bits) string to an unsigned integer. :param c: string containing bytes to convert :param o: offset of bytes to convert in string """ return unpack_from("<I", c, o)[0]
Converts a 4-bytes (32 bits) string to an unsigned integer. :param c: string containing bytes to convert :param o: offset of bytes to convert in string
174,035
from struct import pack, unpack_from def unpack_from(__format: _FmtType, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ... The provided code snippet includes necessary dependencies for implementing the `si32le` function. Write a Python function `def si32le(c, o=0)` to solve the following problem: Converts a 4-bytes (32 bits) string to a signed integer. :param c: string containing bytes to convert :param o: offset of bytes to convert in string Here is the function: def si32le(c, o=0): """ Converts a 4-bytes (32 bits) string to a signed integer. :param c: string containing bytes to convert :param o: offset of bytes to convert in string """ return unpack_from("<i", c, o)[0]
Converts a 4-bytes (32 bits) string to a signed integer. :param c: string containing bytes to convert :param o: offset of bytes to convert in string
174,036
from struct import pack, unpack_from def unpack_from(__format: _FmtType, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ... def i32be(c, o=0): return unpack_from(">I", c, o)[0]
null
174,037
from struct import pack, unpack_from def pack(fmt: _FmtType, *v: Any) -> bytes: ... def o16le(i): return pack("<H", i)
null
174,038
from struct import pack, unpack_from def pack(fmt: _FmtType, *v: Any) -> bytes: ... def o32be(i): return pack(">I", i)
null
174,041
from . import Image, ImageFile from ._binary import i32le as i32 class WalImageFile(ImageFile.ImageFile): format = "WAL" format_description = "Quake2 Texture" def _open(self): self.mode = "P" # read header fields header = self.fp.read(32 + 24 + 32 + 12) self._size = i32(header, 32), i32(header, 36) Image._decompression_bomb_check(self.size) # load pixel data offset = i32(header, 40) self.fp.seek(offset) # strings are null-terminated self.info["name"] = header[:32].split(b"\0", 1)[0] next_name = header[56 : 56 + 32].split(b"\0", 1)[0] if next_name: self.info["next_name"] = next_name def load(self): if not self.im: self.im = Image.core.new(self.mode, self.size) self.frombytes(self.fp.read(self.size[0] * self.size[1])) self.putpalette(quake2palette) return Image.Image.load(self) The provided code snippet includes necessary dependencies for implementing the `open` function. Write a Python function `def open(filename)` to solve the following problem: Load texture from a Quake2 WAL texture file. By default, a Quake2 standard palette is attached to the texture. To override the palette, use the :py:func:`PIL.Image.Image.putpalette()` method. :param filename: WAL file name, or an opened file handle. :returns: An image instance. Here is the function: def open(filename): """ Load texture from a Quake2 WAL texture file. By default, a Quake2 standard palette is attached to the texture. To override the palette, use the :py:func:`PIL.Image.Image.putpalette()` method. :param filename: WAL file name, or an opened file handle. :returns: An image instance. """ return WalImageFile(filename)
Load texture from a Quake2 WAL texture file. By default, a Quake2 standard palette is attached to the texture. To override the palette, use the :py:func:`PIL.Image.Image.putpalette()` method. :param filename: WAL file name, or an opened file handle. :returns: An image instance.
174,042
import itertools import math import os import subprocess from enum import IntEnum from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence from ._binary import i16le as i16 from ._binary import o8 from ._binary import o16le as o16 def _accept(prefix): return prefix[:6] in [b"GIF87a", b"GIF89a"]
null
174,043
import itertools import math import os import subprocess from enum import IntEnum from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence from ._binary import i16le as i16 from ._binary import o8 from ._binary import o16le as o16 def _save(im, fp, filename, save_all=False): # header if "palette" in im.encoderinfo or "palette" in im.info: palette = im.encoderinfo.get("palette", im.info.get("palette")) else: palette = None im.encoderinfo["optimize"] = im.encoderinfo.get("optimize", True) if not save_all or not _write_multiple_frames(im, fp, palette): _write_single_frame(im, fp, palette) fp.write(b";") # end of file if hasattr(fp, "flush"): fp.flush() def _save_all(im, fp, filename): _save(im, fp, filename, save_all=True)
null
174,044
import itertools import math import os import subprocess from enum import IntEnum from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence from ._binary import i16le as i16 from ._binary import o8 from ._binary import o16le as o16 def _save_netpbm(im, fp, filename): # Unused by default. # To use, uncomment the register_save call at the end of the file. # # If you need real GIF compression and/or RGB quantization, you # can use the external NETPBM/PBMPLUS utilities. See comments # below for information on how to enable this. tempfile = im._dump() try: with open(filename, "wb") as f: if im.mode != "RGB": subprocess.check_call( ["ppmtogif", tempfile], stdout=f, stderr=subprocess.DEVNULL ) else: # Pipe ppmquant output into ppmtogif # "ppmquant 256 %s | ppmtogif > %s" % (tempfile, filename) quant_cmd = ["ppmquant", "256", tempfile] togif_cmd = ["ppmtogif"] quant_proc = subprocess.Popen( quant_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL ) togif_proc = subprocess.Popen( togif_cmd, stdin=quant_proc.stdout, stdout=f, stderr=subprocess.DEVNULL, ) # Allow ppmquant to receive SIGPIPE if ppmtogif exits quant_proc.stdout.close() retcode = quant_proc.wait() if retcode: raise subprocess.CalledProcessError(retcode, quant_cmd) retcode = togif_proc.wait() if retcode: raise subprocess.CalledProcessError(retcode, togif_cmd) finally: try: os.unlink(tempfile) except OSError: pass
null
174,045
import itertools import math import os import subprocess from enum import IntEnum from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence from ._binary import i16le as i16 from ._binary import o8 from ._binary import o16le as o16 def _normalize_palette(im, palette, info): """ Normalizes the palette for image. - Sets the palette to the incoming palette, if provided. - Ensures that there's a palette for L mode images - Optimizes the palette if necessary/desired. :param im: Image object :param palette: bytes object containing the source palette, or .... :param info: encoderinfo :returns: Image object """ source_palette = None if palette: # a bytes palette if isinstance(palette, (bytes, bytearray, list)): source_palette = bytearray(palette[:768]) if isinstance(palette, ImagePalette.ImagePalette): source_palette = bytearray(palette.palette) if im.mode == "P": if not source_palette: source_palette = im.im.getpalette("RGB")[:768] else: # L-mode if not source_palette: source_palette = bytearray(i // 3 for i in range(768)) im.palette = ImagePalette.ImagePalette("RGB", palette=source_palette) if palette: used_palette_colors = [] for i in range(0, len(source_palette), 3): source_color = tuple(source_palette[i : i + 3]) index = im.palette.colors.get(source_color) if index in used_palette_colors: index = None used_palette_colors.append(index) for i, index in enumerate(used_palette_colors): if index is None: for j in range(len(used_palette_colors)): if j not in used_palette_colors: used_palette_colors[i] = j break im = im.remap_palette(used_palette_colors) else: used_palette_colors = _get_optimize(im, info) if used_palette_colors is not None: return im.remap_palette(used_palette_colors, source_palette) im.palette.palette = source_palette return im def _get_optimize(im, info): """ Palette optimization is a potentially expensive operation. This function determines if the palette should be optimized using some heuristics, then returns the list of palette entries in use. :param im: Image object :param info: encoderinfo :returns: list of indexes of palette entries in use, or None """ if im.mode in ("P", "L") and info and info.get("optimize", 0): # Potentially expensive operation. # The palette saves 3 bytes per color not used, but palette # lengths are restricted to 3*(2**N) bytes. Max saving would # be 768 -> 6 bytes if we went all the way down to 2 colors. # * If we're over 128 colors, we can't save any space. # * If there aren't any holes, it's not worth collapsing. # * If we have a 'large' image, the palette is in the noise. # create the new palette if not every color is used optimise = _FORCE_OPTIMIZE or im.mode == "L" if optimise or im.width * im.height < 512 * 512: # check which colors are used used_palette_colors = [] for i, count in enumerate(im.histogram()): if count: used_palette_colors.append(i) if optimise or max(used_palette_colors) >= len(used_palette_colors): return used_palette_colors num_palette_colors = len(im.palette.palette) // Image.getmodebands( im.palette.mode ) current_palette_size = 1 << (num_palette_colors - 1).bit_length() if ( # check that the palette would become smaller when saved len(used_palette_colors) <= current_palette_size // 2 # check that the palette is not already the smallest possible size and current_palette_size > 2 ): return used_palette_colors def _get_global_header(im, info): """Return a list of strings representing a GIF header""" # Header Block # https://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp version = b"87a" if im.info.get("version") == b"89a" or ( info and ( "transparency" in info or "loop" in info or info.get("duration") or info.get("comment") ) ): version = b"89a" background = _get_background(im, info.get("background")) palette_bytes = _get_palette_bytes(im) color_table_size = _get_color_table_size(palette_bytes) header = [ b"GIF" # signature + version # version + o16(im.size[0]) # canvas width + o16(im.size[1]), # canvas height # Logical Screen Descriptor # size of global color table + global color table flag o8(color_table_size + 128), # packed fields # background + reserved/aspect o8(background) + o8(0), # Global Color Table _get_header_palette(palette_bytes), ] if "loop" in info: header.append( b"!" + o8(255) # extension intro + o8(11) + b"NETSCAPE2.0" + o8(3) + o8(1) + o16(info["loop"]) # number of loops + o8(0) ) if info.get("comment"): comment_block = b"!" + o8(254) # extension intro comment = info["comment"] if isinstance(comment, str): comment = comment.encode() for i in range(0, len(comment), 255): subblock = comment[i : i + 255] comment_block += o8(len(subblock)) + subblock comment_block += o8(0) header.append(comment_block) return header The provided code snippet includes necessary dependencies for implementing the `getheader` function. Write a Python function `def getheader(im, palette=None, info=None)` to solve the following problem: Legacy Method to get Gif data from image. Warning:: May modify image data. :param im: Image object :param palette: bytes object containing the source palette, or .... :param info: encoderinfo :returns: tuple of(list of header items, optimized palette) Here is the function: def getheader(im, palette=None, info=None): """ Legacy Method to get Gif data from image. Warning:: May modify image data. :param im: Image object :param palette: bytes object containing the source palette, or .... :param info: encoderinfo :returns: tuple of(list of header items, optimized palette) """ used_palette_colors = _get_optimize(im, info) if info is None: info = {} if "background" not in info and "background" in im.info: info["background"] = im.info["background"] im_mod = _normalize_palette(im, palette, info) im.palette = im_mod.palette im.im = im_mod.im header = _get_global_header(im, info) return header, used_palette_colors
Legacy Method to get Gif data from image. Warning:: May modify image data. :param im: Image object :param palette: bytes object containing the source palette, or .... :param info: encoderinfo :returns: tuple of(list of header items, optimized palette)
174,046
import itertools import math import os import subprocess from enum import IntEnum from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence from ._binary import i16le as i16 from ._binary import o8 from ._binary import o16le as o16 def _write_frame_data(fp, im_frame, offset, params): try: im_frame.encoderinfo = params # local image header _write_local_header(fp, im_frame, offset, 0) ImageFile._save( im_frame, fp, [("gif", (0, 0) + im_frame.size, 0, RAWMODE[im_frame.mode])] ) fp.write(b"\0") # end of image data finally: del im_frame.encoderinfo The provided code snippet includes necessary dependencies for implementing the `getdata` function. Write a Python function `def getdata(im, offset=(0, 0), **params)` to solve the following problem: Legacy Method Return a list of strings representing this image. The first string is a local image header, the rest contains encoded image data. To specify duration, add the time in milliseconds, e.g. ``getdata(im_frame, duration=1000)`` :param im: Image object :param offset: Tuple of (x, y) pixels. Defaults to (0, 0) :param \\**params: e.g. duration or other encoder info parameters :returns: List of bytes containing GIF encoded frame data Here is the function: def getdata(im, offset=(0, 0), **params): """ Legacy Method Return a list of strings representing this image. The first string is a local image header, the rest contains encoded image data. To specify duration, add the time in milliseconds, e.g. ``getdata(im_frame, duration=1000)`` :param im: Image object :param offset: Tuple of (x, y) pixels. Defaults to (0, 0) :param \\**params: e.g. duration or other encoder info parameters :returns: List of bytes containing GIF encoded frame data """ class Collector: data = [] def write(self, data): self.data.append(data) im.load() # make sure raster data is available fp = Collector() _write_frame_data(fp, im, offset, params) return fp.data
Legacy Method Return a list of strings representing this image. The first string is a local image header, the rest contains encoded image data. To specify duration, add the time in milliseconds, e.g. ``getdata(im_frame, duration=1000)`` :param im: Image object :param offset: Tuple of (x, y) pixels. Defaults to (0, 0) :param \\**params: e.g. duration or other encoder info parameters :returns: List of bytes containing GIF encoded frame data
174,047
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate class Intent(IntEnum): PERCEPTUAL = 0 RELATIVE_COLORIMETRIC = 1 SATURATION = 2 ABSOLUTE_COLORIMETRIC = 3 class Direction(IntEnum): INPUT = 0 OUTPUT = 1 PROOF = 2 def deprecate( deprecated: str, when: int | None, replacement: str | None = None, *, action: str | None = None, plural: bool = False, ) -> None: """ Deprecations helper. :param deprecated: Name of thing to be deprecated. :param when: Pillow major version to be removed in. :param replacement: Name of replacement. :param action: Instead of "replacement", give a custom call to action e.g. "Upgrade to new thing". :param plural: if the deprecated thing is plural, needing "are" instead of "is". Usually of the form: "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd). Use [replacement] instead." You can leave out the replacement sentence: "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd)" Or with another call to action: "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd). [action]." """ is_ = "are" if plural else "is" if when is None: removed = "a future version" elif when <= int(__version__.split(".")[0]): msg = f"{deprecated} {is_} deprecated and should be removed." raise RuntimeError(msg) elif when == 10: removed = "Pillow 10 (2023-07-01)" elif when == 11: removed = "Pillow 11 (2024-10-15)" else: msg = f"Unknown removal version: {when}. Update {__name__}?" raise ValueError(msg) if replacement and action: msg = "Use only one of 'replacement' and 'action'" raise ValueError(msg) if replacement: action = f". Use {replacement} instead." elif action: action = f". {action.rstrip('.')}." else: action = "" warnings.warn( f"{deprecated} {is_} deprecated and will be removed in {removed}{action}", DeprecationWarning, stacklevel=3, ) def __getattr__(name): for enum, prefix in {Intent: "INTENT_", Direction: "DIRECTION_"}.items(): if name.startswith(prefix): name = name[len(prefix) :] if name in enum.__members__: deprecate(f"{prefix}{name}", 10, f"{enum.__name__}.{name}") return enum[name] msg = f"module '{__name__}' has no attribute '{name}'" raise AttributeError(msg)
null
174,048
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate try: from PIL import _imagingcms except ImportError as ex: # Allow error import for doc purposes, but error out when accessing # anything in core. from ._util import DeferredError _imagingcms = DeferredError(ex) core = _imagingcms class ImageCmsProfile: def __init__(self, profile): """ :param profile: Either a string representing a filename, a file like object containing a profile or a low-level profile object """ if isinstance(profile, str): if sys.platform == "win32": profile_bytes_path = profile.encode() try: profile_bytes_path.decode("ascii") except UnicodeDecodeError: with open(profile, "rb") as f: self._set(core.profile_frombytes(f.read())) return self._set(core.profile_open(profile), profile) elif hasattr(profile, "read"): self._set(core.profile_frombytes(profile.read())) elif isinstance(profile, _imagingcms.CmsProfile): self._set(profile) else: msg = "Invalid type for Profile" raise TypeError(msg) def _set(self, profile, filename=None): self.profile = profile self.filename = filename if profile: self.product_name = None # profile.product_name self.product_info = None # profile.product_info else: self.product_name = None self.product_info = None def tobytes(self): """ Returns the profile in a format suitable for embedding in saved images. :returns: a bytes object containing the ICC profile. """ return core.profile_tobytes(self.profile) The provided code snippet includes necessary dependencies for implementing the `get_display_profile` function. Write a Python function `def get_display_profile(handle=None)` to solve the following problem: (experimental) Fetches the profile for the current display device. :returns: ``None`` if the profile is not known. Here is the function: def get_display_profile(handle=None): """ (experimental) Fetches the profile for the current display device. :returns: ``None`` if the profile is not known. """ if sys.platform != "win32": return None from PIL import ImageWin if isinstance(handle, ImageWin.HDC): profile = core.get_display_profile_win32(handle, 1) else: profile = core.get_display_profile_win32(handle or 0) if profile is None: return None return ImageCmsProfile(profile)
(experimental) Fetches the profile for the current display device. :returns: ``None`` if the profile is not known.
174,049
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate class Intent(IntEnum): PERCEPTUAL = 0 RELATIVE_COLORIMETRIC = 1 SATURATION = 2 ABSOLUTE_COLORIMETRIC = 3 _MAX_FLAG = 0 class ImageCmsProfile: def __init__(self, profile): """ :param profile: Either a string representing a filename, a file like object containing a profile or a low-level profile object """ if isinstance(profile, str): if sys.platform == "win32": profile_bytes_path = profile.encode() try: profile_bytes_path.decode("ascii") except UnicodeDecodeError: with open(profile, "rb") as f: self._set(core.profile_frombytes(f.read())) return self._set(core.profile_open(profile), profile) elif hasattr(profile, "read"): self._set(core.profile_frombytes(profile.read())) elif isinstance(profile, _imagingcms.CmsProfile): self._set(profile) else: msg = "Invalid type for Profile" raise TypeError(msg) def _set(self, profile, filename=None): self.profile = profile self.filename = filename if profile: self.product_name = None # profile.product_name self.product_info = None # profile.product_info else: self.product_name = None self.product_info = None def tobytes(self): """ Returns the profile in a format suitable for embedding in saved images. :returns: a bytes object containing the ICC profile. """ return core.profile_tobytes(self.profile) class ImageCmsTransform(Image.ImagePointHandler): """ Transform. This can be used with the procedural API, or with the standard :py:func:`~PIL.Image.Image.point` method. Will return the output profile in the ``output.info['icc_profile']``. """ def __init__( self, input, output, input_mode, output_mode, intent=Intent.PERCEPTUAL, proof=None, proof_intent=Intent.ABSOLUTE_COLORIMETRIC, flags=0, ): if proof is None: self.transform = core.buildTransform( input.profile, output.profile, input_mode, output_mode, intent, flags ) else: self.transform = core.buildProofTransform( input.profile, output.profile, proof.profile, input_mode, output_mode, intent, proof_intent, flags, ) # Note: inputMode and outputMode are for pyCMS compatibility only self.input_mode = self.inputMode = input_mode self.output_mode = self.outputMode = output_mode self.output_profile = output def point(self, im): return self.apply(im) def apply(self, im, imOut=None): im.load() if imOut is None: imOut = Image.new(self.output_mode, im.size, None) self.transform.apply(im.im.id, imOut.im.id) imOut.info["icc_profile"] = self.output_profile.tobytes() return imOut def apply_in_place(self, im): im.load() if im.mode != self.output_mode: msg = "mode mismatch" raise ValueError(msg) # wrong output mode self.transform.apply(im.im.id, im.im.id) im.info["icc_profile"] = self.output_profile.tobytes() return im class PyCMSError(Exception): """(pyCMS) Exception class. This is used for all errors in the pyCMS API.""" pass The provided code snippet includes necessary dependencies for implementing the `profileToProfile` function. Write a Python function `def profileToProfile( im, inputProfile, outputProfile, renderingIntent=Intent.PERCEPTUAL, outputMode=None, inPlace=False, flags=0, )` to solve the following problem: (pyCMS) Applies an ICC transformation to a given image, mapping from ``inputProfile`` to ``outputProfile``. If the input or output profiles specified are not valid filenames, a :exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and ``outputMode != im.mode``, a :exc:`PyCMSError` will be raised. If an error occurs during application of the profiles, a :exc:`PyCMSError` will be raised. If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS), a :exc:`PyCMSError` will be raised. This function applies an ICC transformation to im from ``inputProfile``'s color space to ``outputProfile``'s color space using the specified rendering intent to decide how to handle out-of-gamut colors. ``outputMode`` can be used to specify that a color mode conversion is to be done using these profiles, but the specified profiles must be able to handle that mode. I.e., if converting im from RGB to CMYK using profiles, the input profile must handle RGB data, and the output profile must handle CMYK data. :param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...) or Image.open(...), etc.) :param inputProfile: String, as a valid filename path to the ICC input profile you wish to use for this image, or a profile object :param outputProfile: String, as a valid filename path to the ICC output profile you wish to use for this image, or a profile object :param renderingIntent: Integer (0-3) specifying the rendering intent you wish to use for the transform ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :param outputMode: A valid PIL mode for the output image (i.e. "RGB", "CMYK", etc.). Note: if rendering the image "inPlace", outputMode MUST be the same mode as the input, or omitted completely. If omitted, the outputMode will be the same as the mode of the input image (im.mode) :param inPlace: Boolean. If ``True``, the original image is modified in-place, and ``None`` is returned. If ``False`` (default), a new :py:class:`~PIL.Image.Image` object is returned with the transform applied. :param flags: Integer (0-...) specifying additional flags :returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on the value of ``inPlace`` :exception PyCMSError: Here is the function: def profileToProfile( im, inputProfile, outputProfile, renderingIntent=Intent.PERCEPTUAL, outputMode=None, inPlace=False, flags=0, ): """ (pyCMS) Applies an ICC transformation to a given image, mapping from ``inputProfile`` to ``outputProfile``. If the input or output profiles specified are not valid filenames, a :exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and ``outputMode != im.mode``, a :exc:`PyCMSError` will be raised. If an error occurs during application of the profiles, a :exc:`PyCMSError` will be raised. If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS), a :exc:`PyCMSError` will be raised. This function applies an ICC transformation to im from ``inputProfile``'s color space to ``outputProfile``'s color space using the specified rendering intent to decide how to handle out-of-gamut colors. ``outputMode`` can be used to specify that a color mode conversion is to be done using these profiles, but the specified profiles must be able to handle that mode. I.e., if converting im from RGB to CMYK using profiles, the input profile must handle RGB data, and the output profile must handle CMYK data. :param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...) or Image.open(...), etc.) :param inputProfile: String, as a valid filename path to the ICC input profile you wish to use for this image, or a profile object :param outputProfile: String, as a valid filename path to the ICC output profile you wish to use for this image, or a profile object :param renderingIntent: Integer (0-3) specifying the rendering intent you wish to use for the transform ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :param outputMode: A valid PIL mode for the output image (i.e. "RGB", "CMYK", etc.). Note: if rendering the image "inPlace", outputMode MUST be the same mode as the input, or omitted completely. If omitted, the outputMode will be the same as the mode of the input image (im.mode) :param inPlace: Boolean. If ``True``, the original image is modified in-place, and ``None`` is returned. If ``False`` (default), a new :py:class:`~PIL.Image.Image` object is returned with the transform applied. :param flags: Integer (0-...) specifying additional flags :returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on the value of ``inPlace`` :exception PyCMSError: """ if outputMode is None: outputMode = im.mode if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3): msg = "renderingIntent must be an integer between 0 and 3" raise PyCMSError(msg) if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG): msg = f"flags must be an integer between 0 and {_MAX_FLAG}" raise PyCMSError(msg) try: if not isinstance(inputProfile, ImageCmsProfile): inputProfile = ImageCmsProfile(inputProfile) if not isinstance(outputProfile, ImageCmsProfile): outputProfile = ImageCmsProfile(outputProfile) transform = ImageCmsTransform( inputProfile, outputProfile, im.mode, outputMode, renderingIntent, flags=flags, ) if inPlace: transform.apply_in_place(im) imOut = None else: imOut = transform.apply(im) except (OSError, TypeError, ValueError) as v: raise PyCMSError(v) from v return imOut
(pyCMS) Applies an ICC transformation to a given image, mapping from ``inputProfile`` to ``outputProfile``. If the input or output profiles specified are not valid filenames, a :exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and ``outputMode != im.mode``, a :exc:`PyCMSError` will be raised. If an error occurs during application of the profiles, a :exc:`PyCMSError` will be raised. If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS), a :exc:`PyCMSError` will be raised. This function applies an ICC transformation to im from ``inputProfile``'s color space to ``outputProfile``'s color space using the specified rendering intent to decide how to handle out-of-gamut colors. ``outputMode`` can be used to specify that a color mode conversion is to be done using these profiles, but the specified profiles must be able to handle that mode. I.e., if converting im from RGB to CMYK using profiles, the input profile must handle RGB data, and the output profile must handle CMYK data. :param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...) or Image.open(...), etc.) :param inputProfile: String, as a valid filename path to the ICC input profile you wish to use for this image, or a profile object :param outputProfile: String, as a valid filename path to the ICC output profile you wish to use for this image, or a profile object :param renderingIntent: Integer (0-3) specifying the rendering intent you wish to use for the transform ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :param outputMode: A valid PIL mode for the output image (i.e. "RGB", "CMYK", etc.). Note: if rendering the image "inPlace", outputMode MUST be the same mode as the input, or omitted completely. If omitted, the outputMode will be the same as the mode of the input image (im.mode) :param inPlace: Boolean. If ``True``, the original image is modified in-place, and ``None`` is returned. If ``False`` (default), a new :py:class:`~PIL.Image.Image` object is returned with the transform applied. :param flags: Integer (0-...) specifying additional flags :returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on the value of ``inPlace`` :exception PyCMSError:
174,050
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate class ImageCmsProfile: def __init__(self, profile): """ :param profile: Either a string representing a filename, a file like object containing a profile or a low-level profile object """ if isinstance(profile, str): if sys.platform == "win32": profile_bytes_path = profile.encode() try: profile_bytes_path.decode("ascii") except UnicodeDecodeError: with open(profile, "rb") as f: self._set(core.profile_frombytes(f.read())) return self._set(core.profile_open(profile), profile) elif hasattr(profile, "read"): self._set(core.profile_frombytes(profile.read())) elif isinstance(profile, _imagingcms.CmsProfile): self._set(profile) else: msg = "Invalid type for Profile" raise TypeError(msg) def _set(self, profile, filename=None): self.profile = profile self.filename = filename if profile: self.product_name = None # profile.product_name self.product_info = None # profile.product_info else: self.product_name = None self.product_info = None def tobytes(self): """ Returns the profile in a format suitable for embedding in saved images. :returns: a bytes object containing the ICC profile. """ return core.profile_tobytes(self.profile) class PyCMSError(Exception): """(pyCMS) Exception class. This is used for all errors in the pyCMS API.""" pass The provided code snippet includes necessary dependencies for implementing the `getOpenProfile` function. Write a Python function `def getOpenProfile(profileFilename)` to solve the following problem: (pyCMS) Opens an ICC profile file. The PyCMSProfile object can be passed back into pyCMS for use in creating transforms and such (as in ImageCms.buildTransformFromOpenProfiles()). If ``profileFilename`` is not a valid filename for an ICC profile, a :exc:`PyCMSError` will be raised. :param profileFilename: String, as a valid filename path to the ICC profile you wish to open, or a file-like object. :returns: A CmsProfile class object. :exception PyCMSError: Here is the function: def getOpenProfile(profileFilename): """ (pyCMS) Opens an ICC profile file. The PyCMSProfile object can be passed back into pyCMS for use in creating transforms and such (as in ImageCms.buildTransformFromOpenProfiles()). If ``profileFilename`` is not a valid filename for an ICC profile, a :exc:`PyCMSError` will be raised. :param profileFilename: String, as a valid filename path to the ICC profile you wish to open, or a file-like object. :returns: A CmsProfile class object. :exception PyCMSError: """ try: return ImageCmsProfile(profileFilename) except (OSError, TypeError, ValueError) as v: raise PyCMSError(v) from v
(pyCMS) Opens an ICC profile file. The PyCMSProfile object can be passed back into pyCMS for use in creating transforms and such (as in ImageCms.buildTransformFromOpenProfiles()). If ``profileFilename`` is not a valid filename for an ICC profile, a :exc:`PyCMSError` will be raised. :param profileFilename: String, as a valid filename path to the ICC profile you wish to open, or a file-like object. :returns: A CmsProfile class object. :exception PyCMSError:
174,051
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate class Intent(IntEnum): PERCEPTUAL = 0 RELATIVE_COLORIMETRIC = 1 SATURATION = 2 ABSOLUTE_COLORIMETRIC = 3 _MAX_FLAG = 0 class ImageCmsProfile: def __init__(self, profile): """ :param profile: Either a string representing a filename, a file like object containing a profile or a low-level profile object """ if isinstance(profile, str): if sys.platform == "win32": profile_bytes_path = profile.encode() try: profile_bytes_path.decode("ascii") except UnicodeDecodeError: with open(profile, "rb") as f: self._set(core.profile_frombytes(f.read())) return self._set(core.profile_open(profile), profile) elif hasattr(profile, "read"): self._set(core.profile_frombytes(profile.read())) elif isinstance(profile, _imagingcms.CmsProfile): self._set(profile) else: msg = "Invalid type for Profile" raise TypeError(msg) def _set(self, profile, filename=None): self.profile = profile self.filename = filename if profile: self.product_name = None # profile.product_name self.product_info = None # profile.product_info else: self.product_name = None self.product_info = None def tobytes(self): """ Returns the profile in a format suitable for embedding in saved images. :returns: a bytes object containing the ICC profile. """ return core.profile_tobytes(self.profile) class ImageCmsTransform(Image.ImagePointHandler): """ Transform. This can be used with the procedural API, or with the standard :py:func:`~PIL.Image.Image.point` method. Will return the output profile in the ``output.info['icc_profile']``. """ def __init__( self, input, output, input_mode, output_mode, intent=Intent.PERCEPTUAL, proof=None, proof_intent=Intent.ABSOLUTE_COLORIMETRIC, flags=0, ): if proof is None: self.transform = core.buildTransform( input.profile, output.profile, input_mode, output_mode, intent, flags ) else: self.transform = core.buildProofTransform( input.profile, output.profile, proof.profile, input_mode, output_mode, intent, proof_intent, flags, ) # Note: inputMode and outputMode are for pyCMS compatibility only self.input_mode = self.inputMode = input_mode self.output_mode = self.outputMode = output_mode self.output_profile = output def point(self, im): return self.apply(im) def apply(self, im, imOut=None): im.load() if imOut is None: imOut = Image.new(self.output_mode, im.size, None) self.transform.apply(im.im.id, imOut.im.id) imOut.info["icc_profile"] = self.output_profile.tobytes() return imOut def apply_in_place(self, im): im.load() if im.mode != self.output_mode: msg = "mode mismatch" raise ValueError(msg) # wrong output mode self.transform.apply(im.im.id, im.im.id) im.info["icc_profile"] = self.output_profile.tobytes() return im class PyCMSError(Exception): """(pyCMS) Exception class. This is used for all errors in the pyCMS API.""" pass The provided code snippet includes necessary dependencies for implementing the `buildTransform` function. Write a Python function `def buildTransform( inputProfile, outputProfile, inMode, outMode, renderingIntent=Intent.PERCEPTUAL, flags=0, )` to solve the following problem: (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the ``outputProfile``. Use applyTransform to apply the transform to a given image. If the input or output profiles specified are not valid filenames, a :exc:`PyCMSError` will be raised. If an error occurs during creation of the transform, a :exc:`PyCMSError` will be raised. If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile`` (or by pyCMS), a :exc:`PyCMSError` will be raised. This function builds and returns an ICC transform from the ``inputProfile`` to the ``outputProfile`` using the ``renderingIntent`` to determine what to do with out-of-gamut colors. It will ONLY work for converting images that are in ``inMode`` to images that are in ``outMode`` color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.). Building the transform is a fair part of the overhead in ImageCms.profileToProfile(), so if you're planning on converting multiple images using the same input/output settings, this can save you time. Once you have a transform object, it can be used with ImageCms.applyProfile() to convert images without the need to re-compute the lookup table for the transform. The reason pyCMS returns a class object rather than a handle directly to the transform is that it needs to keep track of the PIL input/output modes that the transform is meant for. These attributes are stored in the ``inMode`` and ``outMode`` attributes of the object (which can be manually overridden if you really want to, but I don't know of any time that would be of use, or would even work). :param inputProfile: String, as a valid filename path to the ICC input profile you wish to use for this transform, or a profile object :param outputProfile: String, as a valid filename path to the ICC output profile you wish to use for this transform, or a profile object :param inMode: String, as a valid PIL mode that the appropriate profile also supports (i.e. "RGB", "RGBA", "CMYK", etc.) :param outMode: String, as a valid PIL mode that the appropriate profile also supports (i.e. "RGB", "RGBA", "CMYK", etc.) :param renderingIntent: Integer (0-3) specifying the rendering intent you wish to use for the transform ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :param flags: Integer (0-...) specifying additional flags :returns: A CmsTransform class object. :exception PyCMSError: Here is the function: def buildTransform( inputProfile, outputProfile, inMode, outMode, renderingIntent=Intent.PERCEPTUAL, flags=0, ): """ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the ``outputProfile``. Use applyTransform to apply the transform to a given image. If the input or output profiles specified are not valid filenames, a :exc:`PyCMSError` will be raised. If an error occurs during creation of the transform, a :exc:`PyCMSError` will be raised. If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile`` (or by pyCMS), a :exc:`PyCMSError` will be raised. This function builds and returns an ICC transform from the ``inputProfile`` to the ``outputProfile`` using the ``renderingIntent`` to determine what to do with out-of-gamut colors. It will ONLY work for converting images that are in ``inMode`` to images that are in ``outMode`` color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.). Building the transform is a fair part of the overhead in ImageCms.profileToProfile(), so if you're planning on converting multiple images using the same input/output settings, this can save you time. Once you have a transform object, it can be used with ImageCms.applyProfile() to convert images without the need to re-compute the lookup table for the transform. The reason pyCMS returns a class object rather than a handle directly to the transform is that it needs to keep track of the PIL input/output modes that the transform is meant for. These attributes are stored in the ``inMode`` and ``outMode`` attributes of the object (which can be manually overridden if you really want to, but I don't know of any time that would be of use, or would even work). :param inputProfile: String, as a valid filename path to the ICC input profile you wish to use for this transform, or a profile object :param outputProfile: String, as a valid filename path to the ICC output profile you wish to use for this transform, or a profile object :param inMode: String, as a valid PIL mode that the appropriate profile also supports (i.e. "RGB", "RGBA", "CMYK", etc.) :param outMode: String, as a valid PIL mode that the appropriate profile also supports (i.e. "RGB", "RGBA", "CMYK", etc.) :param renderingIntent: Integer (0-3) specifying the rendering intent you wish to use for the transform ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :param flags: Integer (0-...) specifying additional flags :returns: A CmsTransform class object. :exception PyCMSError: """ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3): msg = "renderingIntent must be an integer between 0 and 3" raise PyCMSError(msg) if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG): msg = "flags must be an integer between 0 and %s" + _MAX_FLAG raise PyCMSError(msg) try: if not isinstance(inputProfile, ImageCmsProfile): inputProfile = ImageCmsProfile(inputProfile) if not isinstance(outputProfile, ImageCmsProfile): outputProfile = ImageCmsProfile(outputProfile) return ImageCmsTransform( inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags ) except (OSError, TypeError, ValueError) as v: raise PyCMSError(v) from v
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the ``outputProfile``. Use applyTransform to apply the transform to a given image. If the input or output profiles specified are not valid filenames, a :exc:`PyCMSError` will be raised. If an error occurs during creation of the transform, a :exc:`PyCMSError` will be raised. If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile`` (or by pyCMS), a :exc:`PyCMSError` will be raised. This function builds and returns an ICC transform from the ``inputProfile`` to the ``outputProfile`` using the ``renderingIntent`` to determine what to do with out-of-gamut colors. It will ONLY work for converting images that are in ``inMode`` to images that are in ``outMode`` color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.). Building the transform is a fair part of the overhead in ImageCms.profileToProfile(), so if you're planning on converting multiple images using the same input/output settings, this can save you time. Once you have a transform object, it can be used with ImageCms.applyProfile() to convert images without the need to re-compute the lookup table for the transform. The reason pyCMS returns a class object rather than a handle directly to the transform is that it needs to keep track of the PIL input/output modes that the transform is meant for. These attributes are stored in the ``inMode`` and ``outMode`` attributes of the object (which can be manually overridden if you really want to, but I don't know of any time that would be of use, or would even work). :param inputProfile: String, as a valid filename path to the ICC input profile you wish to use for this transform, or a profile object :param outputProfile: String, as a valid filename path to the ICC output profile you wish to use for this transform, or a profile object :param inMode: String, as a valid PIL mode that the appropriate profile also supports (i.e. "RGB", "RGBA", "CMYK", etc.) :param outMode: String, as a valid PIL mode that the appropriate profile also supports (i.e. "RGB", "RGBA", "CMYK", etc.) :param renderingIntent: Integer (0-3) specifying the rendering intent you wish to use for the transform ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :param flags: Integer (0-...) specifying additional flags :returns: A CmsTransform class object. :exception PyCMSError:
174,052
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate class Intent(IntEnum): PERCEPTUAL = 0 RELATIVE_COLORIMETRIC = 1 SATURATION = 2 ABSOLUTE_COLORIMETRIC = 3 FLAGS = { "MATRIXINPUT": 1, "MATRIXOUTPUT": 2, "MATRIXONLY": (1 | 2), "NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot # Don't create prelinearization tables on precalculated transforms # (internal use): "NOPRELINEARIZATION": 16, "GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink) "NOTCACHE": 64, # Inhibit 1-pixel cache "NOTPRECALC": 256, "NULLTRANSFORM": 512, # Don't transform anyway "HIGHRESPRECALC": 1024, # Use more memory to give better accuracy "LOWRESPRECALC": 2048, # Use less memory to minimize resources "WHITEBLACKCOMPENSATION": 8192, "BLACKPOINTCOMPENSATION": 8192, "GAMUTCHECK": 4096, # Out of Gamut alarm "SOFTPROOFING": 16384, # Do softproofing "PRESERVEBLACK": 32768, # Black preservation "NODEFAULTRESOURCEDEF": 16777216, # CRD special "GRIDPOINTS": lambda n: (n & 0xFF) << 16, # Gridpoints } _MAX_FLAG = 0 class ImageCmsProfile: def __init__(self, profile): """ :param profile: Either a string representing a filename, a file like object containing a profile or a low-level profile object """ if isinstance(profile, str): if sys.platform == "win32": profile_bytes_path = profile.encode() try: profile_bytes_path.decode("ascii") except UnicodeDecodeError: with open(profile, "rb") as f: self._set(core.profile_frombytes(f.read())) return self._set(core.profile_open(profile), profile) elif hasattr(profile, "read"): self._set(core.profile_frombytes(profile.read())) elif isinstance(profile, _imagingcms.CmsProfile): self._set(profile) else: msg = "Invalid type for Profile" raise TypeError(msg) def _set(self, profile, filename=None): self.profile = profile self.filename = filename if profile: self.product_name = None # profile.product_name self.product_info = None # profile.product_info else: self.product_name = None self.product_info = None def tobytes(self): """ Returns the profile in a format suitable for embedding in saved images. :returns: a bytes object containing the ICC profile. """ return core.profile_tobytes(self.profile) class ImageCmsTransform(Image.ImagePointHandler): """ Transform. This can be used with the procedural API, or with the standard :py:func:`~PIL.Image.Image.point` method. Will return the output profile in the ``output.info['icc_profile']``. """ def __init__( self, input, output, input_mode, output_mode, intent=Intent.PERCEPTUAL, proof=None, proof_intent=Intent.ABSOLUTE_COLORIMETRIC, flags=0, ): if proof is None: self.transform = core.buildTransform( input.profile, output.profile, input_mode, output_mode, intent, flags ) else: self.transform = core.buildProofTransform( input.profile, output.profile, proof.profile, input_mode, output_mode, intent, proof_intent, flags, ) # Note: inputMode and outputMode are for pyCMS compatibility only self.input_mode = self.inputMode = input_mode self.output_mode = self.outputMode = output_mode self.output_profile = output def point(self, im): return self.apply(im) def apply(self, im, imOut=None): im.load() if imOut is None: imOut = Image.new(self.output_mode, im.size, None) self.transform.apply(im.im.id, imOut.im.id) imOut.info["icc_profile"] = self.output_profile.tobytes() return imOut def apply_in_place(self, im): im.load() if im.mode != self.output_mode: msg = "mode mismatch" raise ValueError(msg) # wrong output mode self.transform.apply(im.im.id, im.im.id) im.info["icc_profile"] = self.output_profile.tobytes() return im class PyCMSError(Exception): """(pyCMS) Exception class. This is used for all errors in the pyCMS API.""" pass The provided code snippet includes necessary dependencies for implementing the `buildProofTransform` function. Write a Python function `def buildProofTransform( inputProfile, outputProfile, proofProfile, inMode, outMode, renderingIntent=Intent.PERCEPTUAL, proofRenderingIntent=Intent.ABSOLUTE_COLORIMETRIC, flags=FLAGS["SOFTPROOFING"], )` to solve the following problem: (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the ``outputProfile``, but tries to simulate the result that would be obtained on the ``proofProfile`` device. If the input, output, or proof profiles specified are not valid filenames, a :exc:`PyCMSError` will be raised. If an error occurs during creation of the transform, a :exc:`PyCMSError` will be raised. If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile`` (or by pyCMS), a :exc:`PyCMSError` will be raised. This function builds and returns an ICC transform from the ``inputProfile`` to the ``outputProfile``, but tries to simulate the result that would be obtained on the ``proofProfile`` device using ``renderingIntent`` and ``proofRenderingIntent`` to determine what to do with out-of-gamut colors. This is known as "soft-proofing". It will ONLY work for converting images that are in ``inMode`` to images that are in outMode color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.). Usage of the resulting transform object is exactly the same as with ImageCms.buildTransform(). Proof profiling is generally used when using an output device to get a good idea of what the final printed/displayed image would look like on the ``proofProfile`` device when it's quicker and easier to use the output device for judging color. Generally, this means that the output device is a monitor, or a dye-sub printer (etc.), and the simulated device is something more expensive, complicated, or time consuming (making it difficult to make a real print for color judgement purposes). Soft-proofing basically functions by adjusting the colors on the output device to match the colors of the device being simulated. However, when the simulated device has a much wider gamut than the output device, you may obtain marginal results. :param inputProfile: String, as a valid filename path to the ICC input profile you wish to use for this transform, or a profile object :param outputProfile: String, as a valid filename path to the ICC output (monitor, usually) profile you wish to use for this transform, or a profile object :param proofProfile: String, as a valid filename path to the ICC proof profile you wish to use for this transform, or a profile object :param inMode: String, as a valid PIL mode that the appropriate profile also supports (i.e. "RGB", "RGBA", "CMYK", etc.) :param outMode: String, as a valid PIL mode that the appropriate profile also supports (i.e. "RGB", "RGBA", "CMYK", etc.) :param renderingIntent: Integer (0-3) specifying the rendering intent you wish to use for the input->proof (simulated) transform ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :param proofRenderingIntent: Integer (0-3) specifying the rendering intent you wish to use for proof->output transform ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :param flags: Integer (0-...) specifying additional flags :returns: A CmsTransform class object. :exception PyCMSError: Here is the function: def buildProofTransform( inputProfile, outputProfile, proofProfile, inMode, outMode, renderingIntent=Intent.PERCEPTUAL, proofRenderingIntent=Intent.ABSOLUTE_COLORIMETRIC, flags=FLAGS["SOFTPROOFING"], ): """ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the ``outputProfile``, but tries to simulate the result that would be obtained on the ``proofProfile`` device. If the input, output, or proof profiles specified are not valid filenames, a :exc:`PyCMSError` will be raised. If an error occurs during creation of the transform, a :exc:`PyCMSError` will be raised. If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile`` (or by pyCMS), a :exc:`PyCMSError` will be raised. This function builds and returns an ICC transform from the ``inputProfile`` to the ``outputProfile``, but tries to simulate the result that would be obtained on the ``proofProfile`` device using ``renderingIntent`` and ``proofRenderingIntent`` to determine what to do with out-of-gamut colors. This is known as "soft-proofing". It will ONLY work for converting images that are in ``inMode`` to images that are in outMode color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.). Usage of the resulting transform object is exactly the same as with ImageCms.buildTransform(). Proof profiling is generally used when using an output device to get a good idea of what the final printed/displayed image would look like on the ``proofProfile`` device when it's quicker and easier to use the output device for judging color. Generally, this means that the output device is a monitor, or a dye-sub printer (etc.), and the simulated device is something more expensive, complicated, or time consuming (making it difficult to make a real print for color judgement purposes). Soft-proofing basically functions by adjusting the colors on the output device to match the colors of the device being simulated. However, when the simulated device has a much wider gamut than the output device, you may obtain marginal results. :param inputProfile: String, as a valid filename path to the ICC input profile you wish to use for this transform, or a profile object :param outputProfile: String, as a valid filename path to the ICC output (monitor, usually) profile you wish to use for this transform, or a profile object :param proofProfile: String, as a valid filename path to the ICC proof profile you wish to use for this transform, or a profile object :param inMode: String, as a valid PIL mode that the appropriate profile also supports (i.e. "RGB", "RGBA", "CMYK", etc.) :param outMode: String, as a valid PIL mode that the appropriate profile also supports (i.e. "RGB", "RGBA", "CMYK", etc.) :param renderingIntent: Integer (0-3) specifying the rendering intent you wish to use for the input->proof (simulated) transform ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :param proofRenderingIntent: Integer (0-3) specifying the rendering intent you wish to use for proof->output transform ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :param flags: Integer (0-...) specifying additional flags :returns: A CmsTransform class object. :exception PyCMSError: """ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3): msg = "renderingIntent must be an integer between 0 and 3" raise PyCMSError(msg) if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG): msg = "flags must be an integer between 0 and %s" + _MAX_FLAG raise PyCMSError(msg) try: if not isinstance(inputProfile, ImageCmsProfile): inputProfile = ImageCmsProfile(inputProfile) if not isinstance(outputProfile, ImageCmsProfile): outputProfile = ImageCmsProfile(outputProfile) if not isinstance(proofProfile, ImageCmsProfile): proofProfile = ImageCmsProfile(proofProfile) return ImageCmsTransform( inputProfile, outputProfile, inMode, outMode, renderingIntent, proofProfile, proofRenderingIntent, flags, ) except (OSError, TypeError, ValueError) as v: raise PyCMSError(v) from v
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the ``outputProfile``, but tries to simulate the result that would be obtained on the ``proofProfile`` device. If the input, output, or proof profiles specified are not valid filenames, a :exc:`PyCMSError` will be raised. If an error occurs during creation of the transform, a :exc:`PyCMSError` will be raised. If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile`` (or by pyCMS), a :exc:`PyCMSError` will be raised. This function builds and returns an ICC transform from the ``inputProfile`` to the ``outputProfile``, but tries to simulate the result that would be obtained on the ``proofProfile`` device using ``renderingIntent`` and ``proofRenderingIntent`` to determine what to do with out-of-gamut colors. This is known as "soft-proofing". It will ONLY work for converting images that are in ``inMode`` to images that are in outMode color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.). Usage of the resulting transform object is exactly the same as with ImageCms.buildTransform(). Proof profiling is generally used when using an output device to get a good idea of what the final printed/displayed image would look like on the ``proofProfile`` device when it's quicker and easier to use the output device for judging color. Generally, this means that the output device is a monitor, or a dye-sub printer (etc.), and the simulated device is something more expensive, complicated, or time consuming (making it difficult to make a real print for color judgement purposes). Soft-proofing basically functions by adjusting the colors on the output device to match the colors of the device being simulated. However, when the simulated device has a much wider gamut than the output device, you may obtain marginal results. :param inputProfile: String, as a valid filename path to the ICC input profile you wish to use for this transform, or a profile object :param outputProfile: String, as a valid filename path to the ICC output (monitor, usually) profile you wish to use for this transform, or a profile object :param proofProfile: String, as a valid filename path to the ICC proof profile you wish to use for this transform, or a profile object :param inMode: String, as a valid PIL mode that the appropriate profile also supports (i.e. "RGB", "RGBA", "CMYK", etc.) :param outMode: String, as a valid PIL mode that the appropriate profile also supports (i.e. "RGB", "RGBA", "CMYK", etc.) :param renderingIntent: Integer (0-3) specifying the rendering intent you wish to use for the input->proof (simulated) transform ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :param proofRenderingIntent: Integer (0-3) specifying the rendering intent you wish to use for proof->output transform ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :param flags: Integer (0-...) specifying additional flags :returns: A CmsTransform class object. :exception PyCMSError:
174,053
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate class PyCMSError(Exception): """(pyCMS) Exception class. This is used for all errors in the pyCMS API.""" pass The provided code snippet includes necessary dependencies for implementing the `applyTransform` function. Write a Python function `def applyTransform(im, transform, inPlace=False)` to solve the following problem: (pyCMS) Applies a transform to a given image. If ``im.mode != transform.inMode``, a :exc:`PyCMSError` is raised. If ``inPlace`` is ``True`` and ``transform.inMode != transform.outMode``, a :exc:`PyCMSError` is raised. If ``im.mode``, ``transform.inMode`` or ``transform.outMode`` is not supported by pyCMSdll or the profiles you used for the transform, a :exc:`PyCMSError` is raised. If an error occurs while the transform is being applied, a :exc:`PyCMSError` is raised. This function applies a pre-calculated transform (from ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles()) to an image. The transform can be used for multiple images, saving considerable calculation time if doing the same conversion multiple times. If you want to modify im in-place instead of receiving a new image as the return value, set ``inPlace`` to ``True``. This can only be done if ``transform.inMode`` and ``transform.outMode`` are the same, because we can't change the mode in-place (the buffer sizes for some modes are different). The default behavior is to return a new :py:class:`~PIL.Image.Image` object of the same dimensions in mode ``transform.outMode``. :param im: An :py:class:`~PIL.Image.Image` object, and im.mode must be the same as the ``inMode`` supported by the transform. :param transform: A valid CmsTransform class object :param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the transform applied is returned (and ``im`` is not changed). The default is ``False``. :returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object, depending on the value of ``inPlace``. The profile will be returned in the image's ``info['icc_profile']``. :exception PyCMSError: Here is the function: def applyTransform(im, transform, inPlace=False): """ (pyCMS) Applies a transform to a given image. If ``im.mode != transform.inMode``, a :exc:`PyCMSError` is raised. If ``inPlace`` is ``True`` and ``transform.inMode != transform.outMode``, a :exc:`PyCMSError` is raised. If ``im.mode``, ``transform.inMode`` or ``transform.outMode`` is not supported by pyCMSdll or the profiles you used for the transform, a :exc:`PyCMSError` is raised. If an error occurs while the transform is being applied, a :exc:`PyCMSError` is raised. This function applies a pre-calculated transform (from ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles()) to an image. The transform can be used for multiple images, saving considerable calculation time if doing the same conversion multiple times. If you want to modify im in-place instead of receiving a new image as the return value, set ``inPlace`` to ``True``. This can only be done if ``transform.inMode`` and ``transform.outMode`` are the same, because we can't change the mode in-place (the buffer sizes for some modes are different). The default behavior is to return a new :py:class:`~PIL.Image.Image` object of the same dimensions in mode ``transform.outMode``. :param im: An :py:class:`~PIL.Image.Image` object, and im.mode must be the same as the ``inMode`` supported by the transform. :param transform: A valid CmsTransform class object :param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the transform applied is returned (and ``im`` is not changed). The default is ``False``. :returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object, depending on the value of ``inPlace``. The profile will be returned in the image's ``info['icc_profile']``. :exception PyCMSError: """ try: if inPlace: transform.apply_in_place(im) imOut = None else: imOut = transform.apply(im) except (TypeError, ValueError) as v: raise PyCMSError(v) from v return imOut
(pyCMS) Applies a transform to a given image. If ``im.mode != transform.inMode``, a :exc:`PyCMSError` is raised. If ``inPlace`` is ``True`` and ``transform.inMode != transform.outMode``, a :exc:`PyCMSError` is raised. If ``im.mode``, ``transform.inMode`` or ``transform.outMode`` is not supported by pyCMSdll or the profiles you used for the transform, a :exc:`PyCMSError` is raised. If an error occurs while the transform is being applied, a :exc:`PyCMSError` is raised. This function applies a pre-calculated transform (from ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles()) to an image. The transform can be used for multiple images, saving considerable calculation time if doing the same conversion multiple times. If you want to modify im in-place instead of receiving a new image as the return value, set ``inPlace`` to ``True``. This can only be done if ``transform.inMode`` and ``transform.outMode`` are the same, because we can't change the mode in-place (the buffer sizes for some modes are different). The default behavior is to return a new :py:class:`~PIL.Image.Image` object of the same dimensions in mode ``transform.outMode``. :param im: An :py:class:`~PIL.Image.Image` object, and im.mode must be the same as the ``inMode`` supported by the transform. :param transform: A valid CmsTransform class object :param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the transform applied is returned (and ``im`` is not changed). The default is ``False``. :returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object, depending on the value of ``inPlace``. The profile will be returned in the image's ``info['icc_profile']``. :exception PyCMSError:
174,054
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate core = _imagingcms class PyCMSError(Exception): """(pyCMS) Exception class. This is used for all errors in the pyCMS API.""" pass The provided code snippet includes necessary dependencies for implementing the `createProfile` function. Write a Python function `def createProfile(colorSpace, colorTemp=-1)` to solve the following problem: (pyCMS) Creates a profile. If colorSpace not in ``["LAB", "XYZ", "sRGB"]``, a :exc:`PyCMSError` is raised. If using LAB and ``colorTemp`` is not a positive integer, a :exc:`PyCMSError` is raised. If an error occurs while creating the profile, a :exc:`PyCMSError` is raised. Use this function to create common profiles on-the-fly instead of having to supply a profile on disk and knowing the path to it. It returns a normal CmsProfile object that can be passed to ImageCms.buildTransformFromOpenProfiles() to create a transform to apply to images. :param colorSpace: String, the color space of the profile you wish to create. Currently only "LAB", "XYZ", and "sRGB" are supported. :param colorTemp: Positive integer for the white point for the profile, in degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50 illuminant if omitted (5000k). colorTemp is ONLY applied to LAB profiles, and is ignored for XYZ and sRGB. :returns: A CmsProfile class object :exception PyCMSError: Here is the function: def createProfile(colorSpace, colorTemp=-1): """ (pyCMS) Creates a profile. If colorSpace not in ``["LAB", "XYZ", "sRGB"]``, a :exc:`PyCMSError` is raised. If using LAB and ``colorTemp`` is not a positive integer, a :exc:`PyCMSError` is raised. If an error occurs while creating the profile, a :exc:`PyCMSError` is raised. Use this function to create common profiles on-the-fly instead of having to supply a profile on disk and knowing the path to it. It returns a normal CmsProfile object that can be passed to ImageCms.buildTransformFromOpenProfiles() to create a transform to apply to images. :param colorSpace: String, the color space of the profile you wish to create. Currently only "LAB", "XYZ", and "sRGB" are supported. :param colorTemp: Positive integer for the white point for the profile, in degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50 illuminant if omitted (5000k). colorTemp is ONLY applied to LAB profiles, and is ignored for XYZ and sRGB. :returns: A CmsProfile class object :exception PyCMSError: """ if colorSpace not in ["LAB", "XYZ", "sRGB"]: msg = ( f"Color space not supported for on-the-fly profile creation ({colorSpace})" ) raise PyCMSError(msg) if colorSpace == "LAB": try: colorTemp = float(colorTemp) except (TypeError, ValueError) as e: msg = f'Color temperature must be numeric, "{colorTemp}" not valid' raise PyCMSError(msg) from e try: return core.createProfile(colorSpace, colorTemp) except (TypeError, ValueError) as v: raise PyCMSError(v) from v
(pyCMS) Creates a profile. If colorSpace not in ``["LAB", "XYZ", "sRGB"]``, a :exc:`PyCMSError` is raised. If using LAB and ``colorTemp`` is not a positive integer, a :exc:`PyCMSError` is raised. If an error occurs while creating the profile, a :exc:`PyCMSError` is raised. Use this function to create common profiles on-the-fly instead of having to supply a profile on disk and knowing the path to it. It returns a normal CmsProfile object that can be passed to ImageCms.buildTransformFromOpenProfiles() to create a transform to apply to images. :param colorSpace: String, the color space of the profile you wish to create. Currently only "LAB", "XYZ", and "sRGB" are supported. :param colorTemp: Positive integer for the white point for the profile, in degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50 illuminant if omitted (5000k). colorTemp is ONLY applied to LAB profiles, and is ignored for XYZ and sRGB. :returns: A CmsProfile class object :exception PyCMSError:
174,055
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate class ImageCmsProfile: def __init__(self, profile): """ :param profile: Either a string representing a filename, a file like object containing a profile or a low-level profile object """ if isinstance(profile, str): if sys.platform == "win32": profile_bytes_path = profile.encode() try: profile_bytes_path.decode("ascii") except UnicodeDecodeError: with open(profile, "rb") as f: self._set(core.profile_frombytes(f.read())) return self._set(core.profile_open(profile), profile) elif hasattr(profile, "read"): self._set(core.profile_frombytes(profile.read())) elif isinstance(profile, _imagingcms.CmsProfile): self._set(profile) else: msg = "Invalid type for Profile" raise TypeError(msg) def _set(self, profile, filename=None): self.profile = profile self.filename = filename if profile: self.product_name = None # profile.product_name self.product_info = None # profile.product_info else: self.product_name = None self.product_info = None def tobytes(self): """ Returns the profile in a format suitable for embedding in saved images. :returns: a bytes object containing the ICC profile. """ return core.profile_tobytes(self.profile) class PyCMSError(Exception): """(pyCMS) Exception class. This is used for all errors in the pyCMS API.""" pass The provided code snippet includes necessary dependencies for implementing the `getProfileName` function. Write a Python function `def getProfileName(profile)` to solve the following problem: (pyCMS) Gets the internal product name for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised If an error occurs while trying to obtain the name tag, a :exc:`PyCMSError` is raised. Use this function to obtain the INTERNAL name of the profile (stored in an ICC tag in the profile itself), usually the one used when the profile was originally created. Sometimes this tag also contains additional information supplied by the creator. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal name of the profile as stored in an ICC tag. :exception PyCMSError: Here is the function: def getProfileName(profile): """ (pyCMS) Gets the internal product name for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised If an error occurs while trying to obtain the name tag, a :exc:`PyCMSError` is raised. Use this function to obtain the INTERNAL name of the profile (stored in an ICC tag in the profile itself), usually the one used when the profile was originally created. Sometimes this tag also contains additional information supplied by the creator. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal name of the profile as stored in an ICC tag. :exception PyCMSError: """ try: # add an extra newline to preserve pyCMS compatibility if not isinstance(profile, ImageCmsProfile): profile = ImageCmsProfile(profile) # do it in python, not c. # // name was "%s - %s" (model, manufacturer) || Description , # // but if the Model and Manufacturer were the same or the model # // was long, Just the model, in 1.x model = profile.profile.model manufacturer = profile.profile.manufacturer if not (model or manufacturer): return (profile.profile.profile_description or "") + "\n" if not manufacturer or len(model) > 30: return model + "\n" return f"{model} - {manufacturer}\n" except (AttributeError, OSError, TypeError, ValueError) as v: raise PyCMSError(v) from v
(pyCMS) Gets the internal product name for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised If an error occurs while trying to obtain the name tag, a :exc:`PyCMSError` is raised. Use this function to obtain the INTERNAL name of the profile (stored in an ICC tag in the profile itself), usually the one used when the profile was originally created. Sometimes this tag also contains additional information supplied by the creator. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal name of the profile as stored in an ICC tag. :exception PyCMSError:
174,056
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate class ImageCmsProfile: def __init__(self, profile): """ :param profile: Either a string representing a filename, a file like object containing a profile or a low-level profile object """ if isinstance(profile, str): if sys.platform == "win32": profile_bytes_path = profile.encode() try: profile_bytes_path.decode("ascii") except UnicodeDecodeError: with open(profile, "rb") as f: self._set(core.profile_frombytes(f.read())) return self._set(core.profile_open(profile), profile) elif hasattr(profile, "read"): self._set(core.profile_frombytes(profile.read())) elif isinstance(profile, _imagingcms.CmsProfile): self._set(profile) else: msg = "Invalid type for Profile" raise TypeError(msg) def _set(self, profile, filename=None): self.profile = profile self.filename = filename if profile: self.product_name = None # profile.product_name self.product_info = None # profile.product_info else: self.product_name = None self.product_info = None def tobytes(self): """ Returns the profile in a format suitable for embedding in saved images. :returns: a bytes object containing the ICC profile. """ return core.profile_tobytes(self.profile) class PyCMSError(Exception): """(pyCMS) Exception class. This is used for all errors in the pyCMS API.""" pass The provided code snippet includes necessary dependencies for implementing the `getProfileInfo` function. Write a Python function `def getProfileInfo(profile)` to solve the following problem: (pyCMS) Gets the internal product information for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the info tag, a :exc:`PyCMSError` is raised. Use this function to obtain the information stored in the profile's info tag. This often contains details about the profile, and how it was created, as supplied by the creator. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal profile information stored in an ICC tag. :exception PyCMSError: Here is the function: def getProfileInfo(profile): """ (pyCMS) Gets the internal product information for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the info tag, a :exc:`PyCMSError` is raised. Use this function to obtain the information stored in the profile's info tag. This often contains details about the profile, and how it was created, as supplied by the creator. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal profile information stored in an ICC tag. :exception PyCMSError: """ try: if not isinstance(profile, ImageCmsProfile): profile = ImageCmsProfile(profile) # add an extra newline to preserve pyCMS compatibility # Python, not C. the white point bits weren't working well, # so skipping. # info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint description = profile.profile.profile_description cpright = profile.profile.copyright arr = [] for elt in (description, cpright): if elt: arr.append(elt) return "\r\n\r\n".join(arr) + "\r\n\r\n" except (AttributeError, OSError, TypeError, ValueError) as v: raise PyCMSError(v) from v
(pyCMS) Gets the internal product information for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the info tag, a :exc:`PyCMSError` is raised. Use this function to obtain the information stored in the profile's info tag. This often contains details about the profile, and how it was created, as supplied by the creator. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal profile information stored in an ICC tag. :exception PyCMSError:
174,057
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate class ImageCmsProfile: def __init__(self, profile): """ :param profile: Either a string representing a filename, a file like object containing a profile or a low-level profile object """ if isinstance(profile, str): if sys.platform == "win32": profile_bytes_path = profile.encode() try: profile_bytes_path.decode("ascii") except UnicodeDecodeError: with open(profile, "rb") as f: self._set(core.profile_frombytes(f.read())) return self._set(core.profile_open(profile), profile) elif hasattr(profile, "read"): self._set(core.profile_frombytes(profile.read())) elif isinstance(profile, _imagingcms.CmsProfile): self._set(profile) else: msg = "Invalid type for Profile" raise TypeError(msg) def _set(self, profile, filename=None): self.profile = profile self.filename = filename if profile: self.product_name = None # profile.product_name self.product_info = None # profile.product_info else: self.product_name = None self.product_info = None def tobytes(self): """ Returns the profile in a format suitable for embedding in saved images. :returns: a bytes object containing the ICC profile. """ return core.profile_tobytes(self.profile) class PyCMSError(Exception): """(pyCMS) Exception class. This is used for all errors in the pyCMS API.""" pass The provided code snippet includes necessary dependencies for implementing the `getProfileCopyright` function. Write a Python function `def getProfileCopyright(profile)` to solve the following problem: (pyCMS) Gets the copyright for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the copyright tag, a :exc:`PyCMSError` is raised. Use this function to obtain the information stored in the profile's copyright tag. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal profile information stored in an ICC tag. :exception PyCMSError: Here is the function: def getProfileCopyright(profile): """ (pyCMS) Gets the copyright for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the copyright tag, a :exc:`PyCMSError` is raised. Use this function to obtain the information stored in the profile's copyright tag. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal profile information stored in an ICC tag. :exception PyCMSError: """ try: # add an extra newline to preserve pyCMS compatibility if not isinstance(profile, ImageCmsProfile): profile = ImageCmsProfile(profile) return (profile.profile.copyright or "") + "\n" except (AttributeError, OSError, TypeError, ValueError) as v: raise PyCMSError(v) from v
(pyCMS) Gets the copyright for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the copyright tag, a :exc:`PyCMSError` is raised. Use this function to obtain the information stored in the profile's copyright tag. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal profile information stored in an ICC tag. :exception PyCMSError:
174,058
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate class ImageCmsProfile: def __init__(self, profile): """ :param profile: Either a string representing a filename, a file like object containing a profile or a low-level profile object """ if isinstance(profile, str): if sys.platform == "win32": profile_bytes_path = profile.encode() try: profile_bytes_path.decode("ascii") except UnicodeDecodeError: with open(profile, "rb") as f: self._set(core.profile_frombytes(f.read())) return self._set(core.profile_open(profile), profile) elif hasattr(profile, "read"): self._set(core.profile_frombytes(profile.read())) elif isinstance(profile, _imagingcms.CmsProfile): self._set(profile) else: msg = "Invalid type for Profile" raise TypeError(msg) def _set(self, profile, filename=None): self.profile = profile self.filename = filename if profile: self.product_name = None # profile.product_name self.product_info = None # profile.product_info else: self.product_name = None self.product_info = None def tobytes(self): """ Returns the profile in a format suitable for embedding in saved images. :returns: a bytes object containing the ICC profile. """ return core.profile_tobytes(self.profile) class PyCMSError(Exception): """(pyCMS) Exception class. This is used for all errors in the pyCMS API.""" pass The provided code snippet includes necessary dependencies for implementing the `getProfileManufacturer` function. Write a Python function `def getProfileManufacturer(profile)` to solve the following problem: (pyCMS) Gets the manufacturer for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the manufacturer tag, a :exc:`PyCMSError` is raised. Use this function to obtain the information stored in the profile's manufacturer tag. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal profile information stored in an ICC tag. :exception PyCMSError: Here is the function: def getProfileManufacturer(profile): """ (pyCMS) Gets the manufacturer for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the manufacturer tag, a :exc:`PyCMSError` is raised. Use this function to obtain the information stored in the profile's manufacturer tag. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal profile information stored in an ICC tag. :exception PyCMSError: """ try: # add an extra newline to preserve pyCMS compatibility if not isinstance(profile, ImageCmsProfile): profile = ImageCmsProfile(profile) return (profile.profile.manufacturer or "") + "\n" except (AttributeError, OSError, TypeError, ValueError) as v: raise PyCMSError(v) from v
(pyCMS) Gets the manufacturer for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the manufacturer tag, a :exc:`PyCMSError` is raised. Use this function to obtain the information stored in the profile's manufacturer tag. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal profile information stored in an ICC tag. :exception PyCMSError:
174,059
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate class ImageCmsProfile: def __init__(self, profile): """ :param profile: Either a string representing a filename, a file like object containing a profile or a low-level profile object """ if isinstance(profile, str): if sys.platform == "win32": profile_bytes_path = profile.encode() try: profile_bytes_path.decode("ascii") except UnicodeDecodeError: with open(profile, "rb") as f: self._set(core.profile_frombytes(f.read())) return self._set(core.profile_open(profile), profile) elif hasattr(profile, "read"): self._set(core.profile_frombytes(profile.read())) elif isinstance(profile, _imagingcms.CmsProfile): self._set(profile) else: msg = "Invalid type for Profile" raise TypeError(msg) def _set(self, profile, filename=None): self.profile = profile self.filename = filename if profile: self.product_name = None # profile.product_name self.product_info = None # profile.product_info else: self.product_name = None self.product_info = None def tobytes(self): """ Returns the profile in a format suitable for embedding in saved images. :returns: a bytes object containing the ICC profile. """ return core.profile_tobytes(self.profile) class PyCMSError(Exception): """(pyCMS) Exception class. This is used for all errors in the pyCMS API.""" pass The provided code snippet includes necessary dependencies for implementing the `getProfileModel` function. Write a Python function `def getProfileModel(profile)` to solve the following problem: (pyCMS) Gets the model for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the model tag, a :exc:`PyCMSError` is raised. Use this function to obtain the information stored in the profile's model tag. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal profile information stored in an ICC tag. :exception PyCMSError: Here is the function: def getProfileModel(profile): """ (pyCMS) Gets the model for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the model tag, a :exc:`PyCMSError` is raised. Use this function to obtain the information stored in the profile's model tag. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal profile information stored in an ICC tag. :exception PyCMSError: """ try: # add an extra newline to preserve pyCMS compatibility if not isinstance(profile, ImageCmsProfile): profile = ImageCmsProfile(profile) return (profile.profile.model or "") + "\n" except (AttributeError, OSError, TypeError, ValueError) as v: raise PyCMSError(v) from v
(pyCMS) Gets the model for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the model tag, a :exc:`PyCMSError` is raised. Use this function to obtain the information stored in the profile's model tag. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal profile information stored in an ICC tag. :exception PyCMSError:
174,060
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate class ImageCmsProfile: def __init__(self, profile): """ :param profile: Either a string representing a filename, a file like object containing a profile or a low-level profile object """ if isinstance(profile, str): if sys.platform == "win32": profile_bytes_path = profile.encode() try: profile_bytes_path.decode("ascii") except UnicodeDecodeError: with open(profile, "rb") as f: self._set(core.profile_frombytes(f.read())) return self._set(core.profile_open(profile), profile) elif hasattr(profile, "read"): self._set(core.profile_frombytes(profile.read())) elif isinstance(profile, _imagingcms.CmsProfile): self._set(profile) else: msg = "Invalid type for Profile" raise TypeError(msg) def _set(self, profile, filename=None): self.profile = profile self.filename = filename if profile: self.product_name = None # profile.product_name self.product_info = None # profile.product_info else: self.product_name = None self.product_info = None def tobytes(self): """ Returns the profile in a format suitable for embedding in saved images. :returns: a bytes object containing the ICC profile. """ return core.profile_tobytes(self.profile) class PyCMSError(Exception): """(pyCMS) Exception class. This is used for all errors in the pyCMS API.""" pass The provided code snippet includes necessary dependencies for implementing the `getProfileDescription` function. Write a Python function `def getProfileDescription(profile)` to solve the following problem: (pyCMS) Gets the description for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the description tag, a :exc:`PyCMSError` is raised. Use this function to obtain the information stored in the profile's description tag. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal profile information stored in an ICC tag. :exception PyCMSError: Here is the function: def getProfileDescription(profile): """ (pyCMS) Gets the description for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the description tag, a :exc:`PyCMSError` is raised. Use this function to obtain the information stored in the profile's description tag. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal profile information stored in an ICC tag. :exception PyCMSError: """ try: # add an extra newline to preserve pyCMS compatibility if not isinstance(profile, ImageCmsProfile): profile = ImageCmsProfile(profile) return (profile.profile.profile_description or "") + "\n" except (AttributeError, OSError, TypeError, ValueError) as v: raise PyCMSError(v) from v
(pyCMS) Gets the description for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the description tag, a :exc:`PyCMSError` is raised. Use this function to obtain the information stored in the profile's description tag. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: A string containing the internal profile information stored in an ICC tag. :exception PyCMSError:
174,061
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate class ImageCmsProfile: def __init__(self, profile): """ :param profile: Either a string representing a filename, a file like object containing a profile or a low-level profile object """ if isinstance(profile, str): if sys.platform == "win32": profile_bytes_path = profile.encode() try: profile_bytes_path.decode("ascii") except UnicodeDecodeError: with open(profile, "rb") as f: self._set(core.profile_frombytes(f.read())) return self._set(core.profile_open(profile), profile) elif hasattr(profile, "read"): self._set(core.profile_frombytes(profile.read())) elif isinstance(profile, _imagingcms.CmsProfile): self._set(profile) else: msg = "Invalid type for Profile" raise TypeError(msg) def _set(self, profile, filename=None): self.profile = profile self.filename = filename if profile: self.product_name = None # profile.product_name self.product_info = None # profile.product_info else: self.product_name = None self.product_info = None def tobytes(self): """ Returns the profile in a format suitable for embedding in saved images. :returns: a bytes object containing the ICC profile. """ return core.profile_tobytes(self.profile) class PyCMSError(Exception): """(pyCMS) Exception class. This is used for all errors in the pyCMS API.""" pass The provided code snippet includes necessary dependencies for implementing the `getDefaultIntent` function. Write a Python function `def getDefaultIntent(profile)` to solve the following problem: (pyCMS) Gets the default intent name for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the default intent, a :exc:`PyCMSError` is raised. Use this function to determine the default (and usually best optimized) rendering intent for this profile. Most profiles support multiple rendering intents, but are intended mostly for one type of conversion. If you wish to use a different intent than returned, use ImageCms.isIntentSupported() to verify it will work first. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: Integer 0-3 specifying the default rendering intent for this profile. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :exception PyCMSError: Here is the function: def getDefaultIntent(profile): """ (pyCMS) Gets the default intent name for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the default intent, a :exc:`PyCMSError` is raised. Use this function to determine the default (and usually best optimized) rendering intent for this profile. Most profiles support multiple rendering intents, but are intended mostly for one type of conversion. If you wish to use a different intent than returned, use ImageCms.isIntentSupported() to verify it will work first. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: Integer 0-3 specifying the default rendering intent for this profile. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :exception PyCMSError: """ try: if not isinstance(profile, ImageCmsProfile): profile = ImageCmsProfile(profile) return profile.profile.rendering_intent except (AttributeError, OSError, TypeError, ValueError) as v: raise PyCMSError(v) from v
(pyCMS) Gets the default intent name for the given profile. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a :exc:`PyCMSError` is raised. If an error occurs while trying to obtain the default intent, a :exc:`PyCMSError` is raised. Use this function to determine the default (and usually best optimized) rendering intent for this profile. Most profiles support multiple rendering intents, but are intended mostly for one type of conversion. If you wish to use a different intent than returned, use ImageCms.isIntentSupported() to verify it will work first. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :returns: Integer 0-3 specifying the default rendering intent for this profile. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :exception PyCMSError:
174,062
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate class ImageCmsProfile: def __init__(self, profile): """ :param profile: Either a string representing a filename, a file like object containing a profile or a low-level profile object """ if isinstance(profile, str): if sys.platform == "win32": profile_bytes_path = profile.encode() try: profile_bytes_path.decode("ascii") except UnicodeDecodeError: with open(profile, "rb") as f: self._set(core.profile_frombytes(f.read())) return self._set(core.profile_open(profile), profile) elif hasattr(profile, "read"): self._set(core.profile_frombytes(profile.read())) elif isinstance(profile, _imagingcms.CmsProfile): self._set(profile) else: msg = "Invalid type for Profile" raise TypeError(msg) def _set(self, profile, filename=None): self.profile = profile self.filename = filename if profile: self.product_name = None # profile.product_name self.product_info = None # profile.product_info else: self.product_name = None self.product_info = None def tobytes(self): """ Returns the profile in a format suitable for embedding in saved images. :returns: a bytes object containing the ICC profile. """ return core.profile_tobytes(self.profile) class PyCMSError(Exception): """(pyCMS) Exception class. This is used for all errors in the pyCMS API.""" pass The provided code snippet includes necessary dependencies for implementing the `isIntentSupported` function. Write a Python function `def isIntentSupported(profile, intent, direction)` to solve the following problem: (pyCMS) Checks if a given intent is supported. Use this function to verify that you can use your desired ``intent`` with ``profile``, and that ``profile`` can be used for the input/output/proof profile as you desire. Some profiles are created specifically for one "direction", can cannot be used for others. Some profiles can only be used for certain rendering intents, so it's best to either verify this before trying to create a transform with them (using this function), or catch the potential :exc:`PyCMSError` that will occur if they don't support the modes you select. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :param intent: Integer (0-3) specifying the rendering intent you wish to use with this profile ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :param direction: Integer specifying if the profile is to be used for input, output, or proof INPUT = 0 (or use ImageCms.Direction.INPUT) OUTPUT = 1 (or use ImageCms.Direction.OUTPUT) PROOF = 2 (or use ImageCms.Direction.PROOF) :returns: 1 if the intent/direction are supported, -1 if they are not. :exception PyCMSError: Here is the function: def isIntentSupported(profile, intent, direction): """ (pyCMS) Checks if a given intent is supported. Use this function to verify that you can use your desired ``intent`` with ``profile``, and that ``profile`` can be used for the input/output/proof profile as you desire. Some profiles are created specifically for one "direction", can cannot be used for others. Some profiles can only be used for certain rendering intents, so it's best to either verify this before trying to create a transform with them (using this function), or catch the potential :exc:`PyCMSError` that will occur if they don't support the modes you select. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :param intent: Integer (0-3) specifying the rendering intent you wish to use with this profile ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :param direction: Integer specifying if the profile is to be used for input, output, or proof INPUT = 0 (or use ImageCms.Direction.INPUT) OUTPUT = 1 (or use ImageCms.Direction.OUTPUT) PROOF = 2 (or use ImageCms.Direction.PROOF) :returns: 1 if the intent/direction are supported, -1 if they are not. :exception PyCMSError: """ try: if not isinstance(profile, ImageCmsProfile): profile = ImageCmsProfile(profile) # FIXME: I get different results for the same data w. different # compilers. Bug in LittleCMS or in the binding? if profile.profile.is_intent_supported(intent, direction): return 1 else: return -1 except (AttributeError, OSError, TypeError, ValueError) as v: raise PyCMSError(v) from v
(pyCMS) Checks if a given intent is supported. Use this function to verify that you can use your desired ``intent`` with ``profile``, and that ``profile`` can be used for the input/output/proof profile as you desire. Some profiles are created specifically for one "direction", can cannot be used for others. Some profiles can only be used for certain rendering intents, so it's best to either verify this before trying to create a transform with them (using this function), or catch the potential :exc:`PyCMSError` that will occur if they don't support the modes you select. :param profile: EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. :param intent: Integer (0-3) specifying the rendering intent you wish to use with this profile ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 ImageCms.Intent.SATURATION = 2 ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 see the pyCMS documentation for details on rendering intents and what they do. :param direction: Integer specifying if the profile is to be used for input, output, or proof INPUT = 0 (or use ImageCms.Direction.INPUT) OUTPUT = 1 (or use ImageCms.Direction.OUTPUT) PROOF = 2 (or use ImageCms.Direction.PROOF) :returns: 1 if the intent/direction are supported, -1 if they are not. :exception PyCMSError:
174,063
import sys from enum import IntEnum from PIL import Image from ._deprecate import deprecate VERSION = "1.0.0 pil" core = _imagingcms class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": deprecate("Image categories", 10, "is_animated", plural=True) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None def close(self): """ Closes the file pointer, if possible. This operation will destroy the image core and release its memory. The image data will be unusable afterward. This function is required to close images that have multiple frames or have not had their file read and closed by the :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for more information. """ try: if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = DeferredError(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_pretty_(self, p, cycle): """IPython plain text display support""" # Same as __repr__ but without unpredictable id(self), # to keep Jupyter notebook `text/plain` output stable. p.text( "<%s.%s image mode=%s size=%dx%d>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], ) ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: msg = "Could not save to PNG for display" raise ValueError(msg) from e return b.getvalue() def __array_interface__(self): # numpy array interface support new = {"version": 3} try: if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() except Exception as e: if not isinstance(e, (MemoryError, RecursionError)): try: import numpy from packaging.version import parse as parse_version except ImportError: pass else: if parse_version(numpy.__version__) < parse_version("1.23"): warnings.warn(e) raise new["shape"], new["typestr"] = _conv_type_shape(self) return new def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. A list of C encoders can be seen under codecs section of the function array in :file:`_imaging.c`. Python encoders are registered within the relevant plugins. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() if self.width == 0 or self.height == 0: return b"" # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c output = [] while True: bytes_consumed, errcode, data = e.encode(bufsize) output.append(data) if errcode: break if errcode < 0: msg = f"encoder error {errcode} in tobytes" raise RuntimeError(msg) return b"".join(output) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": msg = "not a bitmap" raise ValueError(msg) data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: msg = "not enough image data" raise ValueError(msg) if s[1] != 0: msg = "cannot decode image data" raise ValueError(msg) def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im is not None and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: palette_mode = "RGBA" if mode.startswith("RGBA") else "RGB" self.palette.mode = palette_mode self.palette.palette = self.im.getpalette(palette_mode, palette_mode) if self.im is not None: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK". The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is ``None``, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. When converting from "PA", if an "RGBA" palette is present, the alpha channel from the image will be used instead of the values from the palette. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`Palette.WEB` or :data:`Palette.ADAPTIVE`. :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): msg = "illegal conversion" raise ValueError(msg) im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if (self.mode in ("1", "L", "I") and mode in ("LA", "RGBA")) or ( self.mode == "RGB" and mode == "RGBA" ): # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: msg = "Transparency for P mode should be bytes or int" raise ValueError(msg) if mode == "P" and palette == Palette.ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new if "LAB" in (self.mode, mode): other_mode = mode if self.mode == "LAB" else self.mode if other_mode in ("RGB", "RGBA", "RGBX"): from . import ImageCms srgb = ImageCms.createProfile("sRGB") lab = ImageCms.createProfile("LAB") profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab] transform = ImageCms.buildTransform( profiles[0], profiles[1], self.mode, mode ) return transform.apply(self) # colorspace conversion if dither is None: dither = Dither.FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again modebase = getmodebase(self.mode) if modebase == self.mode: raise im = self.im.convert(modebase) im = im.convert(mode, dither) except KeyError as e: msg = "illegal conversion" raise ValueError(msg) from e new_im = self._new(im) if mode == "P" and palette != Palette.ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`Quantize.MEDIANCUT` (median cut), :data:`Quantize.MAXCOVERAGE` (maximum coverage), :data:`Quantize.FASTOCTREE` (fast octree), :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`Quantize.MEDIANCUT` will be used. The exception to this is RGBA images. :data:`Quantize.MEDIANCUT` and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so :data:`Quantize.FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). :returns: A new image """ self.load() if method is None: # defaults: method = Quantize.MEDIANCUT if self.mode == "RGBA": method = Quantize.FASTOCTREE if self.mode == "RGBA" and method not in ( Quantize.FASTOCTREE, Quantize.LIBIMAGEQUANT, ): # Caller specified an invalid mode. msg = ( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) raise ValueError(msg) if palette: # use palette from reference image palette.load() if palette.mode != "P": msg = "bad mode for palette image" raise ValueError(msg) if self.mode != "RGB" and self.mode != "L": msg = "only RGB or L mode images can be quantized to a palette" raise ValueError(msg) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() if box[2] < box[0]: msg = "Coordinate 'right' is less than 'left'" raise ValueError(msg) elif box[3] < box[1]: msg = "Coordinate 'lower' is less than 'upper'" raise ValueError(msg) self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size in pixels, as a 2-tuple: (width, height). """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): msg = "filter argument should be ImageFilter.Filter instance or class" raise TypeError(msg) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): """ Gets EXIF data from the image. :returns: an :py:class:`~PIL.Image.Exif` object. """ if self._exif is None: self._exif = Exif() self._exif._loaded = False elif self._exif._loaded: return self._exif self._exif._loaded = True exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.bigtiff = self.tag_v2._bigtiff self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation(="|>)([0-9])', xmp_tags) if match: self._exif[0x0112] = int(match[2]) return self._exif def _reload_exif(self): if self._exif is None or not self._exif._loaded: return self._exif._loaded = False self.getexif() def get_child_images(self): child_images = [] exif = self.getexif() ifds = [] if ExifTags.Base.SubIFDs in exif: subifd_offsets = exif[ExifTags.Base.SubIFDs] if subifd_offsets: if not isinstance(subifd_offsets, tuple): subifd_offsets = (subifd_offsets,) for subifd_offset in subifd_offsets: ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset)) ifd1 = exif.get_ifd(ExifTags.IFD.IFD1) if ifd1 and ifd1.get(513): ifds.append((ifd1, exif._info.next)) offset = None for ifd, ifd_offset in ifds: current_offset = self.fp.tell() if offset is None: offset = current_offset fp = self.fp thumbnail_offset = ifd.get(513) if thumbnail_offset is not None: try: thumbnail_offset += self._exif_offset except AttributeError: pass self.fp.seek(thumbnail_offset) data = self.fp.read(ifd.get(514)) fp = io.BytesIO(data) with open(fp) as im: if thumbnail_offset is None: im._frame_pos = [ifd_offset] im._seek(0) im.load() child_images.append(im) if offset is not None: self.fp.seek(offset) return child_images def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self, rawmode="RGB"): """ Returns the image palette as a list. :param rawmode: The mode in which to return the palette. ``None`` will return the palette in its current mode. .. versionadded:: 9.1.0 :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: mode = self.im.getpalettemode() except ValueError: return None # no palette if rawmode is None: rawmode = mode return list(self.im.getpalette(mode, rawmode)) def apply_transparency(self): """ If a P mode image has a "transparency" key in the info dictionary, remove the key and instead apply the transparency to the palette. Otherwise, the image is unchanged. """ if self.mode != "P" or "transparency" not in self.info: return from . import ImagePalette palette = self.getpalette("RGBA") transparency = self.info["transparency"] if isinstance(transparency, bytes): for i, alpha in enumerate(transparency): palette[i * 4 + 3] = alpha else: palette[transparency * 4 + 3] = 0 self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette)) self.palette.dirty = 1 del self.info["transparency"] def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. Counts are grouped into 256 bins for each band, even if the image has more than 8 bits per band. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", "LA", "RGBA" or "RGBa" images (if present, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? msg = "cannot determine region size; use 4-item box" raise ValueError(msg) box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): msg = "Source must be a tuple" raise ValueError(msg) if not isinstance(dest, (list, tuple)): msg = "Destination must be a tuple" raise ValueError(msg) if not len(source) in (2, 4): msg = "Source must be a 2 or 4-tuple" raise ValueError(msg) if not len(dest) == 2: msg = "Destination must be a 2-tuple" raise ValueError(msg) if min(source) < 0: msg = "Source must be non-negative" raise ValueError(msg) if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case msg = "point operation not supported for this mode" raise ValueError(msg) if mode != "F": lut = [round(i) for i in lut] return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: msg = "illegal image mode" raise ValueError(msg) from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): msg = "illegal image mode" raise ValueError(msg) alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): msg = "illegal image mode" raise ValueError(msg) if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P and PA images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode in ("P", "PA") and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P or PA image if self.mode == "PA": alpha = value[3] if len(value) == 4 else 255 value = value[:3] value = self.palette.getcolor(value, self) if self.mode == "PA": value = (value, alpha) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): msg = "illegal image mode" raise ValueError(msg) bands = 3 palette_mode = "RGB" if source_palette is None: if self.mode == "P": self.load() palette_mode = self.im.getpalettemode() if palette_mode == "RGBA": bands = 4 source_palette = self.im.getpalette(palette_mode, palette_mode) else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[ oldPosition * bands : oldPosition * bands + bands ] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette( palette_mode, palette=mapping_palette * bands ) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette(palette_mode + ";L", m_im.palette.tobytes()) m_im = m_im.convert("L") m_im.putpalette(palette_bytes, palette_mode) m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes) if "transparency" in self.info: try: m_im.info["transparency"] = dest_map.index(self.info["transparency"]) except ValueError: if "transparency" in m_im.info: del m_im.info["transparency"] return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`Resampling.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`Resampling.NEAREST`. Otherwise, the default filter is :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = Resampling.NEAREST if type_special else Resampling.BICUBIC elif resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, Resampling.LANCZOS, Resampling.BOX, Resampling.HAMMING, ): msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), (Resampling.BOX, "Image.Resampling.BOX"), (Resampling.HAMMING, "Image.Resampling.HAMMING"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) if reducing_gap is not None and reducing_gap < 1.0: msg = "reducing_gap must be 1.0 or greater" raise ValueError(msg) size = tuple(size) self.load() if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = Resampling.NEAREST if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != Resampling.NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(Transpose.ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose( Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270 ) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform( (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor ) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif is_path(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and is_path(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: msg = f"unknown file extension: {ext}" raise ValueError(msg) from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] created = False if open_fp: created = not os.path.exists(filename) if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) except Exception: if open_fp: fp.close() if created: try: os.remove(filename) except PermissionError: pass raise if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: msg = f'The image has no channel "{channel}"' raise ValueError(msg) from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: Optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If omitted, it defaults to :py:data:`Resampling.BICUBIC`. (was :py:data:`Resampling.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ provided_size = tuple(map(math.floor, size)) def preserve_aspect_ratio(): def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) x, y = provided_size if x >= self.width and y >= self.height: return aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) return x, y box = None if reducing_gap is not None: size = preserve_aspect_ratio() if size is None: return res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if box is None: self.load() # load() may have changed the size of the image size = preserve_aspect_ratio() if size is None: return if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size in pixels, as a 2-tuple: (width, height). :param method: The transformation method. This is one of :py:data:`Transform.EXTENT` (cut out a rectangular subregion), :py:data:`Transform.AFFINE` (affine transform), :py:data:`Transform.PERSPECTIVE` (perspective transform), :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or :py:data:`Transform.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.Transform.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: msg = "missing method data" raise ValueError(msg) im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == Transform.MESH: # list of quads for box, quad in data: im.__transformer( box, self, Transform.QUAD, quad, resample, fillcolor is None ) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): w = box[2] - box[0] h = box[3] - box[1] if method == Transform.AFFINE: data = data[:6] elif method == Transform.EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = Transform.AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == Transform.PERSPECTIVE: data = data[:8] elif method == Transform.QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: msg = "unknown transformation method" raise ValueError(msg) if resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, ): if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS): msg = { Resampling.BOX: "Image.Resampling.BOX", Resampling.HAMMING: "Image.Resampling.HAMMING", Resampling.LANCZOS: "Image.Resampling.LANCZOS", }[resample] + f" ({resample}) cannot be used." else: msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) image.load() self.load() if image.mode in ("1", "P"): resample = Resampling.NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`, :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`, :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`, :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `versions` function. Write a Python function `def versions()` to solve the following problem: (pyCMS) Fetches versions. Here is the function: def versions(): """ (pyCMS) Fetches versions. """ return VERSION, core.littlecms_version, sys.version.split()[0], Image.__version__
(pyCMS) Fetches versions.
174,064
import functools import operator import re from . import Image, ImagePalette def _lut(image, lut): if image.mode == "P": # FIXME: apply to lookup table, not image data msg = "mode P support coming soon" raise NotImplementedError(msg) elif image.mode in ("L", "RGB"): if image.mode == "RGB" and len(lut) == 256: lut = lut + lut + lut return image.point(lut) else: msg = "not supported for this image mode" raise OSError(msg) def scale(image, factor, resample=Image.Resampling.BICUBIC): """ Returns a rescaled image by a specific factor given in parameter. A factor greater than 1 expands the image, between 0 and 1 contracts the image. :param image: The image to rescale. :param factor: The expansion factor, as a float. :param resample: Resampling method to use. Default is :py:attr:`~PIL.Image.Resampling.BICUBIC`. See :ref:`concept-filters`. :returns: An :py:class:`~PIL.Image.Image` object. """ if factor == 1: return image.copy() elif factor <= 0: msg = "the factor must be greater than 0" raise ValueError(msg) else: size = (round(factor * image.width), round(factor * image.height)) return image.resize(size, resample) The provided code snippet includes necessary dependencies for implementing the `autocontrast` function. Write a Python function `def autocontrast(image, cutoff=0, ignore=None, mask=None, preserve_tone=False)` to solve the following problem: Maximize (normalize) image contrast. This function calculates a histogram of the input image (or mask region), removes ``cutoff`` percent of the lightest and darkest pixels from the histogram, and remaps the image so that the darkest pixel becomes black (0), and the lightest becomes white (255). :param image: The image to process. :param cutoff: The percent to cut off from the histogram on the low and high ends. Either a tuple of (low, high), or a single number for both. :param ignore: The background pixel value (use None for no background). :param mask: Histogram used in contrast operation is computed using pixels within the mask. If no mask is given the entire image is used for histogram computation. :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast. .. versionadded:: 8.2.0 :return: An image. Here is the function: def autocontrast(image, cutoff=0, ignore=None, mask=None, preserve_tone=False): """ Maximize (normalize) image contrast. This function calculates a histogram of the input image (or mask region), removes ``cutoff`` percent of the lightest and darkest pixels from the histogram, and remaps the image so that the darkest pixel becomes black (0), and the lightest becomes white (255). :param image: The image to process. :param cutoff: The percent to cut off from the histogram on the low and high ends. Either a tuple of (low, high), or a single number for both. :param ignore: The background pixel value (use None for no background). :param mask: Histogram used in contrast operation is computed using pixels within the mask. If no mask is given the entire image is used for histogram computation. :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast. .. versionadded:: 8.2.0 :return: An image. """ if preserve_tone: histogram = image.convert("L").histogram(mask) else: histogram = image.histogram(mask) lut = [] for layer in range(0, len(histogram), 256): h = histogram[layer : layer + 256] if ignore is not None: # get rid of outliers try: h[ignore] = 0 except TypeError: # assume sequence for ix in ignore: h[ix] = 0 if cutoff: # cut off pixels from both ends of the histogram if not isinstance(cutoff, tuple): cutoff = (cutoff, cutoff) # get number of pixels n = 0 for ix in range(256): n = n + h[ix] # remove cutoff% pixels from the low end cut = n * cutoff[0] // 100 for lo in range(256): if cut > h[lo]: cut = cut - h[lo] h[lo] = 0 else: h[lo] -= cut cut = 0 if cut <= 0: break # remove cutoff% samples from the high end cut = n * cutoff[1] // 100 for hi in range(255, -1, -1): if cut > h[hi]: cut = cut - h[hi] h[hi] = 0 else: h[hi] -= cut cut = 0 if cut <= 0: break # find lowest/highest samples after preprocessing for lo in range(256): if h[lo]: break for hi in range(255, -1, -1): if h[hi]: break if hi <= lo: # don't bother lut.extend(list(range(256))) else: scale = 255.0 / (hi - lo) offset = -lo * scale for ix in range(256): ix = int(ix * scale + offset) if ix < 0: ix = 0 elif ix > 255: ix = 255 lut.append(ix) return _lut(image, lut)
Maximize (normalize) image contrast. This function calculates a histogram of the input image (or mask region), removes ``cutoff`` percent of the lightest and darkest pixels from the histogram, and remaps the image so that the darkest pixel becomes black (0), and the lightest becomes white (255). :param image: The image to process. :param cutoff: The percent to cut off from the histogram on the low and high ends. Either a tuple of (low, high), or a single number for both. :param ignore: The background pixel value (use None for no background). :param mask: Histogram used in contrast operation is computed using pixels within the mask. If no mask is given the entire image is used for histogram computation. :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast. .. versionadded:: 8.2.0 :return: An image.
174,065
import functools import operator import re from . import Image, ImagePalette def _color(color, mode): if isinstance(color, str): from . import ImageColor color = ImageColor.getcolor(color, mode) return color def _lut(image, lut): if image.mode == "P": # FIXME: apply to lookup table, not image data msg = "mode P support coming soon" raise NotImplementedError(msg) elif image.mode in ("L", "RGB"): if image.mode == "RGB" and len(lut) == 256: lut = lut + lut + lut return image.point(lut) else: msg = "not supported for this image mode" raise OSError(msg) The provided code snippet includes necessary dependencies for implementing the `colorize` function. Write a Python function `def colorize(image, black, white, mid=None, blackpoint=0, whitepoint=255, midpoint=127)` to solve the following problem: Colorize grayscale image. This function calculates a color wedge which maps all black pixels in the source image to the first color and all white pixels to the second color. If ``mid`` is specified, it uses three-color mapping. The ``black`` and ``white`` arguments should be RGB tuples or color names; optionally you can use three-color mapping by also specifying ``mid``. Mapping positions for any of the colors can be specified (e.g. ``blackpoint``), where these parameters are the integer value corresponding to where the corresponding color should be mapped. These parameters must have logical order, such that ``blackpoint <= midpoint <= whitepoint`` (if ``mid`` is specified). :param image: The image to colorize. :param black: The color to use for black input pixels. :param white: The color to use for white input pixels. :param mid: The color to use for midtone input pixels. :param blackpoint: an int value [0, 255] for the black mapping. :param whitepoint: an int value [0, 255] for the white mapping. :param midpoint: an int value [0, 255] for the midtone mapping. :return: An image. Here is the function: def colorize(image, black, white, mid=None, blackpoint=0, whitepoint=255, midpoint=127): """ Colorize grayscale image. This function calculates a color wedge which maps all black pixels in the source image to the first color and all white pixels to the second color. If ``mid`` is specified, it uses three-color mapping. The ``black`` and ``white`` arguments should be RGB tuples or color names; optionally you can use three-color mapping by also specifying ``mid``. Mapping positions for any of the colors can be specified (e.g. ``blackpoint``), where these parameters are the integer value corresponding to where the corresponding color should be mapped. These parameters must have logical order, such that ``blackpoint <= midpoint <= whitepoint`` (if ``mid`` is specified). :param image: The image to colorize. :param black: The color to use for black input pixels. :param white: The color to use for white input pixels. :param mid: The color to use for midtone input pixels. :param blackpoint: an int value [0, 255] for the black mapping. :param whitepoint: an int value [0, 255] for the white mapping. :param midpoint: an int value [0, 255] for the midtone mapping. :return: An image. """ # Initial asserts assert image.mode == "L" if mid is None: assert 0 <= blackpoint <= whitepoint <= 255 else: assert 0 <= blackpoint <= midpoint <= whitepoint <= 255 # Define colors from arguments black = _color(black, "RGB") white = _color(white, "RGB") if mid is not None: mid = _color(mid, "RGB") # Empty lists for the mapping red = [] green = [] blue = [] # Create the low-end values for i in range(0, blackpoint): red.append(black[0]) green.append(black[1]) blue.append(black[2]) # Create the mapping (2-color) if mid is None: range_map = range(0, whitepoint - blackpoint) for i in range_map: red.append(black[0] + i * (white[0] - black[0]) // len(range_map)) green.append(black[1] + i * (white[1] - black[1]) // len(range_map)) blue.append(black[2] + i * (white[2] - black[2]) // len(range_map)) # Create the mapping (3-color) else: range_map1 = range(0, midpoint - blackpoint) range_map2 = range(0, whitepoint - midpoint) for i in range_map1: red.append(black[0] + i * (mid[0] - black[0]) // len(range_map1)) green.append(black[1] + i * (mid[1] - black[1]) // len(range_map1)) blue.append(black[2] + i * (mid[2] - black[2]) // len(range_map1)) for i in range_map2: red.append(mid[0] + i * (white[0] - mid[0]) // len(range_map2)) green.append(mid[1] + i * (white[1] - mid[1]) // len(range_map2)) blue.append(mid[2] + i * (white[2] - mid[2]) // len(range_map2)) # Create the high-end values for i in range(0, 256 - whitepoint): red.append(white[0]) green.append(white[1]) blue.append(white[2]) # Return converted image image = image.convert("RGB") return _lut(image, red + green + blue)
Colorize grayscale image. This function calculates a color wedge which maps all black pixels in the source image to the first color and all white pixels to the second color. If ``mid`` is specified, it uses three-color mapping. The ``black`` and ``white`` arguments should be RGB tuples or color names; optionally you can use three-color mapping by also specifying ``mid``. Mapping positions for any of the colors can be specified (e.g. ``blackpoint``), where these parameters are the integer value corresponding to where the corresponding color should be mapped. These parameters must have logical order, such that ``blackpoint <= midpoint <= whitepoint`` (if ``mid`` is specified). :param image: The image to colorize. :param black: The color to use for black input pixels. :param white: The color to use for white input pixels. :param mid: The color to use for midtone input pixels. :param blackpoint: an int value [0, 255] for the black mapping. :param whitepoint: an int value [0, 255] for the white mapping. :param midpoint: an int value [0, 255] for the midtone mapping. :return: An image.
174,066
import functools import operator import re from . import Image, ImagePalette def contain(image, size, method=Image.Resampling.BICUBIC): """ Returns a resized version of the image, set to the maximum width and height within the requested size, while maintaining the original aspect ratio. :param image: The image to resize and crop. :param size: The requested output size in pixels, given as a (width, height) tuple. :param method: Resampling method to use. Default is :py:attr:`~PIL.Image.Resampling.BICUBIC`. See :ref:`concept-filters`. :return: An image. """ im_ratio = image.width / image.height dest_ratio = size[0] / size[1] if im_ratio != dest_ratio: if im_ratio > dest_ratio: new_height = round(image.height / image.width * size[0]) if new_height != size[1]: size = (size[0], new_height) else: new_width = round(image.width / image.height * size[1]) if new_width != size[0]: size = (new_width, size[1]) return image.resize(size, resample=method) class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": deprecate("Image categories", 10, "is_animated", plural=True) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None def close(self): """ Closes the file pointer, if possible. This operation will destroy the image core and release its memory. The image data will be unusable afterward. This function is required to close images that have multiple frames or have not had their file read and closed by the :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for more information. """ try: if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = DeferredError(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_pretty_(self, p, cycle): """IPython plain text display support""" # Same as __repr__ but without unpredictable id(self), # to keep Jupyter notebook `text/plain` output stable. p.text( "<%s.%s image mode=%s size=%dx%d>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], ) ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: msg = "Could not save to PNG for display" raise ValueError(msg) from e return b.getvalue() def __array_interface__(self): # numpy array interface support new = {"version": 3} try: if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() except Exception as e: if not isinstance(e, (MemoryError, RecursionError)): try: import numpy from packaging.version import parse as parse_version except ImportError: pass else: if parse_version(numpy.__version__) < parse_version("1.23"): warnings.warn(e) raise new["shape"], new["typestr"] = _conv_type_shape(self) return new def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. A list of C encoders can be seen under codecs section of the function array in :file:`_imaging.c`. Python encoders are registered within the relevant plugins. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() if self.width == 0 or self.height == 0: return b"" # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c output = [] while True: bytes_consumed, errcode, data = e.encode(bufsize) output.append(data) if errcode: break if errcode < 0: msg = f"encoder error {errcode} in tobytes" raise RuntimeError(msg) return b"".join(output) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": msg = "not a bitmap" raise ValueError(msg) data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: msg = "not enough image data" raise ValueError(msg) if s[1] != 0: msg = "cannot decode image data" raise ValueError(msg) def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im is not None and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: palette_mode = "RGBA" if mode.startswith("RGBA") else "RGB" self.palette.mode = palette_mode self.palette.palette = self.im.getpalette(palette_mode, palette_mode) if self.im is not None: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK". The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is ``None``, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. When converting from "PA", if an "RGBA" palette is present, the alpha channel from the image will be used instead of the values from the palette. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`Palette.WEB` or :data:`Palette.ADAPTIVE`. :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): msg = "illegal conversion" raise ValueError(msg) im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if (self.mode in ("1", "L", "I") and mode in ("LA", "RGBA")) or ( self.mode == "RGB" and mode == "RGBA" ): # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: msg = "Transparency for P mode should be bytes or int" raise ValueError(msg) if mode == "P" and palette == Palette.ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new if "LAB" in (self.mode, mode): other_mode = mode if self.mode == "LAB" else self.mode if other_mode in ("RGB", "RGBA", "RGBX"): from . import ImageCms srgb = ImageCms.createProfile("sRGB") lab = ImageCms.createProfile("LAB") profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab] transform = ImageCms.buildTransform( profiles[0], profiles[1], self.mode, mode ) return transform.apply(self) # colorspace conversion if dither is None: dither = Dither.FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again modebase = getmodebase(self.mode) if modebase == self.mode: raise im = self.im.convert(modebase) im = im.convert(mode, dither) except KeyError as e: msg = "illegal conversion" raise ValueError(msg) from e new_im = self._new(im) if mode == "P" and palette != Palette.ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`Quantize.MEDIANCUT` (median cut), :data:`Quantize.MAXCOVERAGE` (maximum coverage), :data:`Quantize.FASTOCTREE` (fast octree), :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`Quantize.MEDIANCUT` will be used. The exception to this is RGBA images. :data:`Quantize.MEDIANCUT` and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so :data:`Quantize.FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). :returns: A new image """ self.load() if method is None: # defaults: method = Quantize.MEDIANCUT if self.mode == "RGBA": method = Quantize.FASTOCTREE if self.mode == "RGBA" and method not in ( Quantize.FASTOCTREE, Quantize.LIBIMAGEQUANT, ): # Caller specified an invalid mode. msg = ( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) raise ValueError(msg) if palette: # use palette from reference image palette.load() if palette.mode != "P": msg = "bad mode for palette image" raise ValueError(msg) if self.mode != "RGB" and self.mode != "L": msg = "only RGB or L mode images can be quantized to a palette" raise ValueError(msg) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() if box[2] < box[0]: msg = "Coordinate 'right' is less than 'left'" raise ValueError(msg) elif box[3] < box[1]: msg = "Coordinate 'lower' is less than 'upper'" raise ValueError(msg) self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size in pixels, as a 2-tuple: (width, height). """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): msg = "filter argument should be ImageFilter.Filter instance or class" raise TypeError(msg) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): """ Gets EXIF data from the image. :returns: an :py:class:`~PIL.Image.Exif` object. """ if self._exif is None: self._exif = Exif() self._exif._loaded = False elif self._exif._loaded: return self._exif self._exif._loaded = True exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.bigtiff = self.tag_v2._bigtiff self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation(="|>)([0-9])', xmp_tags) if match: self._exif[0x0112] = int(match[2]) return self._exif def _reload_exif(self): if self._exif is None or not self._exif._loaded: return self._exif._loaded = False self.getexif() def get_child_images(self): child_images = [] exif = self.getexif() ifds = [] if ExifTags.Base.SubIFDs in exif: subifd_offsets = exif[ExifTags.Base.SubIFDs] if subifd_offsets: if not isinstance(subifd_offsets, tuple): subifd_offsets = (subifd_offsets,) for subifd_offset in subifd_offsets: ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset)) ifd1 = exif.get_ifd(ExifTags.IFD.IFD1) if ifd1 and ifd1.get(513): ifds.append((ifd1, exif._info.next)) offset = None for ifd, ifd_offset in ifds: current_offset = self.fp.tell() if offset is None: offset = current_offset fp = self.fp thumbnail_offset = ifd.get(513) if thumbnail_offset is not None: try: thumbnail_offset += self._exif_offset except AttributeError: pass self.fp.seek(thumbnail_offset) data = self.fp.read(ifd.get(514)) fp = io.BytesIO(data) with open(fp) as im: if thumbnail_offset is None: im._frame_pos = [ifd_offset] im._seek(0) im.load() child_images.append(im) if offset is not None: self.fp.seek(offset) return child_images def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self, rawmode="RGB"): """ Returns the image palette as a list. :param rawmode: The mode in which to return the palette. ``None`` will return the palette in its current mode. .. versionadded:: 9.1.0 :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: mode = self.im.getpalettemode() except ValueError: return None # no palette if rawmode is None: rawmode = mode return list(self.im.getpalette(mode, rawmode)) def apply_transparency(self): """ If a P mode image has a "transparency" key in the info dictionary, remove the key and instead apply the transparency to the palette. Otherwise, the image is unchanged. """ if self.mode != "P" or "transparency" not in self.info: return from . import ImagePalette palette = self.getpalette("RGBA") transparency = self.info["transparency"] if isinstance(transparency, bytes): for i, alpha in enumerate(transparency): palette[i * 4 + 3] = alpha else: palette[transparency * 4 + 3] = 0 self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette)) self.palette.dirty = 1 del self.info["transparency"] def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. Counts are grouped into 256 bins for each band, even if the image has more than 8 bits per band. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", "LA", "RGBA" or "RGBa" images (if present, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? msg = "cannot determine region size; use 4-item box" raise ValueError(msg) box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): msg = "Source must be a tuple" raise ValueError(msg) if not isinstance(dest, (list, tuple)): msg = "Destination must be a tuple" raise ValueError(msg) if not len(source) in (2, 4): msg = "Source must be a 2 or 4-tuple" raise ValueError(msg) if not len(dest) == 2: msg = "Destination must be a 2-tuple" raise ValueError(msg) if min(source) < 0: msg = "Source must be non-negative" raise ValueError(msg) if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case msg = "point operation not supported for this mode" raise ValueError(msg) if mode != "F": lut = [round(i) for i in lut] return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: msg = "illegal image mode" raise ValueError(msg) from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): msg = "illegal image mode" raise ValueError(msg) alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): msg = "illegal image mode" raise ValueError(msg) if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P and PA images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode in ("P", "PA") and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P or PA image if self.mode == "PA": alpha = value[3] if len(value) == 4 else 255 value = value[:3] value = self.palette.getcolor(value, self) if self.mode == "PA": value = (value, alpha) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): msg = "illegal image mode" raise ValueError(msg) bands = 3 palette_mode = "RGB" if source_palette is None: if self.mode == "P": self.load() palette_mode = self.im.getpalettemode() if palette_mode == "RGBA": bands = 4 source_palette = self.im.getpalette(palette_mode, palette_mode) else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[ oldPosition * bands : oldPosition * bands + bands ] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette( palette_mode, palette=mapping_palette * bands ) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette(palette_mode + ";L", m_im.palette.tobytes()) m_im = m_im.convert("L") m_im.putpalette(palette_bytes, palette_mode) m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes) if "transparency" in self.info: try: m_im.info["transparency"] = dest_map.index(self.info["transparency"]) except ValueError: if "transparency" in m_im.info: del m_im.info["transparency"] return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`Resampling.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`Resampling.NEAREST`. Otherwise, the default filter is :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = Resampling.NEAREST if type_special else Resampling.BICUBIC elif resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, Resampling.LANCZOS, Resampling.BOX, Resampling.HAMMING, ): msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), (Resampling.BOX, "Image.Resampling.BOX"), (Resampling.HAMMING, "Image.Resampling.HAMMING"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) if reducing_gap is not None and reducing_gap < 1.0: msg = "reducing_gap must be 1.0 or greater" raise ValueError(msg) size = tuple(size) self.load() if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = Resampling.NEAREST if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != Resampling.NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(Transpose.ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose( Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270 ) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform( (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor ) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif is_path(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and is_path(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: msg = f"unknown file extension: {ext}" raise ValueError(msg) from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] created = False if open_fp: created = not os.path.exists(filename) if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) except Exception: if open_fp: fp.close() if created: try: os.remove(filename) except PermissionError: pass raise if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: msg = f'The image has no channel "{channel}"' raise ValueError(msg) from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: Optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If omitted, it defaults to :py:data:`Resampling.BICUBIC`. (was :py:data:`Resampling.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ provided_size = tuple(map(math.floor, size)) def preserve_aspect_ratio(): def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) x, y = provided_size if x >= self.width and y >= self.height: return aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) return x, y box = None if reducing_gap is not None: size = preserve_aspect_ratio() if size is None: return res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if box is None: self.load() # load() may have changed the size of the image size = preserve_aspect_ratio() if size is None: return if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size in pixels, as a 2-tuple: (width, height). :param method: The transformation method. This is one of :py:data:`Transform.EXTENT` (cut out a rectangular subregion), :py:data:`Transform.AFFINE` (affine transform), :py:data:`Transform.PERSPECTIVE` (perspective transform), :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or :py:data:`Transform.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.Transform.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: msg = "missing method data" raise ValueError(msg) im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == Transform.MESH: # list of quads for box, quad in data: im.__transformer( box, self, Transform.QUAD, quad, resample, fillcolor is None ) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): w = box[2] - box[0] h = box[3] - box[1] if method == Transform.AFFINE: data = data[:6] elif method == Transform.EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = Transform.AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == Transform.PERSPECTIVE: data = data[:8] elif method == Transform.QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: msg = "unknown transformation method" raise ValueError(msg) if resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, ): if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS): msg = { Resampling.BOX: "Image.Resampling.BOX", Resampling.HAMMING: "Image.Resampling.HAMMING", Resampling.LANCZOS: "Image.Resampling.LANCZOS", }[resample] + f" ({resample}) cannot be used." else: msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) image.load() self.load() if image.mode in ("1", "P"): resample = Resampling.NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`, :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`, :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`, :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `pad` function. Write a Python function `def pad(image, size, method=Image.Resampling.BICUBIC, color=None, centering=(0.5, 0.5))` to solve the following problem: Returns a resized and padded version of the image, expanded to fill the requested aspect ratio and size. :param image: The image to resize and crop. :param size: The requested output size in pixels, given as a (width, height) tuple. :param method: Resampling method to use. Default is :py:attr:`~PIL.Image.Resampling.BICUBIC`. See :ref:`concept-filters`. :param color: The background color of the padded image. :param centering: Control the position of the original image within the padded version. (0.5, 0.5) will keep the image centered (0, 0) will keep the image aligned to the top left (1, 1) will keep the image aligned to the bottom right :return: An image. Here is the function: def pad(image, size, method=Image.Resampling.BICUBIC, color=None, centering=(0.5, 0.5)): """ Returns a resized and padded version of the image, expanded to fill the requested aspect ratio and size. :param image: The image to resize and crop. :param size: The requested output size in pixels, given as a (width, height) tuple. :param method: Resampling method to use. Default is :py:attr:`~PIL.Image.Resampling.BICUBIC`. See :ref:`concept-filters`. :param color: The background color of the padded image. :param centering: Control the position of the original image within the padded version. (0.5, 0.5) will keep the image centered (0, 0) will keep the image aligned to the top left (1, 1) will keep the image aligned to the bottom right :return: An image. """ resized = contain(image, size, method) if resized.size == size: out = resized else: out = Image.new(image.mode, size, color) if resized.palette: out.putpalette(resized.getpalette()) if resized.width != size[0]: x = round((size[0] - resized.width) * max(0, min(centering[0], 1))) out.paste(resized, (x, 0)) else: y = round((size[1] - resized.height) * max(0, min(centering[1], 1))) out.paste(resized, (0, y)) return out
Returns a resized and padded version of the image, expanded to fill the requested aspect ratio and size. :param image: The image to resize and crop. :param size: The requested output size in pixels, given as a (width, height) tuple. :param method: Resampling method to use. Default is :py:attr:`~PIL.Image.Resampling.BICUBIC`. See :ref:`concept-filters`. :param color: The background color of the padded image. :param centering: Control the position of the original image within the padded version. (0.5, 0.5) will keep the image centered (0, 0) will keep the image aligned to the top left (1, 1) will keep the image aligned to the bottom right :return: An image.
174,067
import functools import operator import re from . import Image, ImagePalette class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": deprecate("Image categories", 10, "is_animated", plural=True) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None def close(self): """ Closes the file pointer, if possible. This operation will destroy the image core and release its memory. The image data will be unusable afterward. This function is required to close images that have multiple frames or have not had their file read and closed by the :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for more information. """ try: if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = DeferredError(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_pretty_(self, p, cycle): """IPython plain text display support""" # Same as __repr__ but without unpredictable id(self), # to keep Jupyter notebook `text/plain` output stable. p.text( "<%s.%s image mode=%s size=%dx%d>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], ) ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: msg = "Could not save to PNG for display" raise ValueError(msg) from e return b.getvalue() def __array_interface__(self): # numpy array interface support new = {"version": 3} try: if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() except Exception as e: if not isinstance(e, (MemoryError, RecursionError)): try: import numpy from packaging.version import parse as parse_version except ImportError: pass else: if parse_version(numpy.__version__) < parse_version("1.23"): warnings.warn(e) raise new["shape"], new["typestr"] = _conv_type_shape(self) return new def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. A list of C encoders can be seen under codecs section of the function array in :file:`_imaging.c`. Python encoders are registered within the relevant plugins. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() if self.width == 0 or self.height == 0: return b"" # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c output = [] while True: bytes_consumed, errcode, data = e.encode(bufsize) output.append(data) if errcode: break if errcode < 0: msg = f"encoder error {errcode} in tobytes" raise RuntimeError(msg) return b"".join(output) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": msg = "not a bitmap" raise ValueError(msg) data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: msg = "not enough image data" raise ValueError(msg) if s[1] != 0: msg = "cannot decode image data" raise ValueError(msg) def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im is not None and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: palette_mode = "RGBA" if mode.startswith("RGBA") else "RGB" self.palette.mode = palette_mode self.palette.palette = self.im.getpalette(palette_mode, palette_mode) if self.im is not None: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK". The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is ``None``, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. When converting from "PA", if an "RGBA" palette is present, the alpha channel from the image will be used instead of the values from the palette. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`Palette.WEB` or :data:`Palette.ADAPTIVE`. :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): msg = "illegal conversion" raise ValueError(msg) im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if (self.mode in ("1", "L", "I") and mode in ("LA", "RGBA")) or ( self.mode == "RGB" and mode == "RGBA" ): # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: msg = "Transparency for P mode should be bytes or int" raise ValueError(msg) if mode == "P" and palette == Palette.ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new if "LAB" in (self.mode, mode): other_mode = mode if self.mode == "LAB" else self.mode if other_mode in ("RGB", "RGBA", "RGBX"): from . import ImageCms srgb = ImageCms.createProfile("sRGB") lab = ImageCms.createProfile("LAB") profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab] transform = ImageCms.buildTransform( profiles[0], profiles[1], self.mode, mode ) return transform.apply(self) # colorspace conversion if dither is None: dither = Dither.FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again modebase = getmodebase(self.mode) if modebase == self.mode: raise im = self.im.convert(modebase) im = im.convert(mode, dither) except KeyError as e: msg = "illegal conversion" raise ValueError(msg) from e new_im = self._new(im) if mode == "P" and palette != Palette.ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`Quantize.MEDIANCUT` (median cut), :data:`Quantize.MAXCOVERAGE` (maximum coverage), :data:`Quantize.FASTOCTREE` (fast octree), :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`Quantize.MEDIANCUT` will be used. The exception to this is RGBA images. :data:`Quantize.MEDIANCUT` and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so :data:`Quantize.FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). :returns: A new image """ self.load() if method is None: # defaults: method = Quantize.MEDIANCUT if self.mode == "RGBA": method = Quantize.FASTOCTREE if self.mode == "RGBA" and method not in ( Quantize.FASTOCTREE, Quantize.LIBIMAGEQUANT, ): # Caller specified an invalid mode. msg = ( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) raise ValueError(msg) if palette: # use palette from reference image palette.load() if palette.mode != "P": msg = "bad mode for palette image" raise ValueError(msg) if self.mode != "RGB" and self.mode != "L": msg = "only RGB or L mode images can be quantized to a palette" raise ValueError(msg) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() if box[2] < box[0]: msg = "Coordinate 'right' is less than 'left'" raise ValueError(msg) elif box[3] < box[1]: msg = "Coordinate 'lower' is less than 'upper'" raise ValueError(msg) self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size in pixels, as a 2-tuple: (width, height). """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): msg = "filter argument should be ImageFilter.Filter instance or class" raise TypeError(msg) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): """ Gets EXIF data from the image. :returns: an :py:class:`~PIL.Image.Exif` object. """ if self._exif is None: self._exif = Exif() self._exif._loaded = False elif self._exif._loaded: return self._exif self._exif._loaded = True exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.bigtiff = self.tag_v2._bigtiff self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation(="|>)([0-9])', xmp_tags) if match: self._exif[0x0112] = int(match[2]) return self._exif def _reload_exif(self): if self._exif is None or not self._exif._loaded: return self._exif._loaded = False self.getexif() def get_child_images(self): child_images = [] exif = self.getexif() ifds = [] if ExifTags.Base.SubIFDs in exif: subifd_offsets = exif[ExifTags.Base.SubIFDs] if subifd_offsets: if not isinstance(subifd_offsets, tuple): subifd_offsets = (subifd_offsets,) for subifd_offset in subifd_offsets: ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset)) ifd1 = exif.get_ifd(ExifTags.IFD.IFD1) if ifd1 and ifd1.get(513): ifds.append((ifd1, exif._info.next)) offset = None for ifd, ifd_offset in ifds: current_offset = self.fp.tell() if offset is None: offset = current_offset fp = self.fp thumbnail_offset = ifd.get(513) if thumbnail_offset is not None: try: thumbnail_offset += self._exif_offset except AttributeError: pass self.fp.seek(thumbnail_offset) data = self.fp.read(ifd.get(514)) fp = io.BytesIO(data) with open(fp) as im: if thumbnail_offset is None: im._frame_pos = [ifd_offset] im._seek(0) im.load() child_images.append(im) if offset is not None: self.fp.seek(offset) return child_images def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self, rawmode="RGB"): """ Returns the image palette as a list. :param rawmode: The mode in which to return the palette. ``None`` will return the palette in its current mode. .. versionadded:: 9.1.0 :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: mode = self.im.getpalettemode() except ValueError: return None # no palette if rawmode is None: rawmode = mode return list(self.im.getpalette(mode, rawmode)) def apply_transparency(self): """ If a P mode image has a "transparency" key in the info dictionary, remove the key and instead apply the transparency to the palette. Otherwise, the image is unchanged. """ if self.mode != "P" or "transparency" not in self.info: return from . import ImagePalette palette = self.getpalette("RGBA") transparency = self.info["transparency"] if isinstance(transparency, bytes): for i, alpha in enumerate(transparency): palette[i * 4 + 3] = alpha else: palette[transparency * 4 + 3] = 0 self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette)) self.palette.dirty = 1 del self.info["transparency"] def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. Counts are grouped into 256 bins for each band, even if the image has more than 8 bits per band. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", "LA", "RGBA" or "RGBa" images (if present, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? msg = "cannot determine region size; use 4-item box" raise ValueError(msg) box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): msg = "Source must be a tuple" raise ValueError(msg) if not isinstance(dest, (list, tuple)): msg = "Destination must be a tuple" raise ValueError(msg) if not len(source) in (2, 4): msg = "Source must be a 2 or 4-tuple" raise ValueError(msg) if not len(dest) == 2: msg = "Destination must be a 2-tuple" raise ValueError(msg) if min(source) < 0: msg = "Source must be non-negative" raise ValueError(msg) if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case msg = "point operation not supported for this mode" raise ValueError(msg) if mode != "F": lut = [round(i) for i in lut] return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: msg = "illegal image mode" raise ValueError(msg) from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): msg = "illegal image mode" raise ValueError(msg) alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): msg = "illegal image mode" raise ValueError(msg) if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P and PA images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode in ("P", "PA") and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P or PA image if self.mode == "PA": alpha = value[3] if len(value) == 4 else 255 value = value[:3] value = self.palette.getcolor(value, self) if self.mode == "PA": value = (value, alpha) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): msg = "illegal image mode" raise ValueError(msg) bands = 3 palette_mode = "RGB" if source_palette is None: if self.mode == "P": self.load() palette_mode = self.im.getpalettemode() if palette_mode == "RGBA": bands = 4 source_palette = self.im.getpalette(palette_mode, palette_mode) else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[ oldPosition * bands : oldPosition * bands + bands ] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette( palette_mode, palette=mapping_palette * bands ) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette(palette_mode + ";L", m_im.palette.tobytes()) m_im = m_im.convert("L") m_im.putpalette(palette_bytes, palette_mode) m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes) if "transparency" in self.info: try: m_im.info["transparency"] = dest_map.index(self.info["transparency"]) except ValueError: if "transparency" in m_im.info: del m_im.info["transparency"] return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`Resampling.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`Resampling.NEAREST`. Otherwise, the default filter is :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = Resampling.NEAREST if type_special else Resampling.BICUBIC elif resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, Resampling.LANCZOS, Resampling.BOX, Resampling.HAMMING, ): msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), (Resampling.BOX, "Image.Resampling.BOX"), (Resampling.HAMMING, "Image.Resampling.HAMMING"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) if reducing_gap is not None and reducing_gap < 1.0: msg = "reducing_gap must be 1.0 or greater" raise ValueError(msg) size = tuple(size) self.load() if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = Resampling.NEAREST if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != Resampling.NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(Transpose.ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose( Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270 ) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform( (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor ) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif is_path(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and is_path(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: msg = f"unknown file extension: {ext}" raise ValueError(msg) from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] created = False if open_fp: created = not os.path.exists(filename) if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) except Exception: if open_fp: fp.close() if created: try: os.remove(filename) except PermissionError: pass raise if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: msg = f'The image has no channel "{channel}"' raise ValueError(msg) from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: Optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If omitted, it defaults to :py:data:`Resampling.BICUBIC`. (was :py:data:`Resampling.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ provided_size = tuple(map(math.floor, size)) def preserve_aspect_ratio(): def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) x, y = provided_size if x >= self.width and y >= self.height: return aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) return x, y box = None if reducing_gap is not None: size = preserve_aspect_ratio() if size is None: return res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if box is None: self.load() # load() may have changed the size of the image size = preserve_aspect_ratio() if size is None: return if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size in pixels, as a 2-tuple: (width, height). :param method: The transformation method. This is one of :py:data:`Transform.EXTENT` (cut out a rectangular subregion), :py:data:`Transform.AFFINE` (affine transform), :py:data:`Transform.PERSPECTIVE` (perspective transform), :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or :py:data:`Transform.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.Transform.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: msg = "missing method data" raise ValueError(msg) im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == Transform.MESH: # list of quads for box, quad in data: im.__transformer( box, self, Transform.QUAD, quad, resample, fillcolor is None ) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): w = box[2] - box[0] h = box[3] - box[1] if method == Transform.AFFINE: data = data[:6] elif method == Transform.EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = Transform.AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == Transform.PERSPECTIVE: data = data[:8] elif method == Transform.QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: msg = "unknown transformation method" raise ValueError(msg) if resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, ): if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS): msg = { Resampling.BOX: "Image.Resampling.BOX", Resampling.HAMMING: "Image.Resampling.HAMMING", Resampling.LANCZOS: "Image.Resampling.LANCZOS", }[resample] + f" ({resample}) cannot be used." else: msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) image.load() self.load() if image.mode in ("1", "P"): resample = Resampling.NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`, :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`, :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`, :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `deform` function. Write a Python function `def deform(image, deformer, resample=Image.Resampling.BILINEAR)` to solve the following problem: Deform the image. :param image: The image to deform. :param deformer: A deformer object. Any object that implements a ``getmesh`` method can be used. :param resample: An optional resampling filter. Same values possible as in the PIL.Image.transform function. :return: An image. Here is the function: def deform(image, deformer, resample=Image.Resampling.BILINEAR): """ Deform the image. :param image: The image to deform. :param deformer: A deformer object. Any object that implements a ``getmesh`` method can be used. :param resample: An optional resampling filter. Same values possible as in the PIL.Image.transform function. :return: An image. """ return image.transform( image.size, Image.Transform.MESH, deformer.getmesh(image), resample )
Deform the image. :param image: The image to deform. :param deformer: A deformer object. Any object that implements a ``getmesh`` method can be used. :param resample: An optional resampling filter. Same values possible as in the PIL.Image.transform function. :return: An image.
174,068
import functools import operator import re from . import Image, ImagePalette def _lut(image, lut): if image.mode == "P": # FIXME: apply to lookup table, not image data msg = "mode P support coming soon" raise NotImplementedError(msg) elif image.mode in ("L", "RGB"): if image.mode == "RGB" and len(lut) == 256: lut = lut + lut + lut return image.point(lut) else: msg = "not supported for this image mode" raise OSError(msg) The provided code snippet includes necessary dependencies for implementing the `equalize` function. Write a Python function `def equalize(image, mask=None)` to solve the following problem: Equalize the image histogram. This function applies a non-linear mapping to the input image, in order to create a uniform distribution of grayscale values in the output image. :param image: The image to equalize. :param mask: An optional mask. If given, only the pixels selected by the mask are included in the analysis. :return: An image. Here is the function: def equalize(image, mask=None): """ Equalize the image histogram. This function applies a non-linear mapping to the input image, in order to create a uniform distribution of grayscale values in the output image. :param image: The image to equalize. :param mask: An optional mask. If given, only the pixels selected by the mask are included in the analysis. :return: An image. """ if image.mode == "P": image = image.convert("RGB") h = image.histogram(mask) lut = [] for b in range(0, len(h), 256): histo = [_f for _f in h[b : b + 256] if _f] if len(histo) <= 1: lut.extend(list(range(256))) else: step = (functools.reduce(operator.add, histo) - histo[-1]) // 255 if not step: lut.extend(list(range(256))) else: n = step // 2 for i in range(256): lut.append(n // step) n = n + h[i + b] return _lut(image, lut)
Equalize the image histogram. This function applies a non-linear mapping to the input image, in order to create a uniform distribution of grayscale values in the output image. :param image: The image to equalize. :param mask: An optional mask. If given, only the pixels selected by the mask are included in the analysis. :return: An image.
174,069
import functools import operator import re from . import Image, ImagePalette def _border(border): if isinstance(border, tuple): if len(border) == 2: left, top = right, bottom = border elif len(border) == 4: left, top, right, bottom = border else: left = top = right = bottom = border return left, top, right, bottom def _color(color, mode): if isinstance(color, str): from . import ImageColor color = ImageColor.getcolor(color, mode) return color class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": deprecate("Image categories", 10, "is_animated", plural=True) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None def close(self): """ Closes the file pointer, if possible. This operation will destroy the image core and release its memory. The image data will be unusable afterward. This function is required to close images that have multiple frames or have not had their file read and closed by the :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for more information. """ try: if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = DeferredError(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_pretty_(self, p, cycle): """IPython plain text display support""" # Same as __repr__ but without unpredictable id(self), # to keep Jupyter notebook `text/plain` output stable. p.text( "<%s.%s image mode=%s size=%dx%d>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], ) ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: msg = "Could not save to PNG for display" raise ValueError(msg) from e return b.getvalue() def __array_interface__(self): # numpy array interface support new = {"version": 3} try: if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() except Exception as e: if not isinstance(e, (MemoryError, RecursionError)): try: import numpy from packaging.version import parse as parse_version except ImportError: pass else: if parse_version(numpy.__version__) < parse_version("1.23"): warnings.warn(e) raise new["shape"], new["typestr"] = _conv_type_shape(self) return new def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. A list of C encoders can be seen under codecs section of the function array in :file:`_imaging.c`. Python encoders are registered within the relevant plugins. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() if self.width == 0 or self.height == 0: return b"" # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c output = [] while True: bytes_consumed, errcode, data = e.encode(bufsize) output.append(data) if errcode: break if errcode < 0: msg = f"encoder error {errcode} in tobytes" raise RuntimeError(msg) return b"".join(output) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": msg = "not a bitmap" raise ValueError(msg) data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: msg = "not enough image data" raise ValueError(msg) if s[1] != 0: msg = "cannot decode image data" raise ValueError(msg) def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im is not None and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: palette_mode = "RGBA" if mode.startswith("RGBA") else "RGB" self.palette.mode = palette_mode self.palette.palette = self.im.getpalette(palette_mode, palette_mode) if self.im is not None: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK". The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is ``None``, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. When converting from "PA", if an "RGBA" palette is present, the alpha channel from the image will be used instead of the values from the palette. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`Palette.WEB` or :data:`Palette.ADAPTIVE`. :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): msg = "illegal conversion" raise ValueError(msg) im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if (self.mode in ("1", "L", "I") and mode in ("LA", "RGBA")) or ( self.mode == "RGB" and mode == "RGBA" ): # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: msg = "Transparency for P mode should be bytes or int" raise ValueError(msg) if mode == "P" and palette == Palette.ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new if "LAB" in (self.mode, mode): other_mode = mode if self.mode == "LAB" else self.mode if other_mode in ("RGB", "RGBA", "RGBX"): from . import ImageCms srgb = ImageCms.createProfile("sRGB") lab = ImageCms.createProfile("LAB") profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab] transform = ImageCms.buildTransform( profiles[0], profiles[1], self.mode, mode ) return transform.apply(self) # colorspace conversion if dither is None: dither = Dither.FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again modebase = getmodebase(self.mode) if modebase == self.mode: raise im = self.im.convert(modebase) im = im.convert(mode, dither) except KeyError as e: msg = "illegal conversion" raise ValueError(msg) from e new_im = self._new(im) if mode == "P" and palette != Palette.ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`Quantize.MEDIANCUT` (median cut), :data:`Quantize.MAXCOVERAGE` (maximum coverage), :data:`Quantize.FASTOCTREE` (fast octree), :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`Quantize.MEDIANCUT` will be used. The exception to this is RGBA images. :data:`Quantize.MEDIANCUT` and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so :data:`Quantize.FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). :returns: A new image """ self.load() if method is None: # defaults: method = Quantize.MEDIANCUT if self.mode == "RGBA": method = Quantize.FASTOCTREE if self.mode == "RGBA" and method not in ( Quantize.FASTOCTREE, Quantize.LIBIMAGEQUANT, ): # Caller specified an invalid mode. msg = ( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) raise ValueError(msg) if palette: # use palette from reference image palette.load() if palette.mode != "P": msg = "bad mode for palette image" raise ValueError(msg) if self.mode != "RGB" and self.mode != "L": msg = "only RGB or L mode images can be quantized to a palette" raise ValueError(msg) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() if box[2] < box[0]: msg = "Coordinate 'right' is less than 'left'" raise ValueError(msg) elif box[3] < box[1]: msg = "Coordinate 'lower' is less than 'upper'" raise ValueError(msg) self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size in pixels, as a 2-tuple: (width, height). """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): msg = "filter argument should be ImageFilter.Filter instance or class" raise TypeError(msg) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): """ Gets EXIF data from the image. :returns: an :py:class:`~PIL.Image.Exif` object. """ if self._exif is None: self._exif = Exif() self._exif._loaded = False elif self._exif._loaded: return self._exif self._exif._loaded = True exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.bigtiff = self.tag_v2._bigtiff self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation(="|>)([0-9])', xmp_tags) if match: self._exif[0x0112] = int(match[2]) return self._exif def _reload_exif(self): if self._exif is None or not self._exif._loaded: return self._exif._loaded = False self.getexif() def get_child_images(self): child_images = [] exif = self.getexif() ifds = [] if ExifTags.Base.SubIFDs in exif: subifd_offsets = exif[ExifTags.Base.SubIFDs] if subifd_offsets: if not isinstance(subifd_offsets, tuple): subifd_offsets = (subifd_offsets,) for subifd_offset in subifd_offsets: ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset)) ifd1 = exif.get_ifd(ExifTags.IFD.IFD1) if ifd1 and ifd1.get(513): ifds.append((ifd1, exif._info.next)) offset = None for ifd, ifd_offset in ifds: current_offset = self.fp.tell() if offset is None: offset = current_offset fp = self.fp thumbnail_offset = ifd.get(513) if thumbnail_offset is not None: try: thumbnail_offset += self._exif_offset except AttributeError: pass self.fp.seek(thumbnail_offset) data = self.fp.read(ifd.get(514)) fp = io.BytesIO(data) with open(fp) as im: if thumbnail_offset is None: im._frame_pos = [ifd_offset] im._seek(0) im.load() child_images.append(im) if offset is not None: self.fp.seek(offset) return child_images def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self, rawmode="RGB"): """ Returns the image palette as a list. :param rawmode: The mode in which to return the palette. ``None`` will return the palette in its current mode. .. versionadded:: 9.1.0 :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: mode = self.im.getpalettemode() except ValueError: return None # no palette if rawmode is None: rawmode = mode return list(self.im.getpalette(mode, rawmode)) def apply_transparency(self): """ If a P mode image has a "transparency" key in the info dictionary, remove the key and instead apply the transparency to the palette. Otherwise, the image is unchanged. """ if self.mode != "P" or "transparency" not in self.info: return from . import ImagePalette palette = self.getpalette("RGBA") transparency = self.info["transparency"] if isinstance(transparency, bytes): for i, alpha in enumerate(transparency): palette[i * 4 + 3] = alpha else: palette[transparency * 4 + 3] = 0 self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette)) self.palette.dirty = 1 del self.info["transparency"] def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. Counts are grouped into 256 bins for each band, even if the image has more than 8 bits per band. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", "LA", "RGBA" or "RGBa" images (if present, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? msg = "cannot determine region size; use 4-item box" raise ValueError(msg) box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): msg = "Source must be a tuple" raise ValueError(msg) if not isinstance(dest, (list, tuple)): msg = "Destination must be a tuple" raise ValueError(msg) if not len(source) in (2, 4): msg = "Source must be a 2 or 4-tuple" raise ValueError(msg) if not len(dest) == 2: msg = "Destination must be a 2-tuple" raise ValueError(msg) if min(source) < 0: msg = "Source must be non-negative" raise ValueError(msg) if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case msg = "point operation not supported for this mode" raise ValueError(msg) if mode != "F": lut = [round(i) for i in lut] return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: msg = "illegal image mode" raise ValueError(msg) from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): msg = "illegal image mode" raise ValueError(msg) alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): msg = "illegal image mode" raise ValueError(msg) if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P and PA images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode in ("P", "PA") and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P or PA image if self.mode == "PA": alpha = value[3] if len(value) == 4 else 255 value = value[:3] value = self.palette.getcolor(value, self) if self.mode == "PA": value = (value, alpha) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): msg = "illegal image mode" raise ValueError(msg) bands = 3 palette_mode = "RGB" if source_palette is None: if self.mode == "P": self.load() palette_mode = self.im.getpalettemode() if palette_mode == "RGBA": bands = 4 source_palette = self.im.getpalette(palette_mode, palette_mode) else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[ oldPosition * bands : oldPosition * bands + bands ] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette( palette_mode, palette=mapping_palette * bands ) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette(palette_mode + ";L", m_im.palette.tobytes()) m_im = m_im.convert("L") m_im.putpalette(palette_bytes, palette_mode) m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes) if "transparency" in self.info: try: m_im.info["transparency"] = dest_map.index(self.info["transparency"]) except ValueError: if "transparency" in m_im.info: del m_im.info["transparency"] return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`Resampling.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`Resampling.NEAREST`. Otherwise, the default filter is :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = Resampling.NEAREST if type_special else Resampling.BICUBIC elif resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, Resampling.LANCZOS, Resampling.BOX, Resampling.HAMMING, ): msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), (Resampling.BOX, "Image.Resampling.BOX"), (Resampling.HAMMING, "Image.Resampling.HAMMING"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) if reducing_gap is not None and reducing_gap < 1.0: msg = "reducing_gap must be 1.0 or greater" raise ValueError(msg) size = tuple(size) self.load() if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = Resampling.NEAREST if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != Resampling.NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(Transpose.ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose( Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270 ) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform( (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor ) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif is_path(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and is_path(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: msg = f"unknown file extension: {ext}" raise ValueError(msg) from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] created = False if open_fp: created = not os.path.exists(filename) if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) except Exception: if open_fp: fp.close() if created: try: os.remove(filename) except PermissionError: pass raise if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: msg = f'The image has no channel "{channel}"' raise ValueError(msg) from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: Optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If omitted, it defaults to :py:data:`Resampling.BICUBIC`. (was :py:data:`Resampling.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ provided_size = tuple(map(math.floor, size)) def preserve_aspect_ratio(): def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) x, y = provided_size if x >= self.width and y >= self.height: return aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) return x, y box = None if reducing_gap is not None: size = preserve_aspect_ratio() if size is None: return res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if box is None: self.load() # load() may have changed the size of the image size = preserve_aspect_ratio() if size is None: return if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size in pixels, as a 2-tuple: (width, height). :param method: The transformation method. This is one of :py:data:`Transform.EXTENT` (cut out a rectangular subregion), :py:data:`Transform.AFFINE` (affine transform), :py:data:`Transform.PERSPECTIVE` (perspective transform), :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or :py:data:`Transform.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.Transform.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: msg = "missing method data" raise ValueError(msg) im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == Transform.MESH: # list of quads for box, quad in data: im.__transformer( box, self, Transform.QUAD, quad, resample, fillcolor is None ) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): w = box[2] - box[0] h = box[3] - box[1] if method == Transform.AFFINE: data = data[:6] elif method == Transform.EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = Transform.AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == Transform.PERSPECTIVE: data = data[:8] elif method == Transform.QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: msg = "unknown transformation method" raise ValueError(msg) if resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, ): if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS): msg = { Resampling.BOX: "Image.Resampling.BOX", Resampling.HAMMING: "Image.Resampling.HAMMING", Resampling.LANCZOS: "Image.Resampling.LANCZOS", }[resample] + f" ({resample}) cannot be used." else: msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) image.load() self.load() if image.mode in ("1", "P"): resample = Resampling.NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`, :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`, :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`, :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqpixmap(self) class ImagePalette: """ Color palette for palette mapped images :param mode: The mode to use for the palette. See: :ref:`concept-modes`. Defaults to "RGB" :param palette: An optional palette. If given, it must be a bytearray, an array or a list of ints between 0-255. The list must consist of all channels for one color followed by the next color (e.g. RGBRGBRGB). Defaults to an empty palette. """ def __init__(self, mode="RGB", palette=None, size=0): self.mode = mode self.rawmode = None # if set, palette contains raw data self.palette = palette or bytearray() self.dirty = None if size != 0: deprecate("The size parameter", 10, None) if size != len(self.palette): msg = "wrong palette size" raise ValueError(msg) def palette(self): return self._palette def palette(self, palette): self._colors = None self._palette = palette def colors(self): if self._colors is None: mode_len = len(self.mode) self._colors = {} for i in range(0, len(self.palette), mode_len): color = tuple(self.palette[i : i + mode_len]) if color in self._colors: continue self._colors[color] = i // mode_len return self._colors def colors(self, colors): self._colors = colors def copy(self): new = ImagePalette() new.mode = self.mode new.rawmode = self.rawmode if self.palette is not None: new.palette = self.palette[:] new.dirty = self.dirty return new def getdata(self): """ Get palette contents in format suitable for the low-level ``im.putpalette`` primitive. .. warning:: This method is experimental. """ if self.rawmode: return self.rawmode, self.palette return self.mode, self.tobytes() def tobytes(self): """Convert palette to bytes. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(self.palette, bytes): return self.palette arr = array.array("B", self.palette) return arr.tobytes() # Declare tostring as an alias for tobytes tostring = tobytes def getcolor(self, color, image=None): """Given an rgb tuple, allocate palette entry. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(color, tuple): if self.mode == "RGB": if len(color) == 4: if color[3] != 255: msg = "cannot add non-opaque RGBA color to RGB palette" raise ValueError(msg) color = color[:3] elif self.mode == "RGBA": if len(color) == 3: color += (255,) try: return self.colors[color] except KeyError as e: # allocate new color slot if not isinstance(self.palette, bytearray): self._palette = bytearray(self.palette) index = len(self.palette) // 3 special_colors = () if image: special_colors = ( image.info.get("background"), image.info.get("transparency"), ) while index in special_colors: index += 1 if index >= 256: if image: # Search for an unused index for i, count in reversed(list(enumerate(image.histogram()))): if count == 0 and i not in special_colors: index = i break if index >= 256: msg = "cannot allocate more than 256 colors" raise ValueError(msg) from e self.colors[color] = index if index * 3 < len(self.palette): self._palette = ( self.palette[: index * 3] + bytes(color) + self.palette[index * 3 + 3 :] ) else: self._palette += bytes(color) self.dirty = 1 return index else: msg = f"unknown color specifier: {repr(color)}" raise ValueError(msg) def save(self, fp): """Save palette to text file. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(fp, str): fp = open(fp, "w") fp.write("# Palette\n") fp.write(f"# Mode: {self.mode}\n") for i in range(256): fp.write(f"{i}") for j in range(i * len(self.mode), (i + 1) * len(self.mode)): try: fp.write(f" {self.palette[j]}") except IndexError: fp.write(" 0") fp.write("\n") fp.close() The provided code snippet includes necessary dependencies for implementing the `expand` function. Write a Python function `def expand(image, border=0, fill=0)` to solve the following problem: Add border to the image :param image: The image to expand. :param border: Border width, in pixels. :param fill: Pixel fill value (a color value). Default is 0 (black). :return: An image. Here is the function: def expand(image, border=0, fill=0): """ Add border to the image :param image: The image to expand. :param border: Border width, in pixels. :param fill: Pixel fill value (a color value). Default is 0 (black). :return: An image. """ left, top, right, bottom = _border(border) width = left + image.size[0] + right height = top + image.size[1] + bottom color = _color(fill, image.mode) if image.palette: palette = ImagePalette.ImagePalette(palette=image.getpalette()) if isinstance(color, tuple): color = palette.getcolor(color) else: palette = None out = Image.new(image.mode, (width, height), color) if palette: out.putpalette(palette.palette) out.paste(image, (left, top)) return out
Add border to the image :param image: The image to expand. :param border: Border width, in pixels. :param fill: Pixel fill value (a color value). Default is 0 (black). :return: An image.
174,070
import functools import operator import re from . import Image, ImagePalette def crop(image, border=0): """ Remove border from image. The same amount of pixels are removed from all four sides. This function works on all image modes. .. seealso:: :py:meth:`~PIL.Image.Image.crop` :param image: The image to crop. :param border: The number of pixels to remove. :return: An image. """ left, top, right, bottom = _border(border) return image.crop((left, top, image.size[0] - right, image.size[1] - bottom)) class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": deprecate("Image categories", 10, "is_animated", plural=True) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None def close(self): """ Closes the file pointer, if possible. This operation will destroy the image core and release its memory. The image data will be unusable afterward. This function is required to close images that have multiple frames or have not had their file read and closed by the :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for more information. """ try: if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = DeferredError(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_pretty_(self, p, cycle): """IPython plain text display support""" # Same as __repr__ but without unpredictable id(self), # to keep Jupyter notebook `text/plain` output stable. p.text( "<%s.%s image mode=%s size=%dx%d>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], ) ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: msg = "Could not save to PNG for display" raise ValueError(msg) from e return b.getvalue() def __array_interface__(self): # numpy array interface support new = {"version": 3} try: if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() except Exception as e: if not isinstance(e, (MemoryError, RecursionError)): try: import numpy from packaging.version import parse as parse_version except ImportError: pass else: if parse_version(numpy.__version__) < parse_version("1.23"): warnings.warn(e) raise new["shape"], new["typestr"] = _conv_type_shape(self) return new def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. A list of C encoders can be seen under codecs section of the function array in :file:`_imaging.c`. Python encoders are registered within the relevant plugins. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() if self.width == 0 or self.height == 0: return b"" # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c output = [] while True: bytes_consumed, errcode, data = e.encode(bufsize) output.append(data) if errcode: break if errcode < 0: msg = f"encoder error {errcode} in tobytes" raise RuntimeError(msg) return b"".join(output) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": msg = "not a bitmap" raise ValueError(msg) data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: msg = "not enough image data" raise ValueError(msg) if s[1] != 0: msg = "cannot decode image data" raise ValueError(msg) def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im is not None and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: palette_mode = "RGBA" if mode.startswith("RGBA") else "RGB" self.palette.mode = palette_mode self.palette.palette = self.im.getpalette(palette_mode, palette_mode) if self.im is not None: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK". The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is ``None``, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. When converting from "PA", if an "RGBA" palette is present, the alpha channel from the image will be used instead of the values from the palette. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`Palette.WEB` or :data:`Palette.ADAPTIVE`. :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): msg = "illegal conversion" raise ValueError(msg) im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if (self.mode in ("1", "L", "I") and mode in ("LA", "RGBA")) or ( self.mode == "RGB" and mode == "RGBA" ): # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: msg = "Transparency for P mode should be bytes or int" raise ValueError(msg) if mode == "P" and palette == Palette.ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new if "LAB" in (self.mode, mode): other_mode = mode if self.mode == "LAB" else self.mode if other_mode in ("RGB", "RGBA", "RGBX"): from . import ImageCms srgb = ImageCms.createProfile("sRGB") lab = ImageCms.createProfile("LAB") profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab] transform = ImageCms.buildTransform( profiles[0], profiles[1], self.mode, mode ) return transform.apply(self) # colorspace conversion if dither is None: dither = Dither.FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again modebase = getmodebase(self.mode) if modebase == self.mode: raise im = self.im.convert(modebase) im = im.convert(mode, dither) except KeyError as e: msg = "illegal conversion" raise ValueError(msg) from e new_im = self._new(im) if mode == "P" and palette != Palette.ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`Quantize.MEDIANCUT` (median cut), :data:`Quantize.MAXCOVERAGE` (maximum coverage), :data:`Quantize.FASTOCTREE` (fast octree), :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`Quantize.MEDIANCUT` will be used. The exception to this is RGBA images. :data:`Quantize.MEDIANCUT` and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so :data:`Quantize.FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). :returns: A new image """ self.load() if method is None: # defaults: method = Quantize.MEDIANCUT if self.mode == "RGBA": method = Quantize.FASTOCTREE if self.mode == "RGBA" and method not in ( Quantize.FASTOCTREE, Quantize.LIBIMAGEQUANT, ): # Caller specified an invalid mode. msg = ( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) raise ValueError(msg) if palette: # use palette from reference image palette.load() if palette.mode != "P": msg = "bad mode for palette image" raise ValueError(msg) if self.mode != "RGB" and self.mode != "L": msg = "only RGB or L mode images can be quantized to a palette" raise ValueError(msg) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() if box[2] < box[0]: msg = "Coordinate 'right' is less than 'left'" raise ValueError(msg) elif box[3] < box[1]: msg = "Coordinate 'lower' is less than 'upper'" raise ValueError(msg) self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size in pixels, as a 2-tuple: (width, height). """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): msg = "filter argument should be ImageFilter.Filter instance or class" raise TypeError(msg) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): """ Gets EXIF data from the image. :returns: an :py:class:`~PIL.Image.Exif` object. """ if self._exif is None: self._exif = Exif() self._exif._loaded = False elif self._exif._loaded: return self._exif self._exif._loaded = True exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.bigtiff = self.tag_v2._bigtiff self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation(="|>)([0-9])', xmp_tags) if match: self._exif[0x0112] = int(match[2]) return self._exif def _reload_exif(self): if self._exif is None or not self._exif._loaded: return self._exif._loaded = False self.getexif() def get_child_images(self): child_images = [] exif = self.getexif() ifds = [] if ExifTags.Base.SubIFDs in exif: subifd_offsets = exif[ExifTags.Base.SubIFDs] if subifd_offsets: if not isinstance(subifd_offsets, tuple): subifd_offsets = (subifd_offsets,) for subifd_offset in subifd_offsets: ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset)) ifd1 = exif.get_ifd(ExifTags.IFD.IFD1) if ifd1 and ifd1.get(513): ifds.append((ifd1, exif._info.next)) offset = None for ifd, ifd_offset in ifds: current_offset = self.fp.tell() if offset is None: offset = current_offset fp = self.fp thumbnail_offset = ifd.get(513) if thumbnail_offset is not None: try: thumbnail_offset += self._exif_offset except AttributeError: pass self.fp.seek(thumbnail_offset) data = self.fp.read(ifd.get(514)) fp = io.BytesIO(data) with open(fp) as im: if thumbnail_offset is None: im._frame_pos = [ifd_offset] im._seek(0) im.load() child_images.append(im) if offset is not None: self.fp.seek(offset) return child_images def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self, rawmode="RGB"): """ Returns the image palette as a list. :param rawmode: The mode in which to return the palette. ``None`` will return the palette in its current mode. .. versionadded:: 9.1.0 :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: mode = self.im.getpalettemode() except ValueError: return None # no palette if rawmode is None: rawmode = mode return list(self.im.getpalette(mode, rawmode)) def apply_transparency(self): """ If a P mode image has a "transparency" key in the info dictionary, remove the key and instead apply the transparency to the palette. Otherwise, the image is unchanged. """ if self.mode != "P" or "transparency" not in self.info: return from . import ImagePalette palette = self.getpalette("RGBA") transparency = self.info["transparency"] if isinstance(transparency, bytes): for i, alpha in enumerate(transparency): palette[i * 4 + 3] = alpha else: palette[transparency * 4 + 3] = 0 self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette)) self.palette.dirty = 1 del self.info["transparency"] def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. Counts are grouped into 256 bins for each band, even if the image has more than 8 bits per band. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", "LA", "RGBA" or "RGBa" images (if present, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? msg = "cannot determine region size; use 4-item box" raise ValueError(msg) box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): msg = "Source must be a tuple" raise ValueError(msg) if not isinstance(dest, (list, tuple)): msg = "Destination must be a tuple" raise ValueError(msg) if not len(source) in (2, 4): msg = "Source must be a 2 or 4-tuple" raise ValueError(msg) if not len(dest) == 2: msg = "Destination must be a 2-tuple" raise ValueError(msg) if min(source) < 0: msg = "Source must be non-negative" raise ValueError(msg) if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case msg = "point operation not supported for this mode" raise ValueError(msg) if mode != "F": lut = [round(i) for i in lut] return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: msg = "illegal image mode" raise ValueError(msg) from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): msg = "illegal image mode" raise ValueError(msg) alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): msg = "illegal image mode" raise ValueError(msg) if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P and PA images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode in ("P", "PA") and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P or PA image if self.mode == "PA": alpha = value[3] if len(value) == 4 else 255 value = value[:3] value = self.palette.getcolor(value, self) if self.mode == "PA": value = (value, alpha) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): msg = "illegal image mode" raise ValueError(msg) bands = 3 palette_mode = "RGB" if source_palette is None: if self.mode == "P": self.load() palette_mode = self.im.getpalettemode() if palette_mode == "RGBA": bands = 4 source_palette = self.im.getpalette(palette_mode, palette_mode) else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[ oldPosition * bands : oldPosition * bands + bands ] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette( palette_mode, palette=mapping_palette * bands ) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette(palette_mode + ";L", m_im.palette.tobytes()) m_im = m_im.convert("L") m_im.putpalette(palette_bytes, palette_mode) m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes) if "transparency" in self.info: try: m_im.info["transparency"] = dest_map.index(self.info["transparency"]) except ValueError: if "transparency" in m_im.info: del m_im.info["transparency"] return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`Resampling.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`Resampling.NEAREST`. Otherwise, the default filter is :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = Resampling.NEAREST if type_special else Resampling.BICUBIC elif resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, Resampling.LANCZOS, Resampling.BOX, Resampling.HAMMING, ): msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), (Resampling.BOX, "Image.Resampling.BOX"), (Resampling.HAMMING, "Image.Resampling.HAMMING"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) if reducing_gap is not None and reducing_gap < 1.0: msg = "reducing_gap must be 1.0 or greater" raise ValueError(msg) size = tuple(size) self.load() if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = Resampling.NEAREST if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != Resampling.NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(Transpose.ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose( Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270 ) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform( (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor ) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif is_path(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and is_path(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: msg = f"unknown file extension: {ext}" raise ValueError(msg) from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] created = False if open_fp: created = not os.path.exists(filename) if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) except Exception: if open_fp: fp.close() if created: try: os.remove(filename) except PermissionError: pass raise if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: msg = f'The image has no channel "{channel}"' raise ValueError(msg) from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: Optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If omitted, it defaults to :py:data:`Resampling.BICUBIC`. (was :py:data:`Resampling.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ provided_size = tuple(map(math.floor, size)) def preserve_aspect_ratio(): def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) x, y = provided_size if x >= self.width and y >= self.height: return aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) return x, y box = None if reducing_gap is not None: size = preserve_aspect_ratio() if size is None: return res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if box is None: self.load() # load() may have changed the size of the image size = preserve_aspect_ratio() if size is None: return if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size in pixels, as a 2-tuple: (width, height). :param method: The transformation method. This is one of :py:data:`Transform.EXTENT` (cut out a rectangular subregion), :py:data:`Transform.AFFINE` (affine transform), :py:data:`Transform.PERSPECTIVE` (perspective transform), :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or :py:data:`Transform.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.Transform.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: msg = "missing method data" raise ValueError(msg) im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == Transform.MESH: # list of quads for box, quad in data: im.__transformer( box, self, Transform.QUAD, quad, resample, fillcolor is None ) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): w = box[2] - box[0] h = box[3] - box[1] if method == Transform.AFFINE: data = data[:6] elif method == Transform.EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = Transform.AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == Transform.PERSPECTIVE: data = data[:8] elif method == Transform.QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: msg = "unknown transformation method" raise ValueError(msg) if resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, ): if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS): msg = { Resampling.BOX: "Image.Resampling.BOX", Resampling.HAMMING: "Image.Resampling.HAMMING", Resampling.LANCZOS: "Image.Resampling.LANCZOS", }[resample] + f" ({resample}) cannot be used." else: msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) image.load() self.load() if image.mode in ("1", "P"): resample = Resampling.NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`, :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`, :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`, :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `fit` function. Write a Python function `def fit(image, size, method=Image.Resampling.BICUBIC, bleed=0.0, centering=(0.5, 0.5))` to solve the following problem: Returns a resized and cropped version of the image, cropped to the requested aspect ratio and size. This function was contributed by Kevin Cazabon. :param image: The image to resize and crop. :param size: The requested output size in pixels, given as a (width, height) tuple. :param method: Resampling method to use. Default is :py:attr:`~PIL.Image.Resampling.BICUBIC`. See :ref:`concept-filters`. :param bleed: Remove a border around the outside of the image from all four edges. The value is a decimal percentage (use 0.01 for one percent). The default value is 0 (no border). Cannot be greater than or equal to 0.5. :param centering: Control the cropping position. Use (0.5, 0.5) for center cropping (e.g. if cropping the width, take 50% off of the left side, and therefore 50% off the right side). (0.0, 0.0) will crop from the top left corner (i.e. if cropping the width, take all of the crop off of the right side, and if cropping the height, take all of it off the bottom). (1.0, 0.0) will crop from the bottom left corner, etc. (i.e. if cropping the width, take all of the crop off the left side, and if cropping the height take none from the top, and therefore all off the bottom). :return: An image. Here is the function: def fit(image, size, method=Image.Resampling.BICUBIC, bleed=0.0, centering=(0.5, 0.5)): """ Returns a resized and cropped version of the image, cropped to the requested aspect ratio and size. This function was contributed by Kevin Cazabon. :param image: The image to resize and crop. :param size: The requested output size in pixels, given as a (width, height) tuple. :param method: Resampling method to use. Default is :py:attr:`~PIL.Image.Resampling.BICUBIC`. See :ref:`concept-filters`. :param bleed: Remove a border around the outside of the image from all four edges. The value is a decimal percentage (use 0.01 for one percent). The default value is 0 (no border). Cannot be greater than or equal to 0.5. :param centering: Control the cropping position. Use (0.5, 0.5) for center cropping (e.g. if cropping the width, take 50% off of the left side, and therefore 50% off the right side). (0.0, 0.0) will crop from the top left corner (i.e. if cropping the width, take all of the crop off of the right side, and if cropping the height, take all of it off the bottom). (1.0, 0.0) will crop from the bottom left corner, etc. (i.e. if cropping the width, take all of the crop off the left side, and if cropping the height take none from the top, and therefore all off the bottom). :return: An image. """ # by Kevin Cazabon, Feb 17/2000 # kevin@cazabon.com # https://www.cazabon.com # ensure centering is mutable centering = list(centering) if not 0.0 <= centering[0] <= 1.0: centering[0] = 0.5 if not 0.0 <= centering[1] <= 1.0: centering[1] = 0.5 if not 0.0 <= bleed < 0.5: bleed = 0.0 # calculate the area to use for resizing and cropping, subtracting # the 'bleed' around the edges # number of pixels to trim off on Top and Bottom, Left and Right bleed_pixels = (bleed * image.size[0], bleed * image.size[1]) live_size = ( image.size[0] - bleed_pixels[0] * 2, image.size[1] - bleed_pixels[1] * 2, ) # calculate the aspect ratio of the live_size live_size_ratio = live_size[0] / live_size[1] # calculate the aspect ratio of the output image output_ratio = size[0] / size[1] # figure out if the sides or top/bottom will be cropped off if live_size_ratio == output_ratio: # live_size is already the needed ratio crop_width = live_size[0] crop_height = live_size[1] elif live_size_ratio >= output_ratio: # live_size is wider than what's needed, crop the sides crop_width = output_ratio * live_size[1] crop_height = live_size[1] else: # live_size is taller than what's needed, crop the top and bottom crop_width = live_size[0] crop_height = live_size[0] / output_ratio # make the crop crop_left = bleed_pixels[0] + (live_size[0] - crop_width) * centering[0] crop_top = bleed_pixels[1] + (live_size[1] - crop_height) * centering[1] crop = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height) # resize the image and return it return image.resize(size, method, box=crop)
Returns a resized and cropped version of the image, cropped to the requested aspect ratio and size. This function was contributed by Kevin Cazabon. :param image: The image to resize and crop. :param size: The requested output size in pixels, given as a (width, height) tuple. :param method: Resampling method to use. Default is :py:attr:`~PIL.Image.Resampling.BICUBIC`. See :ref:`concept-filters`. :param bleed: Remove a border around the outside of the image from all four edges. The value is a decimal percentage (use 0.01 for one percent). The default value is 0 (no border). Cannot be greater than or equal to 0.5. :param centering: Control the cropping position. Use (0.5, 0.5) for center cropping (e.g. if cropping the width, take 50% off of the left side, and therefore 50% off the right side). (0.0, 0.0) will crop from the top left corner (i.e. if cropping the width, take all of the crop off of the right side, and if cropping the height, take all of it off the bottom). (1.0, 0.0) will crop from the bottom left corner, etc. (i.e. if cropping the width, take all of the crop off the left side, and if cropping the height take none from the top, and therefore all off the bottom). :return: An image.
174,071
import functools import operator import re from . import Image, ImagePalette class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": deprecate("Image categories", 10, "is_animated", plural=True) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None def close(self): """ Closes the file pointer, if possible. This operation will destroy the image core and release its memory. The image data will be unusable afterward. This function is required to close images that have multiple frames or have not had their file read and closed by the :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for more information. """ try: if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = DeferredError(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_pretty_(self, p, cycle): """IPython plain text display support""" # Same as __repr__ but without unpredictable id(self), # to keep Jupyter notebook `text/plain` output stable. p.text( "<%s.%s image mode=%s size=%dx%d>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], ) ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: msg = "Could not save to PNG for display" raise ValueError(msg) from e return b.getvalue() def __array_interface__(self): # numpy array interface support new = {"version": 3} try: if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() except Exception as e: if not isinstance(e, (MemoryError, RecursionError)): try: import numpy from packaging.version import parse as parse_version except ImportError: pass else: if parse_version(numpy.__version__) < parse_version("1.23"): warnings.warn(e) raise new["shape"], new["typestr"] = _conv_type_shape(self) return new def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. A list of C encoders can be seen under codecs section of the function array in :file:`_imaging.c`. Python encoders are registered within the relevant plugins. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() if self.width == 0 or self.height == 0: return b"" # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c output = [] while True: bytes_consumed, errcode, data = e.encode(bufsize) output.append(data) if errcode: break if errcode < 0: msg = f"encoder error {errcode} in tobytes" raise RuntimeError(msg) return b"".join(output) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": msg = "not a bitmap" raise ValueError(msg) data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: msg = "not enough image data" raise ValueError(msg) if s[1] != 0: msg = "cannot decode image data" raise ValueError(msg) def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im is not None and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: palette_mode = "RGBA" if mode.startswith("RGBA") else "RGB" self.palette.mode = palette_mode self.palette.palette = self.im.getpalette(palette_mode, palette_mode) if self.im is not None: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK". The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is ``None``, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. When converting from "PA", if an "RGBA" palette is present, the alpha channel from the image will be used instead of the values from the palette. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`Palette.WEB` or :data:`Palette.ADAPTIVE`. :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): msg = "illegal conversion" raise ValueError(msg) im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if (self.mode in ("1", "L", "I") and mode in ("LA", "RGBA")) or ( self.mode == "RGB" and mode == "RGBA" ): # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: msg = "Transparency for P mode should be bytes or int" raise ValueError(msg) if mode == "P" and palette == Palette.ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new if "LAB" in (self.mode, mode): other_mode = mode if self.mode == "LAB" else self.mode if other_mode in ("RGB", "RGBA", "RGBX"): from . import ImageCms srgb = ImageCms.createProfile("sRGB") lab = ImageCms.createProfile("LAB") profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab] transform = ImageCms.buildTransform( profiles[0], profiles[1], self.mode, mode ) return transform.apply(self) # colorspace conversion if dither is None: dither = Dither.FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again modebase = getmodebase(self.mode) if modebase == self.mode: raise im = self.im.convert(modebase) im = im.convert(mode, dither) except KeyError as e: msg = "illegal conversion" raise ValueError(msg) from e new_im = self._new(im) if mode == "P" and palette != Palette.ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`Quantize.MEDIANCUT` (median cut), :data:`Quantize.MAXCOVERAGE` (maximum coverage), :data:`Quantize.FASTOCTREE` (fast octree), :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`Quantize.MEDIANCUT` will be used. The exception to this is RGBA images. :data:`Quantize.MEDIANCUT` and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so :data:`Quantize.FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). :returns: A new image """ self.load() if method is None: # defaults: method = Quantize.MEDIANCUT if self.mode == "RGBA": method = Quantize.FASTOCTREE if self.mode == "RGBA" and method not in ( Quantize.FASTOCTREE, Quantize.LIBIMAGEQUANT, ): # Caller specified an invalid mode. msg = ( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) raise ValueError(msg) if palette: # use palette from reference image palette.load() if palette.mode != "P": msg = "bad mode for palette image" raise ValueError(msg) if self.mode != "RGB" and self.mode != "L": msg = "only RGB or L mode images can be quantized to a palette" raise ValueError(msg) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() if box[2] < box[0]: msg = "Coordinate 'right' is less than 'left'" raise ValueError(msg) elif box[3] < box[1]: msg = "Coordinate 'lower' is less than 'upper'" raise ValueError(msg) self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size in pixels, as a 2-tuple: (width, height). """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): msg = "filter argument should be ImageFilter.Filter instance or class" raise TypeError(msg) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): """ Gets EXIF data from the image. :returns: an :py:class:`~PIL.Image.Exif` object. """ if self._exif is None: self._exif = Exif() self._exif._loaded = False elif self._exif._loaded: return self._exif self._exif._loaded = True exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.bigtiff = self.tag_v2._bigtiff self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation(="|>)([0-9])', xmp_tags) if match: self._exif[0x0112] = int(match[2]) return self._exif def _reload_exif(self): if self._exif is None or not self._exif._loaded: return self._exif._loaded = False self.getexif() def get_child_images(self): child_images = [] exif = self.getexif() ifds = [] if ExifTags.Base.SubIFDs in exif: subifd_offsets = exif[ExifTags.Base.SubIFDs] if subifd_offsets: if not isinstance(subifd_offsets, tuple): subifd_offsets = (subifd_offsets,) for subifd_offset in subifd_offsets: ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset)) ifd1 = exif.get_ifd(ExifTags.IFD.IFD1) if ifd1 and ifd1.get(513): ifds.append((ifd1, exif._info.next)) offset = None for ifd, ifd_offset in ifds: current_offset = self.fp.tell() if offset is None: offset = current_offset fp = self.fp thumbnail_offset = ifd.get(513) if thumbnail_offset is not None: try: thumbnail_offset += self._exif_offset except AttributeError: pass self.fp.seek(thumbnail_offset) data = self.fp.read(ifd.get(514)) fp = io.BytesIO(data) with open(fp) as im: if thumbnail_offset is None: im._frame_pos = [ifd_offset] im._seek(0) im.load() child_images.append(im) if offset is not None: self.fp.seek(offset) return child_images def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self, rawmode="RGB"): """ Returns the image palette as a list. :param rawmode: The mode in which to return the palette. ``None`` will return the palette in its current mode. .. versionadded:: 9.1.0 :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: mode = self.im.getpalettemode() except ValueError: return None # no palette if rawmode is None: rawmode = mode return list(self.im.getpalette(mode, rawmode)) def apply_transparency(self): """ If a P mode image has a "transparency" key in the info dictionary, remove the key and instead apply the transparency to the palette. Otherwise, the image is unchanged. """ if self.mode != "P" or "transparency" not in self.info: return from . import ImagePalette palette = self.getpalette("RGBA") transparency = self.info["transparency"] if isinstance(transparency, bytes): for i, alpha in enumerate(transparency): palette[i * 4 + 3] = alpha else: palette[transparency * 4 + 3] = 0 self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette)) self.palette.dirty = 1 del self.info["transparency"] def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. Counts are grouped into 256 bins for each band, even if the image has more than 8 bits per band. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", "LA", "RGBA" or "RGBa" images (if present, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? msg = "cannot determine region size; use 4-item box" raise ValueError(msg) box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): msg = "Source must be a tuple" raise ValueError(msg) if not isinstance(dest, (list, tuple)): msg = "Destination must be a tuple" raise ValueError(msg) if not len(source) in (2, 4): msg = "Source must be a 2 or 4-tuple" raise ValueError(msg) if not len(dest) == 2: msg = "Destination must be a 2-tuple" raise ValueError(msg) if min(source) < 0: msg = "Source must be non-negative" raise ValueError(msg) if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case msg = "point operation not supported for this mode" raise ValueError(msg) if mode != "F": lut = [round(i) for i in lut] return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: msg = "illegal image mode" raise ValueError(msg) from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): msg = "illegal image mode" raise ValueError(msg) alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): msg = "illegal image mode" raise ValueError(msg) if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P and PA images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode in ("P", "PA") and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P or PA image if self.mode == "PA": alpha = value[3] if len(value) == 4 else 255 value = value[:3] value = self.palette.getcolor(value, self) if self.mode == "PA": value = (value, alpha) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): msg = "illegal image mode" raise ValueError(msg) bands = 3 palette_mode = "RGB" if source_palette is None: if self.mode == "P": self.load() palette_mode = self.im.getpalettemode() if palette_mode == "RGBA": bands = 4 source_palette = self.im.getpalette(palette_mode, palette_mode) else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[ oldPosition * bands : oldPosition * bands + bands ] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette( palette_mode, palette=mapping_palette * bands ) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette(palette_mode + ";L", m_im.palette.tobytes()) m_im = m_im.convert("L") m_im.putpalette(palette_bytes, palette_mode) m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes) if "transparency" in self.info: try: m_im.info["transparency"] = dest_map.index(self.info["transparency"]) except ValueError: if "transparency" in m_im.info: del m_im.info["transparency"] return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`Resampling.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`Resampling.NEAREST`. Otherwise, the default filter is :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = Resampling.NEAREST if type_special else Resampling.BICUBIC elif resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, Resampling.LANCZOS, Resampling.BOX, Resampling.HAMMING, ): msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), (Resampling.BOX, "Image.Resampling.BOX"), (Resampling.HAMMING, "Image.Resampling.HAMMING"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) if reducing_gap is not None and reducing_gap < 1.0: msg = "reducing_gap must be 1.0 or greater" raise ValueError(msg) size = tuple(size) self.load() if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = Resampling.NEAREST if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != Resampling.NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(Transpose.ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose( Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270 ) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform( (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor ) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif is_path(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and is_path(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: msg = f"unknown file extension: {ext}" raise ValueError(msg) from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] created = False if open_fp: created = not os.path.exists(filename) if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) except Exception: if open_fp: fp.close() if created: try: os.remove(filename) except PermissionError: pass raise if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: msg = f'The image has no channel "{channel}"' raise ValueError(msg) from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: Optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If omitted, it defaults to :py:data:`Resampling.BICUBIC`. (was :py:data:`Resampling.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ provided_size = tuple(map(math.floor, size)) def preserve_aspect_ratio(): def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) x, y = provided_size if x >= self.width and y >= self.height: return aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) return x, y box = None if reducing_gap is not None: size = preserve_aspect_ratio() if size is None: return res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if box is None: self.load() # load() may have changed the size of the image size = preserve_aspect_ratio() if size is None: return if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size in pixels, as a 2-tuple: (width, height). :param method: The transformation method. This is one of :py:data:`Transform.EXTENT` (cut out a rectangular subregion), :py:data:`Transform.AFFINE` (affine transform), :py:data:`Transform.PERSPECTIVE` (perspective transform), :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or :py:data:`Transform.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.Transform.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: msg = "missing method data" raise ValueError(msg) im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == Transform.MESH: # list of quads for box, quad in data: im.__transformer( box, self, Transform.QUAD, quad, resample, fillcolor is None ) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): w = box[2] - box[0] h = box[3] - box[1] if method == Transform.AFFINE: data = data[:6] elif method == Transform.EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = Transform.AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == Transform.PERSPECTIVE: data = data[:8] elif method == Transform.QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: msg = "unknown transformation method" raise ValueError(msg) if resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, ): if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS): msg = { Resampling.BOX: "Image.Resampling.BOX", Resampling.HAMMING: "Image.Resampling.HAMMING", Resampling.LANCZOS: "Image.Resampling.LANCZOS", }[resample] + f" ({resample}) cannot be used." else: msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) image.load() self.load() if image.mode in ("1", "P"): resample = Resampling.NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`, :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`, :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`, :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `flip` function. Write a Python function `def flip(image)` to solve the following problem: Flip the image vertically (top to bottom). :param image: The image to flip. :return: An image. Here is the function: def flip(image): """ Flip the image vertically (top to bottom). :param image: The image to flip. :return: An image. """ return image.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
Flip the image vertically (top to bottom). :param image: The image to flip. :return: An image.
174,072
import functools import operator import re from . import Image, ImagePalette The provided code snippet includes necessary dependencies for implementing the `grayscale` function. Write a Python function `def grayscale(image)` to solve the following problem: Convert the image to grayscale. :param image: The image to convert. :return: An image. Here is the function: def grayscale(image): """ Convert the image to grayscale. :param image: The image to convert. :return: An image. """ return image.convert("L")
Convert the image to grayscale. :param image: The image to convert. :return: An image.
174,073
import functools import operator import re from . import Image, ImagePalette class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": deprecate("Image categories", 10, "is_animated", plural=True) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None def close(self): """ Closes the file pointer, if possible. This operation will destroy the image core and release its memory. The image data will be unusable afterward. This function is required to close images that have multiple frames or have not had their file read and closed by the :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for more information. """ try: if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = DeferredError(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_pretty_(self, p, cycle): """IPython plain text display support""" # Same as __repr__ but without unpredictable id(self), # to keep Jupyter notebook `text/plain` output stable. p.text( "<%s.%s image mode=%s size=%dx%d>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], ) ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: msg = "Could not save to PNG for display" raise ValueError(msg) from e return b.getvalue() def __array_interface__(self): # numpy array interface support new = {"version": 3} try: if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() except Exception as e: if not isinstance(e, (MemoryError, RecursionError)): try: import numpy from packaging.version import parse as parse_version except ImportError: pass else: if parse_version(numpy.__version__) < parse_version("1.23"): warnings.warn(e) raise new["shape"], new["typestr"] = _conv_type_shape(self) return new def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. A list of C encoders can be seen under codecs section of the function array in :file:`_imaging.c`. Python encoders are registered within the relevant plugins. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() if self.width == 0 or self.height == 0: return b"" # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c output = [] while True: bytes_consumed, errcode, data = e.encode(bufsize) output.append(data) if errcode: break if errcode < 0: msg = f"encoder error {errcode} in tobytes" raise RuntimeError(msg) return b"".join(output) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": msg = "not a bitmap" raise ValueError(msg) data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: msg = "not enough image data" raise ValueError(msg) if s[1] != 0: msg = "cannot decode image data" raise ValueError(msg) def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im is not None and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: palette_mode = "RGBA" if mode.startswith("RGBA") else "RGB" self.palette.mode = palette_mode self.palette.palette = self.im.getpalette(palette_mode, palette_mode) if self.im is not None: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK". The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is ``None``, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. When converting from "PA", if an "RGBA" palette is present, the alpha channel from the image will be used instead of the values from the palette. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`Palette.WEB` or :data:`Palette.ADAPTIVE`. :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): msg = "illegal conversion" raise ValueError(msg) im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if (self.mode in ("1", "L", "I") and mode in ("LA", "RGBA")) or ( self.mode == "RGB" and mode == "RGBA" ): # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: msg = "Transparency for P mode should be bytes or int" raise ValueError(msg) if mode == "P" and palette == Palette.ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new if "LAB" in (self.mode, mode): other_mode = mode if self.mode == "LAB" else self.mode if other_mode in ("RGB", "RGBA", "RGBX"): from . import ImageCms srgb = ImageCms.createProfile("sRGB") lab = ImageCms.createProfile("LAB") profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab] transform = ImageCms.buildTransform( profiles[0], profiles[1], self.mode, mode ) return transform.apply(self) # colorspace conversion if dither is None: dither = Dither.FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again modebase = getmodebase(self.mode) if modebase == self.mode: raise im = self.im.convert(modebase) im = im.convert(mode, dither) except KeyError as e: msg = "illegal conversion" raise ValueError(msg) from e new_im = self._new(im) if mode == "P" and palette != Palette.ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`Quantize.MEDIANCUT` (median cut), :data:`Quantize.MAXCOVERAGE` (maximum coverage), :data:`Quantize.FASTOCTREE` (fast octree), :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`Quantize.MEDIANCUT` will be used. The exception to this is RGBA images. :data:`Quantize.MEDIANCUT` and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so :data:`Quantize.FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). :returns: A new image """ self.load() if method is None: # defaults: method = Quantize.MEDIANCUT if self.mode == "RGBA": method = Quantize.FASTOCTREE if self.mode == "RGBA" and method not in ( Quantize.FASTOCTREE, Quantize.LIBIMAGEQUANT, ): # Caller specified an invalid mode. msg = ( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) raise ValueError(msg) if palette: # use palette from reference image palette.load() if palette.mode != "P": msg = "bad mode for palette image" raise ValueError(msg) if self.mode != "RGB" and self.mode != "L": msg = "only RGB or L mode images can be quantized to a palette" raise ValueError(msg) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() if box[2] < box[0]: msg = "Coordinate 'right' is less than 'left'" raise ValueError(msg) elif box[3] < box[1]: msg = "Coordinate 'lower' is less than 'upper'" raise ValueError(msg) self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size in pixels, as a 2-tuple: (width, height). """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): msg = "filter argument should be ImageFilter.Filter instance or class" raise TypeError(msg) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): """ Gets EXIF data from the image. :returns: an :py:class:`~PIL.Image.Exif` object. """ if self._exif is None: self._exif = Exif() self._exif._loaded = False elif self._exif._loaded: return self._exif self._exif._loaded = True exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.bigtiff = self.tag_v2._bigtiff self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation(="|>)([0-9])', xmp_tags) if match: self._exif[0x0112] = int(match[2]) return self._exif def _reload_exif(self): if self._exif is None or not self._exif._loaded: return self._exif._loaded = False self.getexif() def get_child_images(self): child_images = [] exif = self.getexif() ifds = [] if ExifTags.Base.SubIFDs in exif: subifd_offsets = exif[ExifTags.Base.SubIFDs] if subifd_offsets: if not isinstance(subifd_offsets, tuple): subifd_offsets = (subifd_offsets,) for subifd_offset in subifd_offsets: ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset)) ifd1 = exif.get_ifd(ExifTags.IFD.IFD1) if ifd1 and ifd1.get(513): ifds.append((ifd1, exif._info.next)) offset = None for ifd, ifd_offset in ifds: current_offset = self.fp.tell() if offset is None: offset = current_offset fp = self.fp thumbnail_offset = ifd.get(513) if thumbnail_offset is not None: try: thumbnail_offset += self._exif_offset except AttributeError: pass self.fp.seek(thumbnail_offset) data = self.fp.read(ifd.get(514)) fp = io.BytesIO(data) with open(fp) as im: if thumbnail_offset is None: im._frame_pos = [ifd_offset] im._seek(0) im.load() child_images.append(im) if offset is not None: self.fp.seek(offset) return child_images def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self, rawmode="RGB"): """ Returns the image palette as a list. :param rawmode: The mode in which to return the palette. ``None`` will return the palette in its current mode. .. versionadded:: 9.1.0 :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: mode = self.im.getpalettemode() except ValueError: return None # no palette if rawmode is None: rawmode = mode return list(self.im.getpalette(mode, rawmode)) def apply_transparency(self): """ If a P mode image has a "transparency" key in the info dictionary, remove the key and instead apply the transparency to the palette. Otherwise, the image is unchanged. """ if self.mode != "P" or "transparency" not in self.info: return from . import ImagePalette palette = self.getpalette("RGBA") transparency = self.info["transparency"] if isinstance(transparency, bytes): for i, alpha in enumerate(transparency): palette[i * 4 + 3] = alpha else: palette[transparency * 4 + 3] = 0 self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette)) self.palette.dirty = 1 del self.info["transparency"] def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. Counts are grouped into 256 bins for each band, even if the image has more than 8 bits per band. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", "LA", "RGBA" or "RGBa" images (if present, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? msg = "cannot determine region size; use 4-item box" raise ValueError(msg) box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): msg = "Source must be a tuple" raise ValueError(msg) if not isinstance(dest, (list, tuple)): msg = "Destination must be a tuple" raise ValueError(msg) if not len(source) in (2, 4): msg = "Source must be a 2 or 4-tuple" raise ValueError(msg) if not len(dest) == 2: msg = "Destination must be a 2-tuple" raise ValueError(msg) if min(source) < 0: msg = "Source must be non-negative" raise ValueError(msg) if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case msg = "point operation not supported for this mode" raise ValueError(msg) if mode != "F": lut = [round(i) for i in lut] return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: msg = "illegal image mode" raise ValueError(msg) from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): msg = "illegal image mode" raise ValueError(msg) alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): msg = "illegal image mode" raise ValueError(msg) if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P and PA images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode in ("P", "PA") and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P or PA image if self.mode == "PA": alpha = value[3] if len(value) == 4 else 255 value = value[:3] value = self.palette.getcolor(value, self) if self.mode == "PA": value = (value, alpha) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): msg = "illegal image mode" raise ValueError(msg) bands = 3 palette_mode = "RGB" if source_palette is None: if self.mode == "P": self.load() palette_mode = self.im.getpalettemode() if palette_mode == "RGBA": bands = 4 source_palette = self.im.getpalette(palette_mode, palette_mode) else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[ oldPosition * bands : oldPosition * bands + bands ] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette( palette_mode, palette=mapping_palette * bands ) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette(palette_mode + ";L", m_im.palette.tobytes()) m_im = m_im.convert("L") m_im.putpalette(palette_bytes, palette_mode) m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes) if "transparency" in self.info: try: m_im.info["transparency"] = dest_map.index(self.info["transparency"]) except ValueError: if "transparency" in m_im.info: del m_im.info["transparency"] return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`Resampling.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`Resampling.NEAREST`. Otherwise, the default filter is :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = Resampling.NEAREST if type_special else Resampling.BICUBIC elif resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, Resampling.LANCZOS, Resampling.BOX, Resampling.HAMMING, ): msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), (Resampling.BOX, "Image.Resampling.BOX"), (Resampling.HAMMING, "Image.Resampling.HAMMING"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) if reducing_gap is not None and reducing_gap < 1.0: msg = "reducing_gap must be 1.0 or greater" raise ValueError(msg) size = tuple(size) self.load() if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = Resampling.NEAREST if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != Resampling.NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(Transpose.ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose( Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270 ) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform( (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor ) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif is_path(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and is_path(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: msg = f"unknown file extension: {ext}" raise ValueError(msg) from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] created = False if open_fp: created = not os.path.exists(filename) if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) except Exception: if open_fp: fp.close() if created: try: os.remove(filename) except PermissionError: pass raise if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: msg = f'The image has no channel "{channel}"' raise ValueError(msg) from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: Optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If omitted, it defaults to :py:data:`Resampling.BICUBIC`. (was :py:data:`Resampling.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ provided_size = tuple(map(math.floor, size)) def preserve_aspect_ratio(): def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) x, y = provided_size if x >= self.width and y >= self.height: return aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) return x, y box = None if reducing_gap is not None: size = preserve_aspect_ratio() if size is None: return res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if box is None: self.load() # load() may have changed the size of the image size = preserve_aspect_ratio() if size is None: return if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size in pixels, as a 2-tuple: (width, height). :param method: The transformation method. This is one of :py:data:`Transform.EXTENT` (cut out a rectangular subregion), :py:data:`Transform.AFFINE` (affine transform), :py:data:`Transform.PERSPECTIVE` (perspective transform), :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or :py:data:`Transform.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.Transform.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: msg = "missing method data" raise ValueError(msg) im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == Transform.MESH: # list of quads for box, quad in data: im.__transformer( box, self, Transform.QUAD, quad, resample, fillcolor is None ) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): w = box[2] - box[0] h = box[3] - box[1] if method == Transform.AFFINE: data = data[:6] elif method == Transform.EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = Transform.AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == Transform.PERSPECTIVE: data = data[:8] elif method == Transform.QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: msg = "unknown transformation method" raise ValueError(msg) if resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, ): if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS): msg = { Resampling.BOX: "Image.Resampling.BOX", Resampling.HAMMING: "Image.Resampling.HAMMING", Resampling.LANCZOS: "Image.Resampling.LANCZOS", }[resample] + f" ({resample}) cannot be used." else: msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) image.load() self.load() if image.mode in ("1", "P"): resample = Resampling.NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`, :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`, :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`, :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `mirror` function. Write a Python function `def mirror(image)` to solve the following problem: Flip image horizontally (left to right). :param image: The image to mirror. :return: An image. Here is the function: def mirror(image): """ Flip image horizontally (left to right). :param image: The image to mirror. :return: An image. """ return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
Flip image horizontally (left to right). :param image: The image to mirror. :return: An image.
174,074
import functools import operator import re from . import Image, ImagePalette def _lut(image, lut): if image.mode == "P": # FIXME: apply to lookup table, not image data msg = "mode P support coming soon" raise NotImplementedError(msg) elif image.mode in ("L", "RGB"): if image.mode == "RGB" and len(lut) == 256: lut = lut + lut + lut return image.point(lut) else: msg = "not supported for this image mode" raise OSError(msg) The provided code snippet includes necessary dependencies for implementing the `posterize` function. Write a Python function `def posterize(image, bits)` to solve the following problem: Reduce the number of bits for each color channel. :param image: The image to posterize. :param bits: The number of bits to keep for each channel (1-8). :return: An image. Here is the function: def posterize(image, bits): """ Reduce the number of bits for each color channel. :param image: The image to posterize. :param bits: The number of bits to keep for each channel (1-8). :return: An image. """ lut = [] mask = ~(2 ** (8 - bits) - 1) for i in range(256): lut.append(i & mask) return _lut(image, lut)
Reduce the number of bits for each color channel. :param image: The image to posterize. :param bits: The number of bits to keep for each channel (1-8). :return: An image.
174,075
import functools import operator import re from . import Image, ImagePalette def _lut(image, lut): if image.mode == "P": # FIXME: apply to lookup table, not image data msg = "mode P support coming soon" raise NotImplementedError(msg) elif image.mode in ("L", "RGB"): if image.mode == "RGB" and len(lut) == 256: lut = lut + lut + lut return image.point(lut) else: msg = "not supported for this image mode" raise OSError(msg) The provided code snippet includes necessary dependencies for implementing the `solarize` function. Write a Python function `def solarize(image, threshold=128)` to solve the following problem: Invert all pixel values above a threshold. :param image: The image to solarize. :param threshold: All pixels above this greyscale level are inverted. :return: An image. Here is the function: def solarize(image, threshold=128): """ Invert all pixel values above a threshold. :param image: The image to solarize. :param threshold: All pixels above this greyscale level are inverted. :return: An image. """ lut = [] for i in range(256): if i < threshold: lut.append(i) else: lut.append(255 - i) return _lut(image, lut)
Invert all pixel values above a threshold. :param image: The image to solarize. :param threshold: All pixels above this greyscale level are inverted. :return: An image.
174,076
import functools import operator import re from . import Image, ImagePalette class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": deprecate("Image categories", 10, "is_animated", plural=True) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None def close(self): """ Closes the file pointer, if possible. This operation will destroy the image core and release its memory. The image data will be unusable afterward. This function is required to close images that have multiple frames or have not had their file read and closed by the :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for more information. """ try: if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = DeferredError(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_pretty_(self, p, cycle): """IPython plain text display support""" # Same as __repr__ but without unpredictable id(self), # to keep Jupyter notebook `text/plain` output stable. p.text( "<%s.%s image mode=%s size=%dx%d>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], ) ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: msg = "Could not save to PNG for display" raise ValueError(msg) from e return b.getvalue() def __array_interface__(self): # numpy array interface support new = {"version": 3} try: if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() except Exception as e: if not isinstance(e, (MemoryError, RecursionError)): try: import numpy from packaging.version import parse as parse_version except ImportError: pass else: if parse_version(numpy.__version__) < parse_version("1.23"): warnings.warn(e) raise new["shape"], new["typestr"] = _conv_type_shape(self) return new def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. A list of C encoders can be seen under codecs section of the function array in :file:`_imaging.c`. Python encoders are registered within the relevant plugins. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() if self.width == 0 or self.height == 0: return b"" # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c output = [] while True: bytes_consumed, errcode, data = e.encode(bufsize) output.append(data) if errcode: break if errcode < 0: msg = f"encoder error {errcode} in tobytes" raise RuntimeError(msg) return b"".join(output) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": msg = "not a bitmap" raise ValueError(msg) data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: msg = "not enough image data" raise ValueError(msg) if s[1] != 0: msg = "cannot decode image data" raise ValueError(msg) def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im is not None and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: palette_mode = "RGBA" if mode.startswith("RGBA") else "RGB" self.palette.mode = palette_mode self.palette.palette = self.im.getpalette(palette_mode, palette_mode) if self.im is not None: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK". The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is ``None``, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. When converting from "PA", if an "RGBA" palette is present, the alpha channel from the image will be used instead of the values from the palette. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`Palette.WEB` or :data:`Palette.ADAPTIVE`. :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): msg = "illegal conversion" raise ValueError(msg) im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if (self.mode in ("1", "L", "I") and mode in ("LA", "RGBA")) or ( self.mode == "RGB" and mode == "RGBA" ): # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: msg = "Transparency for P mode should be bytes or int" raise ValueError(msg) if mode == "P" and palette == Palette.ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new if "LAB" in (self.mode, mode): other_mode = mode if self.mode == "LAB" else self.mode if other_mode in ("RGB", "RGBA", "RGBX"): from . import ImageCms srgb = ImageCms.createProfile("sRGB") lab = ImageCms.createProfile("LAB") profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab] transform = ImageCms.buildTransform( profiles[0], profiles[1], self.mode, mode ) return transform.apply(self) # colorspace conversion if dither is None: dither = Dither.FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again modebase = getmodebase(self.mode) if modebase == self.mode: raise im = self.im.convert(modebase) im = im.convert(mode, dither) except KeyError as e: msg = "illegal conversion" raise ValueError(msg) from e new_im = self._new(im) if mode == "P" and palette != Palette.ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`Quantize.MEDIANCUT` (median cut), :data:`Quantize.MAXCOVERAGE` (maximum coverage), :data:`Quantize.FASTOCTREE` (fast octree), :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`Quantize.MEDIANCUT` will be used. The exception to this is RGBA images. :data:`Quantize.MEDIANCUT` and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so :data:`Quantize.FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). :returns: A new image """ self.load() if method is None: # defaults: method = Quantize.MEDIANCUT if self.mode == "RGBA": method = Quantize.FASTOCTREE if self.mode == "RGBA" and method not in ( Quantize.FASTOCTREE, Quantize.LIBIMAGEQUANT, ): # Caller specified an invalid mode. msg = ( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) raise ValueError(msg) if palette: # use palette from reference image palette.load() if palette.mode != "P": msg = "bad mode for palette image" raise ValueError(msg) if self.mode != "RGB" and self.mode != "L": msg = "only RGB or L mode images can be quantized to a palette" raise ValueError(msg) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() if box[2] < box[0]: msg = "Coordinate 'right' is less than 'left'" raise ValueError(msg) elif box[3] < box[1]: msg = "Coordinate 'lower' is less than 'upper'" raise ValueError(msg) self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size in pixels, as a 2-tuple: (width, height). """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): msg = "filter argument should be ImageFilter.Filter instance or class" raise TypeError(msg) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): """ Gets EXIF data from the image. :returns: an :py:class:`~PIL.Image.Exif` object. """ if self._exif is None: self._exif = Exif() self._exif._loaded = False elif self._exif._loaded: return self._exif self._exif._loaded = True exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.bigtiff = self.tag_v2._bigtiff self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation(="|>)([0-9])', xmp_tags) if match: self._exif[0x0112] = int(match[2]) return self._exif def _reload_exif(self): if self._exif is None or not self._exif._loaded: return self._exif._loaded = False self.getexif() def get_child_images(self): child_images = [] exif = self.getexif() ifds = [] if ExifTags.Base.SubIFDs in exif: subifd_offsets = exif[ExifTags.Base.SubIFDs] if subifd_offsets: if not isinstance(subifd_offsets, tuple): subifd_offsets = (subifd_offsets,) for subifd_offset in subifd_offsets: ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset)) ifd1 = exif.get_ifd(ExifTags.IFD.IFD1) if ifd1 and ifd1.get(513): ifds.append((ifd1, exif._info.next)) offset = None for ifd, ifd_offset in ifds: current_offset = self.fp.tell() if offset is None: offset = current_offset fp = self.fp thumbnail_offset = ifd.get(513) if thumbnail_offset is not None: try: thumbnail_offset += self._exif_offset except AttributeError: pass self.fp.seek(thumbnail_offset) data = self.fp.read(ifd.get(514)) fp = io.BytesIO(data) with open(fp) as im: if thumbnail_offset is None: im._frame_pos = [ifd_offset] im._seek(0) im.load() child_images.append(im) if offset is not None: self.fp.seek(offset) return child_images def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self, rawmode="RGB"): """ Returns the image palette as a list. :param rawmode: The mode in which to return the palette. ``None`` will return the palette in its current mode. .. versionadded:: 9.1.0 :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: mode = self.im.getpalettemode() except ValueError: return None # no palette if rawmode is None: rawmode = mode return list(self.im.getpalette(mode, rawmode)) def apply_transparency(self): """ If a P mode image has a "transparency" key in the info dictionary, remove the key and instead apply the transparency to the palette. Otherwise, the image is unchanged. """ if self.mode != "P" or "transparency" not in self.info: return from . import ImagePalette palette = self.getpalette("RGBA") transparency = self.info["transparency"] if isinstance(transparency, bytes): for i, alpha in enumerate(transparency): palette[i * 4 + 3] = alpha else: palette[transparency * 4 + 3] = 0 self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette)) self.palette.dirty = 1 del self.info["transparency"] def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. Counts are grouped into 256 bins for each band, even if the image has more than 8 bits per band. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", "LA", "RGBA" or "RGBa" images (if present, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? msg = "cannot determine region size; use 4-item box" raise ValueError(msg) box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): msg = "Source must be a tuple" raise ValueError(msg) if not isinstance(dest, (list, tuple)): msg = "Destination must be a tuple" raise ValueError(msg) if not len(source) in (2, 4): msg = "Source must be a 2 or 4-tuple" raise ValueError(msg) if not len(dest) == 2: msg = "Destination must be a 2-tuple" raise ValueError(msg) if min(source) < 0: msg = "Source must be non-negative" raise ValueError(msg) if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case msg = "point operation not supported for this mode" raise ValueError(msg) if mode != "F": lut = [round(i) for i in lut] return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: msg = "illegal image mode" raise ValueError(msg) from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): msg = "illegal image mode" raise ValueError(msg) alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): msg = "illegal image mode" raise ValueError(msg) if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P and PA images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode in ("P", "PA") and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P or PA image if self.mode == "PA": alpha = value[3] if len(value) == 4 else 255 value = value[:3] value = self.palette.getcolor(value, self) if self.mode == "PA": value = (value, alpha) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): msg = "illegal image mode" raise ValueError(msg) bands = 3 palette_mode = "RGB" if source_palette is None: if self.mode == "P": self.load() palette_mode = self.im.getpalettemode() if palette_mode == "RGBA": bands = 4 source_palette = self.im.getpalette(palette_mode, palette_mode) else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[ oldPosition * bands : oldPosition * bands + bands ] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette( palette_mode, palette=mapping_palette * bands ) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette(palette_mode + ";L", m_im.palette.tobytes()) m_im = m_im.convert("L") m_im.putpalette(palette_bytes, palette_mode) m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes) if "transparency" in self.info: try: m_im.info["transparency"] = dest_map.index(self.info["transparency"]) except ValueError: if "transparency" in m_im.info: del m_im.info["transparency"] return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`Resampling.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`Resampling.NEAREST`. Otherwise, the default filter is :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = Resampling.NEAREST if type_special else Resampling.BICUBIC elif resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, Resampling.LANCZOS, Resampling.BOX, Resampling.HAMMING, ): msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), (Resampling.BOX, "Image.Resampling.BOX"), (Resampling.HAMMING, "Image.Resampling.HAMMING"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) if reducing_gap is not None and reducing_gap < 1.0: msg = "reducing_gap must be 1.0 or greater" raise ValueError(msg) size = tuple(size) self.load() if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = Resampling.NEAREST if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != Resampling.NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(Transpose.ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose( Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270 ) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform( (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor ) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif is_path(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and is_path(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: msg = f"unknown file extension: {ext}" raise ValueError(msg) from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] created = False if open_fp: created = not os.path.exists(filename) if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) except Exception: if open_fp: fp.close() if created: try: os.remove(filename) except PermissionError: pass raise if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: msg = f'The image has no channel "{channel}"' raise ValueError(msg) from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: Optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If omitted, it defaults to :py:data:`Resampling.BICUBIC`. (was :py:data:`Resampling.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ provided_size = tuple(map(math.floor, size)) def preserve_aspect_ratio(): def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) x, y = provided_size if x >= self.width and y >= self.height: return aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) return x, y box = None if reducing_gap is not None: size = preserve_aspect_ratio() if size is None: return res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if box is None: self.load() # load() may have changed the size of the image size = preserve_aspect_ratio() if size is None: return if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size in pixels, as a 2-tuple: (width, height). :param method: The transformation method. This is one of :py:data:`Transform.EXTENT` (cut out a rectangular subregion), :py:data:`Transform.AFFINE` (affine transform), :py:data:`Transform.PERSPECTIVE` (perspective transform), :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or :py:data:`Transform.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.Transform.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: msg = "missing method data" raise ValueError(msg) im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == Transform.MESH: # list of quads for box, quad in data: im.__transformer( box, self, Transform.QUAD, quad, resample, fillcolor is None ) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): w = box[2] - box[0] h = box[3] - box[1] if method == Transform.AFFINE: data = data[:6] elif method == Transform.EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = Transform.AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == Transform.PERSPECTIVE: data = data[:8] elif method == Transform.QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: msg = "unknown transformation method" raise ValueError(msg) if resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, ): if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS): msg = { Resampling.BOX: "Image.Resampling.BOX", Resampling.HAMMING: "Image.Resampling.HAMMING", Resampling.LANCZOS: "Image.Resampling.LANCZOS", }[resample] + f" ({resample}) cannot be used." else: msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) image.load() self.load() if image.mode in ("1", "P"): resample = Resampling.NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`, :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`, :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`, :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `exif_transpose` function. Write a Python function `def exif_transpose(image)` to solve the following problem: If an image has an EXIF Orientation tag, other than 1, return a new image that is transposed accordingly. The new image will have the orientation data removed. Otherwise, return a copy of the image. :param image: The image to transpose. :return: An image. Here is the function: def exif_transpose(image): """ If an image has an EXIF Orientation tag, other than 1, return a new image that is transposed accordingly. The new image will have the orientation data removed. Otherwise, return a copy of the image. :param image: The image to transpose. :return: An image. """ exif = image.getexif() orientation = exif.get(0x0112) method = { 2: Image.Transpose.FLIP_LEFT_RIGHT, 3: Image.Transpose.ROTATE_180, 4: Image.Transpose.FLIP_TOP_BOTTOM, 5: Image.Transpose.TRANSPOSE, 6: Image.Transpose.ROTATE_270, 7: Image.Transpose.TRANSVERSE, 8: Image.Transpose.ROTATE_90, }.get(orientation) if method is not None: transposed_image = image.transpose(method) transposed_exif = transposed_image.getexif() if 0x0112 in transposed_exif: del transposed_exif[0x0112] if "exif" in transposed_image.info: transposed_image.info["exif"] = transposed_exif.tobytes() elif "Raw profile type exif" in transposed_image.info: transposed_image.info[ "Raw profile type exif" ] = transposed_exif.tobytes().hex() elif "XML:com.adobe.xmp" in transposed_image.info: for pattern in ( r'tiff:Orientation="([0-9])"', r"<tiff:Orientation>([0-9])</tiff:Orientation>", ): transposed_image.info["XML:com.adobe.xmp"] = re.sub( pattern, "", transposed_image.info["XML:com.adobe.xmp"] ) return transposed_image return image.copy()
If an image has an EXIF Orientation tag, other than 1, return a new image that is transposed accordingly. The new image will have the orientation data removed. Otherwise, return a copy of the image. :param image: The image to transpose. :return: An image.
174,079
import io import os import re import subprocess import sys import tempfile from . import Image, ImageFile from ._binary import i32le as i32 from ._deprecate import deprecate gs_windows_binary = None if sys.platform.startswith("win"): import shutil for binary in ("gswin32c", "gswin64c", "gs"): if shutil.which(binary) is not None: gs_windows_binary = binary break else: gs_windows_binary = False def has_ghostscript(): if gs_windows_binary: return True if not sys.platform.startswith("win"): try: subprocess.check_call(["gs", "--version"], stdout=subprocess.DEVNULL) return True except OSError: # No Ghostscript pass return False
null
174,080
import io import os import re import subprocess import sys import tempfile from . import Image, ImageFile from ._binary import i32le as i32 from ._deprecate import deprecate gs_windows_binary = None if sys.platform.startswith("win"): import shutil for binary in ("gswin32c", "gswin64c", "gs"): if shutil.which(binary) is not None: gs_windows_binary = binary break else: gs_windows_binary = False Image.register_open(EpsImageFile.format, EpsImageFile, _accept) Image.register_save(EpsImageFile.format, _save) Image.register_extensions(EpsImageFile.format, [".ps", ".eps"]) Image.register_mime(EpsImageFile.format, "application/postscript") class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": deprecate("Image categories", 10, "is_animated", plural=True) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None def close(self): """ Closes the file pointer, if possible. This operation will destroy the image core and release its memory. The image data will be unusable afterward. This function is required to close images that have multiple frames or have not had their file read and closed by the :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for more information. """ try: if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = DeferredError(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_pretty_(self, p, cycle): """IPython plain text display support""" # Same as __repr__ but without unpredictable id(self), # to keep Jupyter notebook `text/plain` output stable. p.text( "<%s.%s image mode=%s size=%dx%d>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], ) ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: msg = "Could not save to PNG for display" raise ValueError(msg) from e return b.getvalue() def __array_interface__(self): # numpy array interface support new = {"version": 3} try: if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() except Exception as e: if not isinstance(e, (MemoryError, RecursionError)): try: import numpy from packaging.version import parse as parse_version except ImportError: pass else: if parse_version(numpy.__version__) < parse_version("1.23"): warnings.warn(e) raise new["shape"], new["typestr"] = _conv_type_shape(self) return new def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. A list of C encoders can be seen under codecs section of the function array in :file:`_imaging.c`. Python encoders are registered within the relevant plugins. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() if self.width == 0 or self.height == 0: return b"" # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c output = [] while True: bytes_consumed, errcode, data = e.encode(bufsize) output.append(data) if errcode: break if errcode < 0: msg = f"encoder error {errcode} in tobytes" raise RuntimeError(msg) return b"".join(output) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": msg = "not a bitmap" raise ValueError(msg) data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: msg = "not enough image data" raise ValueError(msg) if s[1] != 0: msg = "cannot decode image data" raise ValueError(msg) def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im is not None and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: palette_mode = "RGBA" if mode.startswith("RGBA") else "RGB" self.palette.mode = palette_mode self.palette.palette = self.im.getpalette(palette_mode, palette_mode) if self.im is not None: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK". The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is ``None``, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. When converting from "PA", if an "RGBA" palette is present, the alpha channel from the image will be used instead of the values from the palette. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`Palette.WEB` or :data:`Palette.ADAPTIVE`. :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): msg = "illegal conversion" raise ValueError(msg) im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if (self.mode in ("1", "L", "I") and mode in ("LA", "RGBA")) or ( self.mode == "RGB" and mode == "RGBA" ): # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: msg = "Transparency for P mode should be bytes or int" raise ValueError(msg) if mode == "P" and palette == Palette.ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new if "LAB" in (self.mode, mode): other_mode = mode if self.mode == "LAB" else self.mode if other_mode in ("RGB", "RGBA", "RGBX"): from . import ImageCms srgb = ImageCms.createProfile("sRGB") lab = ImageCms.createProfile("LAB") profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab] transform = ImageCms.buildTransform( profiles[0], profiles[1], self.mode, mode ) return transform.apply(self) # colorspace conversion if dither is None: dither = Dither.FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again modebase = getmodebase(self.mode) if modebase == self.mode: raise im = self.im.convert(modebase) im = im.convert(mode, dither) except KeyError as e: msg = "illegal conversion" raise ValueError(msg) from e new_im = self._new(im) if mode == "P" and palette != Palette.ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`Quantize.MEDIANCUT` (median cut), :data:`Quantize.MAXCOVERAGE` (maximum coverage), :data:`Quantize.FASTOCTREE` (fast octree), :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`Quantize.MEDIANCUT` will be used. The exception to this is RGBA images. :data:`Quantize.MEDIANCUT` and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so :data:`Quantize.FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). :returns: A new image """ self.load() if method is None: # defaults: method = Quantize.MEDIANCUT if self.mode == "RGBA": method = Quantize.FASTOCTREE if self.mode == "RGBA" and method not in ( Quantize.FASTOCTREE, Quantize.LIBIMAGEQUANT, ): # Caller specified an invalid mode. msg = ( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) raise ValueError(msg) if palette: # use palette from reference image palette.load() if palette.mode != "P": msg = "bad mode for palette image" raise ValueError(msg) if self.mode != "RGB" and self.mode != "L": msg = "only RGB or L mode images can be quantized to a palette" raise ValueError(msg) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() if box[2] < box[0]: msg = "Coordinate 'right' is less than 'left'" raise ValueError(msg) elif box[3] < box[1]: msg = "Coordinate 'lower' is less than 'upper'" raise ValueError(msg) self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size in pixels, as a 2-tuple: (width, height). """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): msg = "filter argument should be ImageFilter.Filter instance or class" raise TypeError(msg) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): """ Gets EXIF data from the image. :returns: an :py:class:`~PIL.Image.Exif` object. """ if self._exif is None: self._exif = Exif() self._exif._loaded = False elif self._exif._loaded: return self._exif self._exif._loaded = True exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.bigtiff = self.tag_v2._bigtiff self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation(="|>)([0-9])', xmp_tags) if match: self._exif[0x0112] = int(match[2]) return self._exif def _reload_exif(self): if self._exif is None or not self._exif._loaded: return self._exif._loaded = False self.getexif() def get_child_images(self): child_images = [] exif = self.getexif() ifds = [] if ExifTags.Base.SubIFDs in exif: subifd_offsets = exif[ExifTags.Base.SubIFDs] if subifd_offsets: if not isinstance(subifd_offsets, tuple): subifd_offsets = (subifd_offsets,) for subifd_offset in subifd_offsets: ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset)) ifd1 = exif.get_ifd(ExifTags.IFD.IFD1) if ifd1 and ifd1.get(513): ifds.append((ifd1, exif._info.next)) offset = None for ifd, ifd_offset in ifds: current_offset = self.fp.tell() if offset is None: offset = current_offset fp = self.fp thumbnail_offset = ifd.get(513) if thumbnail_offset is not None: try: thumbnail_offset += self._exif_offset except AttributeError: pass self.fp.seek(thumbnail_offset) data = self.fp.read(ifd.get(514)) fp = io.BytesIO(data) with open(fp) as im: if thumbnail_offset is None: im._frame_pos = [ifd_offset] im._seek(0) im.load() child_images.append(im) if offset is not None: self.fp.seek(offset) return child_images def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self, rawmode="RGB"): """ Returns the image palette as a list. :param rawmode: The mode in which to return the palette. ``None`` will return the palette in its current mode. .. versionadded:: 9.1.0 :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: mode = self.im.getpalettemode() except ValueError: return None # no palette if rawmode is None: rawmode = mode return list(self.im.getpalette(mode, rawmode)) def apply_transparency(self): """ If a P mode image has a "transparency" key in the info dictionary, remove the key and instead apply the transparency to the palette. Otherwise, the image is unchanged. """ if self.mode != "P" or "transparency" not in self.info: return from . import ImagePalette palette = self.getpalette("RGBA") transparency = self.info["transparency"] if isinstance(transparency, bytes): for i, alpha in enumerate(transparency): palette[i * 4 + 3] = alpha else: palette[transparency * 4 + 3] = 0 self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette)) self.palette.dirty = 1 del self.info["transparency"] def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. Counts are grouped into 256 bins for each band, even if the image has more than 8 bits per band. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", "LA", "RGBA" or "RGBa" images (if present, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? msg = "cannot determine region size; use 4-item box" raise ValueError(msg) box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): msg = "Source must be a tuple" raise ValueError(msg) if not isinstance(dest, (list, tuple)): msg = "Destination must be a tuple" raise ValueError(msg) if not len(source) in (2, 4): msg = "Source must be a 2 or 4-tuple" raise ValueError(msg) if not len(dest) == 2: msg = "Destination must be a 2-tuple" raise ValueError(msg) if min(source) < 0: msg = "Source must be non-negative" raise ValueError(msg) if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case msg = "point operation not supported for this mode" raise ValueError(msg) if mode != "F": lut = [round(i) for i in lut] return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: msg = "illegal image mode" raise ValueError(msg) from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): msg = "illegal image mode" raise ValueError(msg) alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): msg = "illegal image mode" raise ValueError(msg) if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P and PA images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode in ("P", "PA") and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P or PA image if self.mode == "PA": alpha = value[3] if len(value) == 4 else 255 value = value[:3] value = self.palette.getcolor(value, self) if self.mode == "PA": value = (value, alpha) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): msg = "illegal image mode" raise ValueError(msg) bands = 3 palette_mode = "RGB" if source_palette is None: if self.mode == "P": self.load() palette_mode = self.im.getpalettemode() if palette_mode == "RGBA": bands = 4 source_palette = self.im.getpalette(palette_mode, palette_mode) else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[ oldPosition * bands : oldPosition * bands + bands ] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette( palette_mode, palette=mapping_palette * bands ) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette(palette_mode + ";L", m_im.palette.tobytes()) m_im = m_im.convert("L") m_im.putpalette(palette_bytes, palette_mode) m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes) if "transparency" in self.info: try: m_im.info["transparency"] = dest_map.index(self.info["transparency"]) except ValueError: if "transparency" in m_im.info: del m_im.info["transparency"] return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`Resampling.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`Resampling.NEAREST`. Otherwise, the default filter is :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = Resampling.NEAREST if type_special else Resampling.BICUBIC elif resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, Resampling.LANCZOS, Resampling.BOX, Resampling.HAMMING, ): msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), (Resampling.BOX, "Image.Resampling.BOX"), (Resampling.HAMMING, "Image.Resampling.HAMMING"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) if reducing_gap is not None and reducing_gap < 1.0: msg = "reducing_gap must be 1.0 or greater" raise ValueError(msg) size = tuple(size) self.load() if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = Resampling.NEAREST if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != Resampling.NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(Transpose.ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose( Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270 ) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform( (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor ) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif is_path(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and is_path(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: msg = f"unknown file extension: {ext}" raise ValueError(msg) from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] created = False if open_fp: created = not os.path.exists(filename) if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) except Exception: if open_fp: fp.close() if created: try: os.remove(filename) except PermissionError: pass raise if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: msg = f'The image has no channel "{channel}"' raise ValueError(msg) from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: Optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If omitted, it defaults to :py:data:`Resampling.BICUBIC`. (was :py:data:`Resampling.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ provided_size = tuple(map(math.floor, size)) def preserve_aspect_ratio(): def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) x, y = provided_size if x >= self.width and y >= self.height: return aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) return x, y box = None if reducing_gap is not None: size = preserve_aspect_ratio() if size is None: return res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if box is None: self.load() # load() may have changed the size of the image size = preserve_aspect_ratio() if size is None: return if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size in pixels, as a 2-tuple: (width, height). :param method: The transformation method. This is one of :py:data:`Transform.EXTENT` (cut out a rectangular subregion), :py:data:`Transform.AFFINE` (affine transform), :py:data:`Transform.PERSPECTIVE` (perspective transform), :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or :py:data:`Transform.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.Transform.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: msg = "missing method data" raise ValueError(msg) im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == Transform.MESH: # list of quads for box, quad in data: im.__transformer( box, self, Transform.QUAD, quad, resample, fillcolor is None ) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): w = box[2] - box[0] h = box[3] - box[1] if method == Transform.AFFINE: data = data[:6] elif method == Transform.EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = Transform.AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == Transform.PERSPECTIVE: data = data[:8] elif method == Transform.QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: msg = "unknown transformation method" raise ValueError(msg) if resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, ): if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS): msg = { Resampling.BOX: "Image.Resampling.BOX", Resampling.HAMMING: "Image.Resampling.HAMMING", Resampling.LANCZOS: "Image.Resampling.LANCZOS", }[resample] + f" ({resample}) cannot be used." else: msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) image.load() self.load() if image.mode in ("1", "P"): resample = Resampling.NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`, :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`, :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`, :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `Ghostscript` function. Write a Python function `def Ghostscript(tile, size, fp, scale=1, transparency=False)` to solve the following problem: Render an image using Ghostscript Here is the function: def Ghostscript(tile, size, fp, scale=1, transparency=False): """Render an image using Ghostscript""" # Unpack decoder tile decoder, tile, offset, data = tile[0] length, bbox = data # Hack to support hi-res rendering scale = int(scale) or 1 # orig_size = size # orig_bbox = bbox size = (size[0] * scale, size[1] * scale) # resolution is dependent on bbox and size res = ( 72.0 * size[0] / (bbox[2] - bbox[0]), 72.0 * size[1] / (bbox[3] - bbox[1]), ) out_fd, outfile = tempfile.mkstemp() os.close(out_fd) infile_temp = None if hasattr(fp, "name") and os.path.exists(fp.name): infile = fp.name else: in_fd, infile_temp = tempfile.mkstemp() os.close(in_fd) infile = infile_temp # Ignore length and offset! # Ghostscript can read it # Copy whole file to read in Ghostscript with open(infile_temp, "wb") as f: # fetch length of fp fp.seek(0, io.SEEK_END) fsize = fp.tell() # ensure start position # go back fp.seek(0) lengthfile = fsize while lengthfile > 0: s = fp.read(min(lengthfile, 100 * 1024)) if not s: break lengthfile -= len(s) f.write(s) device = "pngalpha" if transparency else "ppmraw" # Build Ghostscript command command = [ "gs", "-q", # quiet mode "-g%dx%d" % size, # set output geometry (pixels) "-r%fx%f" % res, # set input DPI (dots per inch) "-dBATCH", # exit after processing "-dNOPAUSE", # don't pause between pages "-dSAFER", # safe mode f"-sDEVICE={device}", f"-sOutputFile={outfile}", # output file # adjust for image origin "-c", f"{-bbox[0]} {-bbox[1]} translate", "-f", infile, # input file # showpage (see https://bugs.ghostscript.com/show_bug.cgi?id=698272) "-c", "showpage", ] if gs_windows_binary is not None: if not gs_windows_binary: msg = "Unable to locate Ghostscript on paths" raise OSError(msg) command[0] = gs_windows_binary # push data through Ghostscript try: startupinfo = None if sys.platform.startswith("win"): startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW subprocess.check_call(command, startupinfo=startupinfo) out_im = Image.open(outfile) out_im.load() finally: try: os.unlink(outfile) if infile_temp: os.unlink(infile_temp) except OSError: pass im = out_im.im.copy() out_im.close() return im
Render an image using Ghostscript
174,081
import io import os import re import subprocess import sys import tempfile from . import Image, ImageFile from ._binary import i32le as i32 from ._deprecate import deprecate def _accept(prefix): return prefix[:4] == b"%!PS" or (len(prefix) >= 4 and i32(prefix) == 0xC6D3D0C5)
null
174,082
import io import os import re import subprocess import sys import tempfile from . import Image, ImageFile from ._binary import i32le as i32 from ._deprecate import deprecate class ImageFile(Image.Image): """Base class for image file format handlers.""" def __init__(self, fp=None, filename=None): super().__init__() self._min_frame = 0 self.custom_mimetype = None self.tile = None """ A list of tile descriptors, or ``None`` """ self.readonly = 1 # until we know better self.decoderconfig = () self.decodermaxblock = MAXBLOCK if is_path(fp): # filename self.fp = open(fp, "rb") self.filename = fp self._exclusive_fp = True else: # stream self.fp = fp self.filename = filename # can be overridden self._exclusive_fp = None try: try: self._open() except ( IndexError, # end of data TypeError, # end of data (ord) KeyError, # unsupported mode EOFError, # got header but not the first frame struct.error, ) as v: raise SyntaxError(v) from v if not self.mode or self.size[0] <= 0 or self.size[1] <= 0: msg = "not identified by this driver" raise SyntaxError(msg) except BaseException: # close the file only if we have opened it this constructor if self._exclusive_fp: self.fp.close() raise def get_format_mimetype(self): if self.custom_mimetype: return self.custom_mimetype if self.format is not None: return Image.MIME.get(self.format.upper()) def __setstate__(self, state): self.tile = [] super().__setstate__(state) def verify(self): """Check file integrity""" # raise exception if something's wrong. must be called # directly after open, and closes file when finished. if self._exclusive_fp: self.fp.close() self.fp = None def load(self): """Load image data based on tile list""" if self.tile is None: msg = "cannot load this image" raise OSError(msg) pixel = Image.Image.load(self) if not self.tile: return pixel self.map = None use_mmap = self.filename and len(self.tile) == 1 # As of pypy 2.1.0, memory mapping was failing here. use_mmap = use_mmap and not hasattr(sys, "pypy_version_info") readonly = 0 # look for read/seek overrides try: read = self.load_read # don't use mmap if there are custom read/seek functions use_mmap = False except AttributeError: read = self.fp.read try: seek = self.load_seek use_mmap = False except AttributeError: seek = self.fp.seek if use_mmap: # try memory mapping decoder_name, extents, offset, args = self.tile[0] if ( decoder_name == "raw" and len(args) >= 3 and args[0] == self.mode and args[0] in Image._MAPMODES ): try: # use mmap, if possible import mmap with open(self.filename) as fp: self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ) if offset + self.size[1] * args[1] > self.map.size(): # buffer is not large enough raise OSError self.im = Image.core.map_buffer( self.map, self.size, decoder_name, offset, args ) readonly = 1 # After trashing self.im, # we might need to reload the palette data. if self.palette: self.palette.dirty = 1 except (AttributeError, OSError, ImportError): self.map = None self.load_prepare() err_code = -3 # initialize to unknown error if not self.map: # sort tiles in file order self.tile.sort(key=_tilesort) try: # FIXME: This is a hack to handle TIFF's JpegTables tag. prefix = self.tile_prefix except AttributeError: prefix = b"" # Remove consecutive duplicates that only differ by their offset self.tile = [ list(tiles)[-1] for _, tiles in itertools.groupby( self.tile, lambda tile: (tile[0], tile[1], tile[3]) ) ] for decoder_name, extents, offset, args in self.tile: seek(offset) decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) err_code = decoder.decode(b"")[1] else: b = prefix while True: try: s = read(self.decodermaxblock) except (IndexError, struct.error) as e: # truncated png/gif if LOAD_TRUNCATED_IMAGES: break else: msg = "image file is truncated" raise OSError(msg) from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: msg = ( "image file is truncated " f"({len(b)} bytes not processed)" ) raise OSError(msg) b = b + s n, err_code = decoder.decode(b) if n < 0: break b = b[n:] finally: # Need to cleanup here to prevent leaks decoder.cleanup() self.tile = [] self.readonly = readonly self.load_end() if self._exclusive_fp and self._close_exclusive_fp_after_loading: self.fp.close() self.fp = None if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0: # still raised if decoder fails to return anything raise_oserror(err_code) return Image.Image.load(self) def load_prepare(self): # create image memory if necessary if not self.im or self.im.mode != self.mode or self.im.size != self.size: self.im = Image.core.new(self.mode, self.size) # create palette (optional) if self.mode == "P": Image.Image.load(self) def load_end(self): # may be overridden pass # may be defined for contained formats # def load_seek(self, pos): # pass # may be defined for blocked formats (e.g. PNG) # def load_read(self, bytes): # pass def _seek_check(self, frame): if ( frame < self._min_frame # Only check upper limit on frames if additional seek operations # are not required to do so or ( not (hasattr(self, "_n_frames") and self._n_frames is None) and frame >= self.n_frames + self._min_frame ) ): msg = "attempt to seek outside sequence" raise EOFError(msg) return self.tell() != frame The provided code snippet includes necessary dependencies for implementing the `_save` function. Write a Python function `def _save(im, fp, filename, eps=1)` to solve the following problem: EPS Writer for the Python Imaging Library. Here is the function: def _save(im, fp, filename, eps=1): """EPS Writer for the Python Imaging Library.""" # make sure image data is available im.load() # determine PostScript image mode if im.mode == "L": operator = (8, 1, b"image") elif im.mode == "RGB": operator = (8, 3, b"false 3 colorimage") elif im.mode == "CMYK": operator = (8, 4, b"false 4 colorimage") else: msg = "image mode is not supported" raise ValueError(msg) if eps: # write EPS header fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n") fp.write(b"%%Creator: PIL 0.1 EpsEncode\n") # fp.write("%%CreationDate: %s"...) fp.write(b"%%%%BoundingBox: 0 0 %d %d\n" % im.size) fp.write(b"%%Pages: 1\n") fp.write(b"%%EndComments\n") fp.write(b"%%Page: 1 1\n") fp.write(b"%%ImageData: %d %d " % im.size) fp.write(b'%d %d 0 1 1 "%s"\n' % operator) # image header fp.write(b"gsave\n") fp.write(b"10 dict begin\n") fp.write(b"/buf %d string def\n" % (im.size[0] * operator[1])) fp.write(b"%d %d scale\n" % im.size) fp.write(b"%d %d 8\n" % im.size) # <= bits fp.write(b"[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1])) fp.write(b"{ currentfile buf readhexstring pop } bind\n") fp.write(operator[2] + b"\n") if hasattr(fp, "flush"): fp.flush() ImageFile._save(im, fp, [("eps", (0, 0) + im.size, 0, None)]) fp.write(b"\n%%%%EndBinary\n") fp.write(b"grestore end\n") if hasattr(fp, "flush"): fp.flush()
EPS Writer for the Python Imaging Library.
174,083
from . import FontFile, Image class Image: def __init__(self): def __getattr__(self, name): def width(self): def height(self): def size(self): def _new(self, im): def __enter__(self): def __exit__(self, *args): def close(self): def _copy(self): def _ensure_mutable(self): def _dump(self, file=None, format=None, **options): def __eq__(self, other): def __repr__(self): def _repr_pretty_(self, p, cycle): def _repr_png_(self): def __array_interface__(self): def __getstate__(self): def __setstate__(self, state): def tobytes(self, encoder_name="raw", *args): def tobitmap(self, name="image"): def frombytes(self, data, decoder_name="raw", *args): def load(self): def verify(self): def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): def convert_transparency(m, v): def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): def copy(self): def crop(self, box=None): def _crop(self, im, box): def draft(self, mode, size): def _expand(self, xmargin, ymargin=None): def filter(self, filter): def getbands(self): def getbbox(self): def getcolors(self, maxcolors=256): def getdata(self, band=None): def getextrema(self): def _getxmp(self, xmp_tags): def get_name(tag): def get_value(element): def getexif(self): def _reload_exif(self): def get_child_images(self): def getim(self): def getpalette(self, rawmode="RGB"): def apply_transparency(self): def getpixel(self, xy): def getprojection(self): def histogram(self, mask=None, extrema=None): def entropy(self, mask=None, extrema=None): def paste(self, im, box=None, mask=None): def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): def point(self, lut, mode=None): def putalpha(self, alpha): def putdata(self, data, scale=1.0, offset=0.0): def putpalette(self, data, rawmode="RGB"): def putpixel(self, xy, value): def remap_palette(self, dest_map, source_palette=None): def _get_safe_box(self, size, resample, box): def resize(self, size, resample=None, box=None, reducing_gap=None): def reduce(self, factor, box=None): def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): def transform(x, y, matrix): def save(self, fp, format=None, **params): def seek(self, frame): def show(self, title=None): def split(self): def getchannel(self, channel): def tell(self): def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): def preserve_aspect_ratio(): def round_aspect(number, key): def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): def transpose(self, method): def effect_spread(self, distance): def toqimage(self): def toqpixmap(self): def bdf_char(f): # skip to STARTCHAR while True: s = f.readline() if not s: return None if s[:9] == b"STARTCHAR": break id = s[9:].strip().decode("ascii") # load symbol properties props = {} while True: s = f.readline() if not s or s[:6] == b"BITMAP": break i = s.find(b" ") props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii") # load bitmap bitmap = [] while True: s = f.readline() if not s or s[:7] == b"ENDCHAR": break bitmap.append(s[:-1]) bitmap = b"".join(bitmap) # The word BBX # followed by the width in x (BBw), height in y (BBh), # and x and y displacement (BBxoff0, BByoff0) # of the lower left corner from the origin of the character. width, height, x_disp, y_disp = [int(p) for p in props["BBX"].split()] # The word DWIDTH # followed by the width in x and y of the character in device pixels. dwx, dwy = [int(p) for p in props["DWIDTH"].split()] bbox = ( (dwx, dwy), (x_disp, -y_disp - height, width + x_disp, -y_disp), (0, 0, width, height), ) try: im = Image.frombytes("1", (width, height), bitmap, "hex", "1") except ValueError: # deal with zero-width characters im = Image.new("1", (width, height)) return id, int(props["ENCODING"]), bbox, im
null
174,084
import warnings from . import Image, ImageFile, ImagePalette from ._binary import i16le as i16 from ._binary import o8 from ._binary import o16le as o16 SAVE = { "1": ("1", 1, 0, 3), "L": ("L", 8, 0, 3), "LA": ("LA", 16, 0, 3), "P": ("P", 8, 1, 1), "RGB": ("BGR", 24, 0, 2), "RGBA": ("BGRA", 32, 0, 2), } class ImageFile(Image.Image): """Base class for image file format handlers.""" def __init__(self, fp=None, filename=None): super().__init__() self._min_frame = 0 self.custom_mimetype = None self.tile = None """ A list of tile descriptors, or ``None`` """ self.readonly = 1 # until we know better self.decoderconfig = () self.decodermaxblock = MAXBLOCK if is_path(fp): # filename self.fp = open(fp, "rb") self.filename = fp self._exclusive_fp = True else: # stream self.fp = fp self.filename = filename # can be overridden self._exclusive_fp = None try: try: self._open() except ( IndexError, # end of data TypeError, # end of data (ord) KeyError, # unsupported mode EOFError, # got header but not the first frame struct.error, ) as v: raise SyntaxError(v) from v if not self.mode or self.size[0] <= 0 or self.size[1] <= 0: msg = "not identified by this driver" raise SyntaxError(msg) except BaseException: # close the file only if we have opened it this constructor if self._exclusive_fp: self.fp.close() raise def get_format_mimetype(self): if self.custom_mimetype: return self.custom_mimetype if self.format is not None: return Image.MIME.get(self.format.upper()) def __setstate__(self, state): self.tile = [] super().__setstate__(state) def verify(self): """Check file integrity""" # raise exception if something's wrong. must be called # directly after open, and closes file when finished. if self._exclusive_fp: self.fp.close() self.fp = None def load(self): """Load image data based on tile list""" if self.tile is None: msg = "cannot load this image" raise OSError(msg) pixel = Image.Image.load(self) if not self.tile: return pixel self.map = None use_mmap = self.filename and len(self.tile) == 1 # As of pypy 2.1.0, memory mapping was failing here. use_mmap = use_mmap and not hasattr(sys, "pypy_version_info") readonly = 0 # look for read/seek overrides try: read = self.load_read # don't use mmap if there are custom read/seek functions use_mmap = False except AttributeError: read = self.fp.read try: seek = self.load_seek use_mmap = False except AttributeError: seek = self.fp.seek if use_mmap: # try memory mapping decoder_name, extents, offset, args = self.tile[0] if ( decoder_name == "raw" and len(args) >= 3 and args[0] == self.mode and args[0] in Image._MAPMODES ): try: # use mmap, if possible import mmap with open(self.filename) as fp: self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ) if offset + self.size[1] * args[1] > self.map.size(): # buffer is not large enough raise OSError self.im = Image.core.map_buffer( self.map, self.size, decoder_name, offset, args ) readonly = 1 # After trashing self.im, # we might need to reload the palette data. if self.palette: self.palette.dirty = 1 except (AttributeError, OSError, ImportError): self.map = None self.load_prepare() err_code = -3 # initialize to unknown error if not self.map: # sort tiles in file order self.tile.sort(key=_tilesort) try: # FIXME: This is a hack to handle TIFF's JpegTables tag. prefix = self.tile_prefix except AttributeError: prefix = b"" # Remove consecutive duplicates that only differ by their offset self.tile = [ list(tiles)[-1] for _, tiles in itertools.groupby( self.tile, lambda tile: (tile[0], tile[1], tile[3]) ) ] for decoder_name, extents, offset, args in self.tile: seek(offset) decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) err_code = decoder.decode(b"")[1] else: b = prefix while True: try: s = read(self.decodermaxblock) except (IndexError, struct.error) as e: # truncated png/gif if LOAD_TRUNCATED_IMAGES: break else: msg = "image file is truncated" raise OSError(msg) from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: msg = ( "image file is truncated " f"({len(b)} bytes not processed)" ) raise OSError(msg) b = b + s n, err_code = decoder.decode(b) if n < 0: break b = b[n:] finally: # Need to cleanup here to prevent leaks decoder.cleanup() self.tile = [] self.readonly = readonly self.load_end() if self._exclusive_fp and self._close_exclusive_fp_after_loading: self.fp.close() self.fp = None if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0: # still raised if decoder fails to return anything raise_oserror(err_code) return Image.Image.load(self) def load_prepare(self): # create image memory if necessary if not self.im or self.im.mode != self.mode or self.im.size != self.size: self.im = Image.core.new(self.mode, self.size) # create palette (optional) if self.mode == "P": Image.Image.load(self) def load_end(self): # may be overridden pass # may be defined for contained formats # def load_seek(self, pos): # pass # may be defined for blocked formats (e.g. PNG) # def load_read(self, bytes): # pass def _seek_check(self, frame): if ( frame < self._min_frame # Only check upper limit on frames if additional seek operations # are not required to do so or ( not (hasattr(self, "_n_frames") and self._n_frames is None) and frame >= self.n_frames + self._min_frame ) ): msg = "attempt to seek outside sequence" raise EOFError(msg) return self.tell() != frame def o8(i): return bytes((i & 255,)) def _save(im, fp, filename): try: rawmode, bits, colormaptype, imagetype = SAVE[im.mode] except KeyError as e: msg = f"cannot write mode {im.mode} as TGA" raise OSError(msg) from e if "rle" in im.encoderinfo: rle = im.encoderinfo["rle"] else: compression = im.encoderinfo.get("compression", im.info.get("compression")) rle = compression == "tga_rle" if rle: imagetype += 8 id_section = im.encoderinfo.get("id_section", im.info.get("id_section", "")) id_len = len(id_section) if id_len > 255: id_len = 255 id_section = id_section[:255] warnings.warn("id_section has been trimmed to 255 characters") if colormaptype: palette = im.im.getpalette("RGB", "BGR") colormaplength, colormapentry = len(palette) // 3, 24 else: colormaplength, colormapentry = 0, 0 if im.mode in ("LA", "RGBA"): flags = 8 else: flags = 0 orientation = im.encoderinfo.get("orientation", im.info.get("orientation", -1)) if orientation > 0: flags = flags | 0x20 fp.write( o8(id_len) + o8(colormaptype) + o8(imagetype) + o16(0) # colormapfirst + o16(colormaplength) + o8(colormapentry) + o16(0) + o16(0) + o16(im.size[0]) + o16(im.size[1]) + o8(bits) + o8(flags) ) if id_section: fp.write(id_section) if colormaptype: fp.write(palette) if rle: ImageFile._save( im, fp, [("tga_rle", (0, 0) + im.size, 0, (rawmode, orientation))] ) else: ImageFile._save( im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, orientation))] ) # write targa version 2 footer fp.write(b"\000" * 8 + b"TRUEVISION-XFILE." + b"\000")
null
174,086
from . import Image, ImageFile def _accept(prefix): return prefix[:4] == b"GRIB" and prefix[7] == 1
null
174,087
from . import Image, ImageFile _handler = None def _save(im, fp, filename): if _handler is None or not hasattr(_handler, "save"): msg = "GRIB save handler not installed" raise OSError(msg) _handler.save(im, fp, filename)
null
174,089
import builtins from . import Image, _imagingmath class _Operand: """Wraps an image operand, providing standard operators""" def __init__(self, im): self.im = im def __fixup(self, im1): # convert image to suitable mode if isinstance(im1, _Operand): # argument was an image. if im1.im.mode in ("1", "L"): return im1.im.convert("I") elif im1.im.mode in ("I", "F"): return im1.im else: msg = f"unsupported mode: {im1.im.mode}" raise ValueError(msg) else: # argument was a constant if _isconstant(im1) and self.im.mode in ("1", "L", "I"): return Image.new("I", self.im.size, im1) else: return Image.new("F", self.im.size, im1) def apply(self, op, im1, im2=None, mode=None): im1 = self.__fixup(im1) if im2 is None: # unary operation out = Image.new(mode or im1.mode, im1.size, None) im1.load() try: op = getattr(_imagingmath, op + "_" + im1.mode) except AttributeError as e: msg = f"bad operand type for '{op}'" raise TypeError(msg) from e _imagingmath.unop(op, out.im.id, im1.im.id) else: # binary operation im2 = self.__fixup(im2) if im1.mode != im2.mode: # convert both arguments to floating point if im1.mode != "F": im1 = im1.convert("F") if im2.mode != "F": im2 = im2.convert("F") if im1.size != im2.size: # crop both arguments to a common size size = (min(im1.size[0], im2.size[0]), min(im1.size[1], im2.size[1])) if im1.size != size: im1 = im1.crop((0, 0) + size) if im2.size != size: im2 = im2.crop((0, 0) + size) out = Image.new(mode or im1.mode, im1.size, None) im1.load() im2.load() try: op = getattr(_imagingmath, op + "_" + im1.mode) except AttributeError as e: msg = f"bad operand type for '{op}'" raise TypeError(msg) from e _imagingmath.binop(op, out.im.id, im1.im.id, im2.im.id) return _Operand(out) # unary operators def __bool__(self): # an image is "true" if it contains at least one non-zero pixel return self.im.getbbox() is not None def __abs__(self): return self.apply("abs", self) def __pos__(self): return self def __neg__(self): return self.apply("neg", self) # binary operators def __add__(self, other): return self.apply("add", self, other) def __radd__(self, other): return self.apply("add", other, self) def __sub__(self, other): return self.apply("sub", self, other) def __rsub__(self, other): return self.apply("sub", other, self) def __mul__(self, other): return self.apply("mul", self, other) def __rmul__(self, other): return self.apply("mul", other, self) def __truediv__(self, other): return self.apply("div", self, other) def __rtruediv__(self, other): return self.apply("div", other, self) def __mod__(self, other): return self.apply("mod", self, other) def __rmod__(self, other): return self.apply("mod", other, self) def __pow__(self, other): return self.apply("pow", self, other) def __rpow__(self, other): return self.apply("pow", other, self) # bitwise def __invert__(self): return self.apply("invert", self) def __and__(self, other): return self.apply("and", self, other) def __rand__(self, other): return self.apply("and", other, self) def __or__(self, other): return self.apply("or", self, other) def __ror__(self, other): return self.apply("or", other, self) def __xor__(self, other): return self.apply("xor", self, other) def __rxor__(self, other): return self.apply("xor", other, self) def __lshift__(self, other): return self.apply("lshift", self, other) def __rshift__(self, other): return self.apply("rshift", self, other) # logical def __eq__(self, other): return self.apply("eq", self, other) def __ne__(self, other): return self.apply("ne", self, other) def __lt__(self, other): return self.apply("lt", self, other) def __le__(self, other): return self.apply("le", self, other) def __gt__(self, other): return self.apply("gt", self, other) def __ge__(self, other): return self.apply("ge", self, other) def imagemath_int(self): return _Operand(self.im.convert("I"))
null
174,090
import builtins from . import Image, _imagingmath class _Operand: """Wraps an image operand, providing standard operators""" def __init__(self, im): self.im = im def __fixup(self, im1): # convert image to suitable mode if isinstance(im1, _Operand): # argument was an image. if im1.im.mode in ("1", "L"): return im1.im.convert("I") elif im1.im.mode in ("I", "F"): return im1.im else: msg = f"unsupported mode: {im1.im.mode}" raise ValueError(msg) else: # argument was a constant if _isconstant(im1) and self.im.mode in ("1", "L", "I"): return Image.new("I", self.im.size, im1) else: return Image.new("F", self.im.size, im1) def apply(self, op, im1, im2=None, mode=None): im1 = self.__fixup(im1) if im2 is None: # unary operation out = Image.new(mode or im1.mode, im1.size, None) im1.load() try: op = getattr(_imagingmath, op + "_" + im1.mode) except AttributeError as e: msg = f"bad operand type for '{op}'" raise TypeError(msg) from e _imagingmath.unop(op, out.im.id, im1.im.id) else: # binary operation im2 = self.__fixup(im2) if im1.mode != im2.mode: # convert both arguments to floating point if im1.mode != "F": im1 = im1.convert("F") if im2.mode != "F": im2 = im2.convert("F") if im1.size != im2.size: # crop both arguments to a common size size = (min(im1.size[0], im2.size[0]), min(im1.size[1], im2.size[1])) if im1.size != size: im1 = im1.crop((0, 0) + size) if im2.size != size: im2 = im2.crop((0, 0) + size) out = Image.new(mode or im1.mode, im1.size, None) im1.load() im2.load() try: op = getattr(_imagingmath, op + "_" + im1.mode) except AttributeError as e: msg = f"bad operand type for '{op}'" raise TypeError(msg) from e _imagingmath.binop(op, out.im.id, im1.im.id, im2.im.id) return _Operand(out) # unary operators def __bool__(self): # an image is "true" if it contains at least one non-zero pixel return self.im.getbbox() is not None def __abs__(self): return self.apply("abs", self) def __pos__(self): return self def __neg__(self): return self.apply("neg", self) # binary operators def __add__(self, other): return self.apply("add", self, other) def __radd__(self, other): return self.apply("add", other, self) def __sub__(self, other): return self.apply("sub", self, other) def __rsub__(self, other): return self.apply("sub", other, self) def __mul__(self, other): return self.apply("mul", self, other) def __rmul__(self, other): return self.apply("mul", other, self) def __truediv__(self, other): return self.apply("div", self, other) def __rtruediv__(self, other): return self.apply("div", other, self) def __mod__(self, other): return self.apply("mod", self, other) def __rmod__(self, other): return self.apply("mod", other, self) def __pow__(self, other): return self.apply("pow", self, other) def __rpow__(self, other): return self.apply("pow", other, self) # bitwise def __invert__(self): return self.apply("invert", self) def __and__(self, other): return self.apply("and", self, other) def __rand__(self, other): return self.apply("and", other, self) def __or__(self, other): return self.apply("or", self, other) def __ror__(self, other): return self.apply("or", other, self) def __xor__(self, other): return self.apply("xor", self, other) def __rxor__(self, other): return self.apply("xor", other, self) def __lshift__(self, other): return self.apply("lshift", self, other) def __rshift__(self, other): return self.apply("rshift", self, other) # logical def __eq__(self, other): return self.apply("eq", self, other) def __ne__(self, other): return self.apply("ne", self, other) def __lt__(self, other): return self.apply("lt", self, other) def __le__(self, other): return self.apply("le", self, other) def __gt__(self, other): return self.apply("gt", self, other) def __ge__(self, other): return self.apply("ge", self, other) def imagemath_float(self): return _Operand(self.im.convert("F"))
null
174,095
import builtins from . import Image, _imagingmath class _Operand: def __init__(self, im): def __fixup(self, im1): def apply(self, op, im1, im2=None, mode=None): def __bool__(self): def __abs__(self): def __pos__(self): def __neg__(self): def __add__(self, other): def __radd__(self, other): def __sub__(self, other): def __rsub__(self, other): def __mul__(self, other): def __rmul__(self, other): def __truediv__(self, other): def __rtruediv__(self, other): def __mod__(self, other): def __rmod__(self, other): def __pow__(self, other): def __rpow__(self, other): def __invert__(self): def __and__(self, other): def __rand__(self, other): def __or__(self, other): def __ror__(self, other): def __xor__(self, other): def __rxor__(self, other): def __lshift__(self, other): def __rshift__(self, other): def __eq__(self, other): def __ne__(self, other): def __lt__(self, other): def __le__(self, other): def __gt__(self, other): def __ge__(self, other): def imagemath_convert(self, mode): return _Operand(self.im.convert(mode))
null
174,096
import builtins from . import Image, _imagingmath class _Operand: """Wraps an image operand, providing standard operators""" def __init__(self, im): self.im = im def __fixup(self, im1): # convert image to suitable mode if isinstance(im1, _Operand): # argument was an image. if im1.im.mode in ("1", "L"): return im1.im.convert("I") elif im1.im.mode in ("I", "F"): return im1.im else: msg = f"unsupported mode: {im1.im.mode}" raise ValueError(msg) else: # argument was a constant if _isconstant(im1) and self.im.mode in ("1", "L", "I"): return Image.new("I", self.im.size, im1) else: return Image.new("F", self.im.size, im1) def apply(self, op, im1, im2=None, mode=None): im1 = self.__fixup(im1) if im2 is None: # unary operation out = Image.new(mode or im1.mode, im1.size, None) im1.load() try: op = getattr(_imagingmath, op + "_" + im1.mode) except AttributeError as e: msg = f"bad operand type for '{op}'" raise TypeError(msg) from e _imagingmath.unop(op, out.im.id, im1.im.id) else: # binary operation im2 = self.__fixup(im2) if im1.mode != im2.mode: # convert both arguments to floating point if im1.mode != "F": im1 = im1.convert("F") if im2.mode != "F": im2 = im2.convert("F") if im1.size != im2.size: # crop both arguments to a common size size = (min(im1.size[0], im2.size[0]), min(im1.size[1], im2.size[1])) if im1.size != size: im1 = im1.crop((0, 0) + size) if im2.size != size: im2 = im2.crop((0, 0) + size) out = Image.new(mode or im1.mode, im1.size, None) im1.load() im2.load() try: op = getattr(_imagingmath, op + "_" + im1.mode) except AttributeError as e: msg = f"bad operand type for '{op}'" raise TypeError(msg) from e _imagingmath.binop(op, out.im.id, im1.im.id, im2.im.id) return _Operand(out) # unary operators def __bool__(self): # an image is "true" if it contains at least one non-zero pixel return self.im.getbbox() is not None def __abs__(self): return self.apply("abs", self) def __pos__(self): return self def __neg__(self): return self.apply("neg", self) # binary operators def __add__(self, other): return self.apply("add", self, other) def __radd__(self, other): return self.apply("add", other, self) def __sub__(self, other): return self.apply("sub", self, other) def __rsub__(self, other): return self.apply("sub", other, self) def __mul__(self, other): return self.apply("mul", self, other) def __rmul__(self, other): return self.apply("mul", other, self) def __truediv__(self, other): return self.apply("div", self, other) def __rtruediv__(self, other): return self.apply("div", other, self) def __mod__(self, other): return self.apply("mod", self, other) def __rmod__(self, other): return self.apply("mod", other, self) def __pow__(self, other): return self.apply("pow", self, other) def __rpow__(self, other): return self.apply("pow", other, self) # bitwise def __invert__(self): return self.apply("invert", self) def __and__(self, other): return self.apply("and", self, other) def __rand__(self, other): return self.apply("and", other, self) def __or__(self, other): return self.apply("or", self, other) def __ror__(self, other): return self.apply("or", other, self) def __xor__(self, other): return self.apply("xor", self, other) def __rxor__(self, other): return self.apply("xor", other, self) def __lshift__(self, other): return self.apply("lshift", self, other) def __rshift__(self, other): return self.apply("rshift", self, other) # logical def __eq__(self, other): return self.apply("eq", self, other) def __ne__(self, other): return self.apply("ne", self, other) def __lt__(self, other): return self.apply("lt", self, other) def __le__(self, other): return self.apply("le", self, other) def __gt__(self, other): return self.apply("gt", self, other) def __ge__(self, other): return self.apply("ge", self, other) ops = {} for k, v in list(globals().items()): if k[:10] == "imagemath_": ops[k[10:]] = v The provided code snippet includes necessary dependencies for implementing the `eval` function. Write a Python function `def eval(expression, _dict={}, **kw)` to solve the following problem: Evaluates an image expression. :param expression: A string containing a Python-style expression. :param options: Values to add to the evaluation context. You can either use a dictionary, or one or more keyword arguments. :return: The evaluated expression. This is usually an image object, but can also be an integer, a floating point value, or a pixel tuple, depending on the expression. Here is the function: def eval(expression, _dict={}, **kw): """ Evaluates an image expression. :param expression: A string containing a Python-style expression. :param options: Values to add to the evaluation context. You can either use a dictionary, or one or more keyword arguments. :return: The evaluated expression. This is usually an image object, but can also be an integer, a floating point value, or a pixel tuple, depending on the expression. """ # build execution namespace args = ops.copy() args.update(_dict) args.update(kw) for k, v in list(args.items()): if hasattr(v, "im"): args[k] = _Operand(v) compiled_code = compile(expression, "<string>", "eval") def scan(code): for const in code.co_consts: if type(const) == type(compiled_code): scan(const) for name in code.co_names: if name not in args and name != "abs": msg = f"'{name}' not allowed" raise ValueError(msg) scan(compiled_code) out = builtins.eval(expression, {"__builtins": {"abs": abs}}, args) try: return out.im except AttributeError: return out
Evaluates an image expression. :param expression: A string containing a Python-style expression. :param options: Values to add to the evaluation context. You can either use a dictionary, or one or more keyword arguments. :return: The evaluated expression. This is usually an image object, but can also be an integer, a floating point value, or a pixel tuple, depending on the expression.
174,097
import sys from io import BytesIO from . import Image from ._deprecate import deprecate from ._util import is_path def fromqimage(im): """ :param im: QImage or PIL ImageQt object """ buffer = QBuffer() if qt_version == "6": try: qt_openmode = QIODevice.OpenModeFlag except AttributeError: qt_openmode = QIODevice.OpenMode else: qt_openmode = QIODevice buffer.open(qt_openmode.ReadWrite) # preserve alpha channel with png # otherwise ppm is more friendly with Image.open if im.hasAlphaChannel(): im.save(buffer, "png") else: im.save(buffer, "ppm") b = BytesIO() b.write(buffer.data()) buffer.close() b.seek(0) return Image.open(b) def fromqpixmap(im): return fromqimage(im) # buffer = QBuffer() # buffer.open(QIODevice.ReadWrite) # # im.save(buffer) # # What if png doesn't support some image features like animation? # im.save(buffer, 'ppm') # bytes_io = BytesIO() # bytes_io.write(buffer.data()) # buffer.close() # bytes_io.seek(0) # return Image.open(bytes_io)
null
174,098
import sys from io import BytesIO from . import Image from ._deprecate import deprecate from ._util import is_path for qt_version, qt_module in qt_versions: try: if qt_module == "PyQt6": from PyQt6.QtCore import QBuffer, QIODevice from PyQt6.QtGui import QImage, QPixmap, qRgba elif qt_module == "PySide6": from PySide6.QtCore import QBuffer, QIODevice from PySide6.QtGui import QImage, QPixmap, qRgba elif qt_module == "PyQt5": from PyQt5.QtCore import QBuffer, QIODevice from PyQt5.QtGui import QImage, QPixmap, qRgba deprecate("Support for PyQt5", 10, "PyQt6 or PySide6") elif qt_module == "PySide2": from PySide2.QtCore import QBuffer, QIODevice from PySide2.QtGui import QImage, QPixmap, qRgba deprecate("Support for PySide2", 10, "PyQt6 or PySide6") except (ImportError, RuntimeError): continue qt_is_installed = True break else: qt_is_installed = False qt_version = None def rgb(r, g, b, a=255): """(Internal) Turns an RGB color into a Qt compatible color integer.""" # use qRgb to pack the colors, and then turn the resulting long # into a negative integer with the same bitpattern. return qRgba(r, g, b, a) & 0xFFFFFFFF def align8to32(bytes, width, mode): """ converts each scanline of data from 8 bit to 32 bit aligned """ bits_per_pixel = {"1": 1, "L": 8, "P": 8, "I;16": 16}[mode] # calculate bytes per line and the extra padding if needed bits_per_line = bits_per_pixel * width full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8) bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0) extra_padding = -bytes_per_line % 4 # already 32 bit aligned by luck if not extra_padding: return bytes new_data = [] for i in range(len(bytes) // bytes_per_line): new_data.append( bytes[i * bytes_per_line : (i + 1) * bytes_per_line] + b"\x00" * extra_padding ) return b"".join(new_data) class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": deprecate("Image categories", 10, "is_animated", plural=True) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None def close(self): """ Closes the file pointer, if possible. This operation will destroy the image core and release its memory. The image data will be unusable afterward. This function is required to close images that have multiple frames or have not had their file read and closed by the :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for more information. """ try: if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = DeferredError(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_pretty_(self, p, cycle): """IPython plain text display support""" # Same as __repr__ but without unpredictable id(self), # to keep Jupyter notebook `text/plain` output stable. p.text( "<%s.%s image mode=%s size=%dx%d>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], ) ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: msg = "Could not save to PNG for display" raise ValueError(msg) from e return b.getvalue() def __array_interface__(self): # numpy array interface support new = {"version": 3} try: if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() except Exception as e: if not isinstance(e, (MemoryError, RecursionError)): try: import numpy from packaging.version import parse as parse_version except ImportError: pass else: if parse_version(numpy.__version__) < parse_version("1.23"): warnings.warn(e) raise new["shape"], new["typestr"] = _conv_type_shape(self) return new def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. A list of C encoders can be seen under codecs section of the function array in :file:`_imaging.c`. Python encoders are registered within the relevant plugins. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() if self.width == 0 or self.height == 0: return b"" # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c output = [] while True: bytes_consumed, errcode, data = e.encode(bufsize) output.append(data) if errcode: break if errcode < 0: msg = f"encoder error {errcode} in tobytes" raise RuntimeError(msg) return b"".join(output) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": msg = "not a bitmap" raise ValueError(msg) data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: msg = "not enough image data" raise ValueError(msg) if s[1] != 0: msg = "cannot decode image data" raise ValueError(msg) def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im is not None and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: palette_mode = "RGBA" if mode.startswith("RGBA") else "RGB" self.palette.mode = palette_mode self.palette.palette = self.im.getpalette(palette_mode, palette_mode) if self.im is not None: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK". The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is ``None``, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. When converting from "PA", if an "RGBA" palette is present, the alpha channel from the image will be used instead of the values from the palette. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`Palette.WEB` or :data:`Palette.ADAPTIVE`. :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): msg = "illegal conversion" raise ValueError(msg) im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if (self.mode in ("1", "L", "I") and mode in ("LA", "RGBA")) or ( self.mode == "RGB" and mode == "RGBA" ): # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: msg = "Transparency for P mode should be bytes or int" raise ValueError(msg) if mode == "P" and palette == Palette.ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new if "LAB" in (self.mode, mode): other_mode = mode if self.mode == "LAB" else self.mode if other_mode in ("RGB", "RGBA", "RGBX"): from . import ImageCms srgb = ImageCms.createProfile("sRGB") lab = ImageCms.createProfile("LAB") profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab] transform = ImageCms.buildTransform( profiles[0], profiles[1], self.mode, mode ) return transform.apply(self) # colorspace conversion if dither is None: dither = Dither.FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again modebase = getmodebase(self.mode) if modebase == self.mode: raise im = self.im.convert(modebase) im = im.convert(mode, dither) except KeyError as e: msg = "illegal conversion" raise ValueError(msg) from e new_im = self._new(im) if mode == "P" and palette != Palette.ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`Quantize.MEDIANCUT` (median cut), :data:`Quantize.MAXCOVERAGE` (maximum coverage), :data:`Quantize.FASTOCTREE` (fast octree), :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`Quantize.MEDIANCUT` will be used. The exception to this is RGBA images. :data:`Quantize.MEDIANCUT` and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so :data:`Quantize.FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). :returns: A new image """ self.load() if method is None: # defaults: method = Quantize.MEDIANCUT if self.mode == "RGBA": method = Quantize.FASTOCTREE if self.mode == "RGBA" and method not in ( Quantize.FASTOCTREE, Quantize.LIBIMAGEQUANT, ): # Caller specified an invalid mode. msg = ( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) raise ValueError(msg) if palette: # use palette from reference image palette.load() if palette.mode != "P": msg = "bad mode for palette image" raise ValueError(msg) if self.mode != "RGB" and self.mode != "L": msg = "only RGB or L mode images can be quantized to a palette" raise ValueError(msg) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() if box[2] < box[0]: msg = "Coordinate 'right' is less than 'left'" raise ValueError(msg) elif box[3] < box[1]: msg = "Coordinate 'lower' is less than 'upper'" raise ValueError(msg) self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size in pixels, as a 2-tuple: (width, height). """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): msg = "filter argument should be ImageFilter.Filter instance or class" raise TypeError(msg) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): """ Gets EXIF data from the image. :returns: an :py:class:`~PIL.Image.Exif` object. """ if self._exif is None: self._exif = Exif() self._exif._loaded = False elif self._exif._loaded: return self._exif self._exif._loaded = True exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.bigtiff = self.tag_v2._bigtiff self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation(="|>)([0-9])', xmp_tags) if match: self._exif[0x0112] = int(match[2]) return self._exif def _reload_exif(self): if self._exif is None or not self._exif._loaded: return self._exif._loaded = False self.getexif() def get_child_images(self): child_images = [] exif = self.getexif() ifds = [] if ExifTags.Base.SubIFDs in exif: subifd_offsets = exif[ExifTags.Base.SubIFDs] if subifd_offsets: if not isinstance(subifd_offsets, tuple): subifd_offsets = (subifd_offsets,) for subifd_offset in subifd_offsets: ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset)) ifd1 = exif.get_ifd(ExifTags.IFD.IFD1) if ifd1 and ifd1.get(513): ifds.append((ifd1, exif._info.next)) offset = None for ifd, ifd_offset in ifds: current_offset = self.fp.tell() if offset is None: offset = current_offset fp = self.fp thumbnail_offset = ifd.get(513) if thumbnail_offset is not None: try: thumbnail_offset += self._exif_offset except AttributeError: pass self.fp.seek(thumbnail_offset) data = self.fp.read(ifd.get(514)) fp = io.BytesIO(data) with open(fp) as im: if thumbnail_offset is None: im._frame_pos = [ifd_offset] im._seek(0) im.load() child_images.append(im) if offset is not None: self.fp.seek(offset) return child_images def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self, rawmode="RGB"): """ Returns the image palette as a list. :param rawmode: The mode in which to return the palette. ``None`` will return the palette in its current mode. .. versionadded:: 9.1.0 :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: mode = self.im.getpalettemode() except ValueError: return None # no palette if rawmode is None: rawmode = mode return list(self.im.getpalette(mode, rawmode)) def apply_transparency(self): """ If a P mode image has a "transparency" key in the info dictionary, remove the key and instead apply the transparency to the palette. Otherwise, the image is unchanged. """ if self.mode != "P" or "transparency" not in self.info: return from . import ImagePalette palette = self.getpalette("RGBA") transparency = self.info["transparency"] if isinstance(transparency, bytes): for i, alpha in enumerate(transparency): palette[i * 4 + 3] = alpha else: palette[transparency * 4 + 3] = 0 self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette)) self.palette.dirty = 1 del self.info["transparency"] def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. Counts are grouped into 256 bins for each band, even if the image has more than 8 bits per band. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", "LA", "RGBA" or "RGBa" images (if present, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? msg = "cannot determine region size; use 4-item box" raise ValueError(msg) box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): msg = "Source must be a tuple" raise ValueError(msg) if not isinstance(dest, (list, tuple)): msg = "Destination must be a tuple" raise ValueError(msg) if not len(source) in (2, 4): msg = "Source must be a 2 or 4-tuple" raise ValueError(msg) if not len(dest) == 2: msg = "Destination must be a 2-tuple" raise ValueError(msg) if min(source) < 0: msg = "Source must be non-negative" raise ValueError(msg) if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case msg = "point operation not supported for this mode" raise ValueError(msg) if mode != "F": lut = [round(i) for i in lut] return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: msg = "illegal image mode" raise ValueError(msg) from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): msg = "illegal image mode" raise ValueError(msg) alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): msg = "illegal image mode" raise ValueError(msg) if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P and PA images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode in ("P", "PA") and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P or PA image if self.mode == "PA": alpha = value[3] if len(value) == 4 else 255 value = value[:3] value = self.palette.getcolor(value, self) if self.mode == "PA": value = (value, alpha) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): msg = "illegal image mode" raise ValueError(msg) bands = 3 palette_mode = "RGB" if source_palette is None: if self.mode == "P": self.load() palette_mode = self.im.getpalettemode() if palette_mode == "RGBA": bands = 4 source_palette = self.im.getpalette(palette_mode, palette_mode) else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[ oldPosition * bands : oldPosition * bands + bands ] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette( palette_mode, palette=mapping_palette * bands ) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette(palette_mode + ";L", m_im.palette.tobytes()) m_im = m_im.convert("L") m_im.putpalette(palette_bytes, palette_mode) m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes) if "transparency" in self.info: try: m_im.info["transparency"] = dest_map.index(self.info["transparency"]) except ValueError: if "transparency" in m_im.info: del m_im.info["transparency"] return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`Resampling.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`Resampling.NEAREST`. Otherwise, the default filter is :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = Resampling.NEAREST if type_special else Resampling.BICUBIC elif resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, Resampling.LANCZOS, Resampling.BOX, Resampling.HAMMING, ): msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), (Resampling.BOX, "Image.Resampling.BOX"), (Resampling.HAMMING, "Image.Resampling.HAMMING"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) if reducing_gap is not None and reducing_gap < 1.0: msg = "reducing_gap must be 1.0 or greater" raise ValueError(msg) size = tuple(size) self.load() if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = Resampling.NEAREST if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != Resampling.NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(Transpose.ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose( Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270 ) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform( (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor ) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif is_path(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and is_path(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: msg = f"unknown file extension: {ext}" raise ValueError(msg) from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] created = False if open_fp: created = not os.path.exists(filename) if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) except Exception: if open_fp: fp.close() if created: try: os.remove(filename) except PermissionError: pass raise if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: msg = f'The image has no channel "{channel}"' raise ValueError(msg) from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: Optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If omitted, it defaults to :py:data:`Resampling.BICUBIC`. (was :py:data:`Resampling.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ provided_size = tuple(map(math.floor, size)) def preserve_aspect_ratio(): def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) x, y = provided_size if x >= self.width and y >= self.height: return aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) return x, y box = None if reducing_gap is not None: size = preserve_aspect_ratio() if size is None: return res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if box is None: self.load() # load() may have changed the size of the image size = preserve_aspect_ratio() if size is None: return if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size in pixels, as a 2-tuple: (width, height). :param method: The transformation method. This is one of :py:data:`Transform.EXTENT` (cut out a rectangular subregion), :py:data:`Transform.AFFINE` (affine transform), :py:data:`Transform.PERSPECTIVE` (perspective transform), :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or :py:data:`Transform.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.Transform.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: msg = "missing method data" raise ValueError(msg) im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == Transform.MESH: # list of quads for box, quad in data: im.__transformer( box, self, Transform.QUAD, quad, resample, fillcolor is None ) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): w = box[2] - box[0] h = box[3] - box[1] if method == Transform.AFFINE: data = data[:6] elif method == Transform.EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = Transform.AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == Transform.PERSPECTIVE: data = data[:8] elif method == Transform.QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: msg = "unknown transformation method" raise ValueError(msg) if resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, ): if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS): msg = { Resampling.BOX: "Image.Resampling.BOX", Resampling.HAMMING: "Image.Resampling.HAMMING", Resampling.LANCZOS: "Image.Resampling.LANCZOS", }[resample] + f" ({resample}) cannot be used." else: msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) image.load() self.load() if image.mode in ("1", "P"): resample = Resampling.NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`, :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`, :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`, :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqpixmap(self) def is_path(f): return isinstance(f, (bytes, str, Path)) def _toqclass_helper(im): data = None colortable = None exclusive_fp = False # handle filename, if given instead of image name if hasattr(im, "toUtf8"): # FIXME - is this really the best way to do this? im = str(im.toUtf8(), "utf-8") if is_path(im): im = Image.open(im) exclusive_fp = True qt_format = QImage.Format if qt_version == "6" else QImage if im.mode == "1": format = qt_format.Format_Mono elif im.mode == "L": format = qt_format.Format_Indexed8 colortable = [] for i in range(256): colortable.append(rgb(i, i, i)) elif im.mode == "P": format = qt_format.Format_Indexed8 colortable = [] palette = im.getpalette() for i in range(0, len(palette), 3): colortable.append(rgb(*palette[i : i + 3])) elif im.mode == "RGB": # Populate the 4th channel with 255 im = im.convert("RGBA") data = im.tobytes("raw", "BGRA") format = qt_format.Format_RGB32 elif im.mode == "RGBA": data = im.tobytes("raw", "BGRA") format = qt_format.Format_ARGB32 elif im.mode == "I;16" and hasattr(qt_format, "Format_Grayscale16"): # Qt 5.13+ im = im.point(lambda i: i * 256) format = qt_format.Format_Grayscale16 else: if exclusive_fp: im.close() msg = f"unsupported image mode {repr(im.mode)}" raise ValueError(msg) size = im.size __data = data or align8to32(im.tobytes(), size[0], im.mode) if exclusive_fp: im.close() return {"data": __data, "size": size, "format": format, "colortable": colortable}
null
174,099
import sys from io import BytesIO from . import Image from ._deprecate import deprecate from ._util import is_path def toqimage(im): return ImageQt(im) def toqpixmap(im): # # This doesn't work. For now using a dumb approach. # im_data = _toqclass_helper(im) # result = QPixmap(im_data["size"][0], im_data["size"][1]) # result.loadFromData(im_data["data"]) qimage = toqimage(im) return QPixmap.fromImage(qimage)
null
174,100
from collections import namedtuple class TagInfo(namedtuple("_TagInfo", "value name type length enum")): __slots__ = [] def __new__(cls, value=None, name="unknown", type=None, length=None, enum=None): return super().__new__(cls, value, name, type, length, enum or {}) def cvt_enum(self, value): # Using get will call hash(value), which can be expensive # for some types (e.g. Fraction). Since self.enum is rarely # used, it's usually better to test it first. return self.enum.get(value, value) if self.enum else value TAGS_V2 = { 254: ("NewSubfileType", LONG, 1), 255: ("SubfileType", SHORT, 1), 256: ("ImageWidth", LONG, 1), 257: ("ImageLength", LONG, 1), 258: ("BitsPerSample", SHORT, 0), 259: ( "Compression", SHORT, 1, { "Uncompressed": 1, "CCITT 1d": 2, "Group 3 Fax": 3, "Group 4 Fax": 4, "LZW": 5, "JPEG": 6, "PackBits": 32773, }, ), 262: ( "PhotometricInterpretation", SHORT, 1, { "WhiteIsZero": 0, "BlackIsZero": 1, "RGB": 2, "RGB Palette": 3, "Transparency Mask": 4, "CMYK": 5, "YCbCr": 6, "CieLAB": 8, "CFA": 32803, # TIFF/EP, Adobe DNG "LinearRaw": 32892, # Adobe DNG }, ), 263: ("Threshholding", SHORT, 1), 264: ("CellWidth", SHORT, 1), 265: ("CellLength", SHORT, 1), 266: ("FillOrder", SHORT, 1), 269: ("DocumentName", ASCII, 1), 270: ("ImageDescription", ASCII, 1), 271: ("Make", ASCII, 1), 272: ("Model", ASCII, 1), 273: ("StripOffsets", LONG, 0), 274: ("Orientation", SHORT, 1), 277: ("SamplesPerPixel", SHORT, 1), 278: ("RowsPerStrip", LONG, 1), 279: ("StripByteCounts", LONG, 0), 280: ("MinSampleValue", SHORT, 0), 281: ("MaxSampleValue", SHORT, 0), 282: ("XResolution", RATIONAL, 1), 283: ("YResolution", RATIONAL, 1), 284: ("PlanarConfiguration", SHORT, 1, {"Contiguous": 1, "Separate": 2}), 285: ("PageName", ASCII, 1), 286: ("XPosition", RATIONAL, 1), 287: ("YPosition", RATIONAL, 1), 288: ("FreeOffsets", LONG, 1), 289: ("FreeByteCounts", LONG, 1), 290: ("GrayResponseUnit", SHORT, 1), 291: ("GrayResponseCurve", SHORT, 0), 292: ("T4Options", LONG, 1), 293: ("T6Options", LONG, 1), 296: ("ResolutionUnit", SHORT, 1, {"none": 1, "inch": 2, "cm": 3}), 297: ("PageNumber", SHORT, 2), 301: ("TransferFunction", SHORT, 0), 305: ("Software", ASCII, 1), 306: ("DateTime", ASCII, 1), 315: ("Artist", ASCII, 1), 316: ("HostComputer", ASCII, 1), 317: ("Predictor", SHORT, 1, {"none": 1, "Horizontal Differencing": 2}), 318: ("WhitePoint", RATIONAL, 2), 319: ("PrimaryChromaticities", RATIONAL, 6), 320: ("ColorMap", SHORT, 0), 321: ("HalftoneHints", SHORT, 2), 322: ("TileWidth", LONG, 1), 323: ("TileLength", LONG, 1), 324: ("TileOffsets", LONG, 0), 325: ("TileByteCounts", LONG, 0), 330: ("SubIFDs", LONG, 0), 332: ("InkSet", SHORT, 1), 333: ("InkNames", ASCII, 1), 334: ("NumberOfInks", SHORT, 1), 336: ("DotRange", SHORT, 0), 337: ("TargetPrinter", ASCII, 1), 338: ("ExtraSamples", SHORT, 0), 339: ("SampleFormat", SHORT, 0), 340: ("SMinSampleValue", DOUBLE, 0), 341: ("SMaxSampleValue", DOUBLE, 0), 342: ("TransferRange", SHORT, 6), 347: ("JPEGTables", UNDEFINED, 1), # obsolete JPEG tags 512: ("JPEGProc", SHORT, 1), 513: ("JPEGInterchangeFormat", LONG, 1), 514: ("JPEGInterchangeFormatLength", LONG, 1), 515: ("JPEGRestartInterval", SHORT, 1), 517: ("JPEGLosslessPredictors", SHORT, 0), 518: ("JPEGPointTransforms", SHORT, 0), 519: ("JPEGQTables", LONG, 0), 520: ("JPEGDCTables", LONG, 0), 521: ("JPEGACTables", LONG, 0), 529: ("YCbCrCoefficients", RATIONAL, 3), 530: ("YCbCrSubSampling", SHORT, 2), 531: ("YCbCrPositioning", SHORT, 1), 532: ("ReferenceBlackWhite", RATIONAL, 6), 700: ("XMP", BYTE, 0), 33432: ("Copyright", ASCII, 1), 33723: ("IptcNaaInfo", UNDEFINED, 1), 34377: ("PhotoshopInfo", BYTE, 0), # FIXME add more tags here 34665: ("ExifIFD", LONG, 1), 34675: ("ICCProfile", UNDEFINED, 1), 34853: ("GPSInfoIFD", LONG, 1), 36864: ("ExifVersion", UNDEFINED, 1), 37724: ("ImageSourceData", UNDEFINED, 1), 40965: ("InteroperabilityIFD", LONG, 1), 41730: ("CFAPattern", UNDEFINED, 1), # MPInfo 45056: ("MPFVersion", UNDEFINED, 1), 45057: ("NumberOfImages", LONG, 1), 45058: ("MPEntry", UNDEFINED, 1), 45059: ("ImageUIDList", UNDEFINED, 0), # UNDONE, check 45060: ("TotalFrames", LONG, 1), 45313: ("MPIndividualNum", LONG, 1), 45569: ("PanOrientation", LONG, 1), 45570: ("PanOverlap_H", RATIONAL, 1), 45571: ("PanOverlap_V", RATIONAL, 1), 45572: ("BaseViewpointNum", LONG, 1), 45573: ("ConvergenceAngle", SIGNED_RATIONAL, 1), 45574: ("BaselineLength", RATIONAL, 1), 45575: ("VerticalDivergence", SIGNED_RATIONAL, 1), 45576: ("AxisDistance_X", SIGNED_RATIONAL, 1), 45577: ("AxisDistance_Y", SIGNED_RATIONAL, 1), 45578: ("AxisDistance_Z", SIGNED_RATIONAL, 1), 45579: ("YawAngle", SIGNED_RATIONAL, 1), 45580: ("PitchAngle", SIGNED_RATIONAL, 1), 45581: ("RollAngle", SIGNED_RATIONAL, 1), 40960: ("FlashPixVersion", UNDEFINED, 1), 50741: ("MakerNoteSafety", SHORT, 1, {"Unsafe": 0, "Safe": 1}), 50780: ("BestQualityScale", RATIONAL, 1), 50838: ("ImageJMetaDataByteCounts", LONG, 0), # Can be more than one 50839: ("ImageJMetaData", UNDEFINED, 1), # see Issue #2006 } TAGS_V2_GROUPS = { # ExifIFD 34665: { 36864: ("ExifVersion", UNDEFINED, 1), 40960: ("FlashPixVersion", UNDEFINED, 1), 40965: ("InteroperabilityIFD", LONG, 1), 41730: ("CFAPattern", UNDEFINED, 1), }, # GPSInfoIFD 34853: { 0: ("GPSVersionID", BYTE, 4), 1: ("GPSLatitudeRef", ASCII, 2), 2: ("GPSLatitude", RATIONAL, 3), 3: ("GPSLongitudeRef", ASCII, 2), 4: ("GPSLongitude", RATIONAL, 3), 5: ("GPSAltitudeRef", BYTE, 1), 6: ("GPSAltitude", RATIONAL, 1), 7: ("GPSTimeStamp", RATIONAL, 3), 8: ("GPSSatellites", ASCII, 0), 9: ("GPSStatus", ASCII, 2), 10: ("GPSMeasureMode", ASCII, 2), 11: ("GPSDOP", RATIONAL, 1), 12: ("GPSSpeedRef", ASCII, 2), 13: ("GPSSpeed", RATIONAL, 1), 14: ("GPSTrackRef", ASCII, 2), 15: ("GPSTrack", RATIONAL, 1), 16: ("GPSImgDirectionRef", ASCII, 2), 17: ("GPSImgDirection", RATIONAL, 1), 18: ("GPSMapDatum", ASCII, 0), 19: ("GPSDestLatitudeRef", ASCII, 2), 20: ("GPSDestLatitude", RATIONAL, 3), 21: ("GPSDestLongitudeRef", ASCII, 2), 22: ("GPSDestLongitude", RATIONAL, 3), 23: ("GPSDestBearingRef", ASCII, 2), 24: ("GPSDestBearing", RATIONAL, 1), 25: ("GPSDestDistanceRef", ASCII, 2), 26: ("GPSDestDistance", RATIONAL, 1), 27: ("GPSProcessingMethod", UNDEFINED, 0), 28: ("GPSAreaInformation", UNDEFINED, 0), 29: ("GPSDateStamp", ASCII, 11), 30: ("GPSDifferential", SHORT, 1), }, # InteroperabilityIFD 40965: {1: ("InteropIndex", ASCII, 1), 2: ("InteropVersion", UNDEFINED, 1)}, } TAGS = { 347: "JPEGTables", 700: "XMP", # Additional Exif Info 32932: "Wang Annotation", 33434: "ExposureTime", 33437: "FNumber", 33445: "MD FileTag", 33446: "MD ScalePixel", 33447: "MD ColorTable", 33448: "MD LabName", 33449: "MD SampleInfo", 33450: "MD PrepDate", 33451: "MD PrepTime", 33452: "MD FileUnits", 33550: "ModelPixelScaleTag", 33723: "IptcNaaInfo", 33918: "INGR Packet Data Tag", 33919: "INGR Flag Registers", 33920: "IrasB Transformation Matrix", 33922: "ModelTiepointTag", 34264: "ModelTransformationTag", 34377: "PhotoshopInfo", 34735: "GeoKeyDirectoryTag", 34736: "GeoDoubleParamsTag", 34737: "GeoAsciiParamsTag", 34850: "ExposureProgram", 34852: "SpectralSensitivity", 34855: "ISOSpeedRatings", 34856: "OECF", 34864: "SensitivityType", 34865: "StandardOutputSensitivity", 34866: "RecommendedExposureIndex", 34867: "ISOSpeed", 34868: "ISOSpeedLatitudeyyy", 34869: "ISOSpeedLatitudezzz", 34908: "HylaFAX FaxRecvParams", 34909: "HylaFAX FaxSubAddress", 34910: "HylaFAX FaxRecvTime", 36864: "ExifVersion", 36867: "DateTimeOriginal", 36868: "DateTimeDigitized", 37121: "ComponentsConfiguration", 37122: "CompressedBitsPerPixel", 37724: "ImageSourceData", 37377: "ShutterSpeedValue", 37378: "ApertureValue", 37379: "BrightnessValue", 37380: "ExposureBiasValue", 37381: "MaxApertureValue", 37382: "SubjectDistance", 37383: "MeteringMode", 37384: "LightSource", 37385: "Flash", 37386: "FocalLength", 37396: "SubjectArea", 37500: "MakerNote", 37510: "UserComment", 37520: "SubSec", 37521: "SubSecTimeOriginal", 37522: "SubsecTimeDigitized", 40960: "FlashPixVersion", 40961: "ColorSpace", 40962: "PixelXDimension", 40963: "PixelYDimension", 40964: "RelatedSoundFile", 40965: "InteroperabilityIFD", 41483: "FlashEnergy", 41484: "SpatialFrequencyResponse", 41486: "FocalPlaneXResolution", 41487: "FocalPlaneYResolution", 41488: "FocalPlaneResolutionUnit", 41492: "SubjectLocation", 41493: "ExposureIndex", 41495: "SensingMethod", 41728: "FileSource", 41729: "SceneType", 41730: "CFAPattern", 41985: "CustomRendered", 41986: "ExposureMode", 41987: "WhiteBalance", 41988: "DigitalZoomRatio", 41989: "FocalLengthIn35mmFilm", 41990: "SceneCaptureType", 41991: "GainControl", 41992: "Contrast", 41993: "Saturation", 41994: "Sharpness", 41995: "DeviceSettingDescription", 41996: "SubjectDistanceRange", 42016: "ImageUniqueID", 42032: "CameraOwnerName", 42033: "BodySerialNumber", 42034: "LensSpecification", 42035: "LensMake", 42036: "LensModel", 42037: "LensSerialNumber", 42112: "GDAL_METADATA", 42113: "GDAL_NODATA", 42240: "Gamma", 50215: "Oce Scanjob Description", 50216: "Oce Application Selector", 50217: "Oce Identification Number", 50218: "Oce ImageLogic Characteristics", # Adobe DNG 50706: "DNGVersion", 50707: "DNGBackwardVersion", 50708: "UniqueCameraModel", 50709: "LocalizedCameraModel", 50710: "CFAPlaneColor", 50711: "CFALayout", 50712: "LinearizationTable", 50713: "BlackLevelRepeatDim", 50714: "BlackLevel", 50715: "BlackLevelDeltaH", 50716: "BlackLevelDeltaV", 50717: "WhiteLevel", 50718: "DefaultScale", 50719: "DefaultCropOrigin", 50720: "DefaultCropSize", 50721: "ColorMatrix1", 50722: "ColorMatrix2", 50723: "CameraCalibration1", 50724: "CameraCalibration2", 50725: "ReductionMatrix1", 50726: "ReductionMatrix2", 50727: "AnalogBalance", 50728: "AsShotNeutral", 50729: "AsShotWhiteXY", 50730: "BaselineExposure", 50731: "BaselineNoise", 50732: "BaselineSharpness", 50733: "BayerGreenSplit", 50734: "LinearResponseLimit", 50735: "CameraSerialNumber", 50736: "LensInfo", 50737: "ChromaBlurRadius", 50738: "AntiAliasStrength", 50740: "DNGPrivateData", 50778: "CalibrationIlluminant1", 50779: "CalibrationIlluminant2", 50784: "Alias Layer Metadata", } def _populate(): for k, v in TAGS_V2.items(): # Populate legacy structure. TAGS[k] = v[0] if len(v) == 4: for sk, sv in v[3].items(): TAGS[(k, sv)] = sk TAGS_V2[k] = TagInfo(k, *v) for group, tags in TAGS_V2_GROUPS.items(): for k, v in tags.items(): tags[k] = TagInfo(k, *v)
null
174,102
import re from . import Image, ImageFile class ImageFile(Image.Image): def __init__(self, fp=None, filename=None): def get_format_mimetype(self): def __setstate__(self, state): def verify(self): def load(self): def load_prepare(self): def load_end(self): def _seek_check(self, frame): def _save(im, fp, filename): if im.mode != "1": msg = f"cannot write mode {im.mode} as XBM" raise OSError(msg) fp.write(f"#define im_width {im.size[0]}\n".encode("ascii")) fp.write(f"#define im_height {im.size[1]}\n".encode("ascii")) hotspot = im.encoderinfo.get("hotspot") if hotspot: fp.write(f"#define im_x_hot {hotspot[0]}\n".encode("ascii")) fp.write(f"#define im_y_hot {hotspot[1]}\n".encode("ascii")) fp.write(b"static char im_bits[] = {\n") ImageFile._save(im, fp, [("xbm", (0, 0) + im.size, 0, None)]) fp.write(b"};\n")
null
174,103
import io import itertools import logging import math import os import struct import warnings from collections.abc import MutableMapping from fractions import Fraction from numbers import Number, Rational from . import Image, ImageFile, ImageOps, ImagePalette, TiffTags from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from .TiffTags import TYPES PREFIXES = [ b"MM\x00\x2A", # Valid TIFF header with big-endian byte order b"II\x2A\x00", # Valid TIFF header with little-endian byte order b"MM\x2A\x00", # Invalid TIFF header, assume big-endian b"II\x00\x2A", # Invalid TIFF header, assume little-endian b"MM\x00\x2B", # BigTIFF with big-endian byte order b"II\x2B\x00", # BigTIFF with little-endian byte order ] def _accept(prefix): return prefix[:4] in PREFIXES
null
174,104
import io import itertools import logging import math import os import struct import warnings from collections.abc import MutableMapping from fractions import Fraction from numbers import Number, Rational from . import Image, ImageFile, ImageOps, ImagePalette, TiffTags from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from .TiffTags import TYPES def _limit_rational(val, max_val): inv = abs(val) > 1 n_d = IFDRational(1 / val if inv else val).limit_rational(max_val) return n_d[::-1] if inv else n_d class Fraction(Rational): def __new__( cls, numerator: Union[int, Rational] = ..., denominator: Optional[Union[int, Rational]] = ..., *, _normalize: bool = ... ) -> Fraction: ... def __new__(cls, __value: Union[float, Decimal, str], *, _normalize: bool = ...) -> Fraction: ... def from_float(cls, f: float) -> Fraction: ... def from_decimal(cls, dec: Decimal) -> Fraction: ... def limit_denominator(self, max_denominator: int = ...) -> Fraction: ... if sys.version_info >= (3, 8): def as_integer_ratio(self) -> Tuple[int, int]: ... def numerator(self) -> int: ... def denominator(self) -> int: ... def __add__(self, other: Union[int, Fraction]) -> Fraction: ... def __add__(self, other: float) -> float: ... def __add__(self, other: complex) -> complex: ... def __radd__(self, other: Union[int, Fraction]) -> Fraction: ... def __radd__(self, other: float) -> float: ... def __radd__(self, other: complex) -> complex: ... def __sub__(self, other: Union[int, Fraction]) -> Fraction: ... def __sub__(self, other: float) -> float: ... def __sub__(self, other: complex) -> complex: ... def __rsub__(self, other: Union[int, Fraction]) -> Fraction: ... def __rsub__(self, other: float) -> float: ... def __rsub__(self, other: complex) -> complex: ... def __mul__(self, other: Union[int, Fraction]) -> Fraction: ... def __mul__(self, other: float) -> float: ... def __mul__(self, other: complex) -> complex: ... def __rmul__(self, other: Union[int, Fraction]) -> Fraction: ... def __rmul__(self, other: float) -> float: ... def __rmul__(self, other: complex) -> complex: ... def __truediv__(self, other: Union[int, Fraction]) -> Fraction: ... def __truediv__(self, other: float) -> float: ... def __truediv__(self, other: complex) -> complex: ... def __rtruediv__(self, other: Union[int, Fraction]) -> Fraction: ... def __rtruediv__(self, other: float) -> float: ... def __rtruediv__(self, other: complex) -> complex: ... if sys.version_info < (3, 0): def __div__(self, other: Union[int, Fraction]) -> Fraction: ... def __div__(self, other: float) -> float: ... def __div__(self, other: complex) -> complex: ... def __rdiv__(self, other: Union[int, Fraction]) -> Fraction: ... def __rdiv__(self, other: float) -> float: ... def __rdiv__(self, other: complex) -> complex: ... def __floordiv__(self, other: Union[int, Fraction]) -> int: ... def __floordiv__(self, other: float) -> float: ... def __rfloordiv__(self, other: Union[int, Fraction]) -> int: ... def __rfloordiv__(self, other: float) -> float: ... def __mod__(self, other: Union[int, Fraction]) -> Fraction: ... def __mod__(self, other: float) -> float: ... def __rmod__(self, other: Union[int, Fraction]) -> Fraction: ... def __rmod__(self, other: float) -> float: ... def __divmod__(self, other: Union[int, Fraction]) -> Tuple[int, Fraction]: ... def __divmod__(self, other: float) -> Tuple[float, Fraction]: ... def __rdivmod__(self, other: Union[int, Fraction]) -> Tuple[int, Fraction]: ... def __rdivmod__(self, other: float) -> Tuple[float, Fraction]: ... def __pow__(self, other: int) -> Fraction: ... def __pow__(self, other: Union[float, Fraction]) -> float: ... def __pow__(self, other: complex) -> complex: ... def __rpow__(self, other: Union[int, float, Fraction]) -> float: ... def __rpow__(self, other: complex) -> complex: ... def __pos__(self) -> Fraction: ... def __neg__(self) -> Fraction: ... def __abs__(self) -> Fraction: ... def __trunc__(self) -> int: ... if sys.version_info >= (3, 0): def __floor__(self) -> int: ... def __ceil__(self) -> int: ... def __round__(self, ndigits: None = ...) -> int: ... def __round__(self, ndigits: int) -> Fraction: ... def __hash__(self) -> int: ... def __eq__(self, other: object) -> bool: ... def __lt__(self, other: _ComparableNum) -> bool: ... def __gt__(self, other: _ComparableNum) -> bool: ... def __le__(self, other: _ComparableNum) -> bool: ... def __ge__(self, other: _ComparableNum) -> bool: ... if sys.version_info >= (3, 0): def __bool__(self) -> bool: ... else: def __nonzero__(self) -> bool: ... # Not actually defined within fractions.py, but provides more useful # overrides def real(self) -> Fraction: ... def imag(self) -> Literal[0]: ... def conjugate(self) -> Fraction: ... def _limit_signed_rational(val, max_val, min_val): frac = Fraction(val) n_d = frac.numerator, frac.denominator if min(n_d) < min_val: n_d = _limit_rational(val, abs(min_val)) if max(n_d) > max_val: val = Fraction(*n_d) n_d = _limit_rational(val, max_val) return n_d
null
174,105
import io import itertools import logging import math import os import struct import warnings from collections.abc import MutableMapping from fractions import Fraction from numbers import Number, Rational from . import Image, ImageFile, ImageOps, ImagePalette, TiffTags from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from .TiffTags import TYPES for idx, name in TYPES.items(): name = name.replace(" ", "_") setattr(ImageFileDirectory_v2, "load_" + name, _load_dispatch[idx][1]) setattr(ImageFileDirectory_v2, "write_" + name, _write_dispatch[idx]) def _save(im, fp, filename): try: rawmode, prefix, photo, format, bits, extra = SAVE_INFO[im.mode] except KeyError as e: msg = f"cannot write mode {im.mode} as TIFF" raise OSError(msg) from e ifd = ImageFileDirectory_v2(prefix=prefix) encoderinfo = im.encoderinfo encoderconfig = im.encoderconfig try: compression = encoderinfo["compression"] except KeyError: compression = im.info.get("compression") if isinstance(compression, int): # compression value may be from BMP. Ignore it compression = None if compression is None: compression = "raw" elif compression == "tiff_jpeg": # OJPEG is obsolete, so use new-style JPEG compression instead compression = "jpeg" elif compression == "tiff_deflate": compression = "tiff_adobe_deflate" libtiff = WRITE_LIBTIFF or compression != "raw" # required for color libtiff images ifd[PLANAR_CONFIGURATION] = 1 ifd[IMAGEWIDTH] = im.size[0] ifd[IMAGELENGTH] = im.size[1] # write any arbitrary tags passed in as an ImageFileDirectory if "tiffinfo" in encoderinfo: info = encoderinfo["tiffinfo"] elif "exif" in encoderinfo: info = encoderinfo["exif"] if isinstance(info, bytes): exif = Image.Exif() exif.load(info) info = exif else: info = {} logger.debug("Tiffinfo Keys: %s" % list(info)) if isinstance(info, ImageFileDirectory_v1): info = info.to_v2() for key in info: if isinstance(info, Image.Exif) and key in TiffTags.TAGS_V2_GROUPS: ifd[key] = info.get_ifd(key) else: ifd[key] = info.get(key) try: ifd.tagtype[key] = info.tagtype[key] except Exception: pass # might not be an IFD. Might not have populated type # additions written by Greg Couch, gregc@cgl.ucsf.edu # inspired by image-sig posting from Kevin Cazabon, kcazabon@home.com if hasattr(im, "tag_v2"): # preserve tags from original TIFF image file for key in ( RESOLUTION_UNIT, X_RESOLUTION, Y_RESOLUTION, IPTC_NAA_CHUNK, PHOTOSHOP_CHUNK, XMP, ): if key in im.tag_v2: ifd[key] = im.tag_v2[key] ifd.tagtype[key] = im.tag_v2.tagtype[key] # preserve ICC profile (should also work when saving other formats # which support profiles as TIFF) -- 2008-06-06 Florian Hoech icc = encoderinfo.get("icc_profile", im.info.get("icc_profile")) if icc: ifd[ICCPROFILE] = icc for key, name in [ (IMAGEDESCRIPTION, "description"), (X_RESOLUTION, "resolution"), (Y_RESOLUTION, "resolution"), (X_RESOLUTION, "x_resolution"), (Y_RESOLUTION, "y_resolution"), (RESOLUTION_UNIT, "resolution_unit"), (SOFTWARE, "software"), (DATE_TIME, "date_time"), (ARTIST, "artist"), (COPYRIGHT, "copyright"), ]: if name in encoderinfo: ifd[key] = encoderinfo[name] dpi = encoderinfo.get("dpi") if dpi: ifd[RESOLUTION_UNIT] = 2 ifd[X_RESOLUTION] = dpi[0] ifd[Y_RESOLUTION] = dpi[1] if bits != (1,): ifd[BITSPERSAMPLE] = bits if len(bits) != 1: ifd[SAMPLESPERPIXEL] = len(bits) if extra is not None: ifd[EXTRASAMPLES] = extra if format != 1: ifd[SAMPLEFORMAT] = format if PHOTOMETRIC_INTERPRETATION not in ifd: ifd[PHOTOMETRIC_INTERPRETATION] = photo elif im.mode in ("1", "L") and ifd[PHOTOMETRIC_INTERPRETATION] == 0: if im.mode == "1": inverted_im = im.copy() px = inverted_im.load() for y in range(inverted_im.height): for x in range(inverted_im.width): px[x, y] = 0 if px[x, y] == 255 else 255 im = inverted_im else: im = ImageOps.invert(im) if im.mode in ["P", "PA"]: lut = im.im.getpalette("RGB", "RGB;L") colormap = [] colors = len(lut) // 3 for i in range(3): colormap += [v * 256 for v in lut[colors * i : colors * (i + 1)]] colormap += [0] * (256 - colors) ifd[COLORMAP] = colormap # data orientation stride = len(bits) * ((im.size[0] * bits[0] + 7) // 8) # aim for given strip size (64 KB by default) when using libtiff writer if libtiff: im_strip_size = encoderinfo.get("strip_size", STRIP_SIZE) rows_per_strip = 1 if stride == 0 else min(im_strip_size // stride, im.size[1]) # JPEG encoder expects multiple of 8 rows if compression == "jpeg": rows_per_strip = min(((rows_per_strip + 7) // 8) * 8, im.size[1]) else: rows_per_strip = im.size[1] if rows_per_strip == 0: rows_per_strip = 1 strip_byte_counts = 1 if stride == 0 else stride * rows_per_strip strips_per_image = (im.size[1] + rows_per_strip - 1) // rows_per_strip ifd[ROWSPERSTRIP] = rows_per_strip if strip_byte_counts >= 2**16: ifd.tagtype[STRIPBYTECOUNTS] = TiffTags.LONG ifd[STRIPBYTECOUNTS] = (strip_byte_counts,) * (strips_per_image - 1) + ( stride * im.size[1] - strip_byte_counts * (strips_per_image - 1), ) ifd[STRIPOFFSETS] = tuple( range(0, strip_byte_counts * strips_per_image, strip_byte_counts) ) # this is adjusted by IFD writer # no compression by default: ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1) if im.mode == "YCbCr": for tag, value in { YCBCRSUBSAMPLING: (1, 1), REFERENCEBLACKWHITE: (0, 255, 128, 255, 128, 255), }.items(): ifd.setdefault(tag, value) blocklist = [TILEWIDTH, TILELENGTH, TILEOFFSETS, TILEBYTECOUNTS] if libtiff: if "quality" in encoderinfo: quality = encoderinfo["quality"] if not isinstance(quality, int) or quality < 0 or quality > 100: msg = "Invalid quality setting" raise ValueError(msg) if compression != "jpeg": msg = "quality setting only supported for 'jpeg' compression" raise ValueError(msg) ifd[JPEGQUALITY] = quality logger.debug("Saving using libtiff encoder") logger.debug("Items: %s" % sorted(ifd.items())) _fp = 0 if hasattr(fp, "fileno"): try: fp.seek(0) _fp = os.dup(fp.fileno()) except io.UnsupportedOperation: pass # optional types for non core tags types = {} # STRIPOFFSETS and STRIPBYTECOUNTS are added by the library # based on the data in the strip. # The other tags expect arrays with a certain length (fixed or depending on # BITSPERSAMPLE, etc), passing arrays with a different length will result in # segfaults. Block these tags until we add extra validation. # SUBIFD may also cause a segfault. blocklist += [ REFERENCEBLACKWHITE, STRIPBYTECOUNTS, STRIPOFFSETS, TRANSFERFUNCTION, SUBIFD, ] # bits per sample is a single short in the tiff directory, not a list. atts = {BITSPERSAMPLE: bits[0]} # Merge the ones that we have with (optional) more bits from # the original file, e.g x,y resolution so that we can # save(load('')) == original file. legacy_ifd = {} if hasattr(im, "tag"): legacy_ifd = im.tag.to_v2() # SAMPLEFORMAT is determined by the image format and should not be copied # from legacy_ifd. supplied_tags = {**getattr(im, "tag_v2", {}), **legacy_ifd} if SAMPLEFORMAT in supplied_tags: del supplied_tags[SAMPLEFORMAT] for tag, value in itertools.chain(ifd.items(), supplied_tags.items()): # Libtiff can only process certain core items without adding # them to the custom dictionary. # Custom items are supported for int, float, unicode, string and byte # values. Other types and tuples require a tagtype. if tag not in TiffTags.LIBTIFF_CORE: if not getattr(Image.core, "libtiff_support_custom_tags", False): continue if tag in ifd.tagtype: types[tag] = ifd.tagtype[tag] elif not (isinstance(value, (int, float, str, bytes))): continue else: type = TiffTags.lookup(tag).type if type: types[tag] = type if tag not in atts and tag not in blocklist: if isinstance(value, str): atts[tag] = value.encode("ascii", "replace") + b"\0" elif isinstance(value, IFDRational): atts[tag] = float(value) else: atts[tag] = value if SAMPLEFORMAT in atts and len(atts[SAMPLEFORMAT]) == 1: atts[SAMPLEFORMAT] = atts[SAMPLEFORMAT][0] logger.debug("Converted items: %s" % sorted(atts.items())) # libtiff always expects the bytes in native order. # we're storing image byte order. So, if the rawmode # contains I;16, we need to convert from native to image # byte order. if im.mode in ("I;16B", "I;16"): rawmode = "I;16N" # Pass tags as sorted list so that the tags are set in a fixed order. # This is required by libtiff for some tags. For example, the JPEGQUALITY # pseudo tag requires that the COMPRESS tag was already set. tags = list(atts.items()) tags.sort() a = (rawmode, compression, _fp, filename, tags, types) e = Image._getencoder(im.mode, "libtiff", a, encoderconfig) e.setimage(im.im, (0, 0) + im.size) while True: # undone, change to self.decodermaxblock: errcode, data = e.encode(16 * 1024)[1:] if not _fp: fp.write(data) if errcode: break if _fp: try: os.close(_fp) except OSError: pass if errcode < 0: msg = f"encoder error {errcode} when writing image file" raise OSError(msg) else: for tag in blocklist: del ifd[tag] offset = ifd.save(fp) ImageFile._save( im, fp, [("raw", (0, 0) + im.size, offset, (rawmode, stride, 1))] ) # -- helper for multi-page save -- if "_debug_multipage" in encoderinfo: # just to access o32 and o16 (using correct byte order) im._debug_multipage = ifd class AppendingTiffWriter: fieldSizes = [ 0, # None 1, # byte 1, # ascii 2, # short 4, # long 8, # rational 1, # sbyte 1, # undefined 2, # sshort 4, # slong 8, # srational 4, # float 8, # double ] # StripOffsets = 273 # FreeOffsets = 288 # TileOffsets = 324 # JPEGQTables = 519 # JPEGDCTables = 520 # JPEGACTables = 521 Tags = {273, 288, 324, 519, 520, 521} def __init__(self, fn, new=False): if hasattr(fn, "read"): self.f = fn self.close_fp = False else: self.name = fn self.close_fp = True try: self.f = open(fn, "w+b" if new else "r+b") except OSError: self.f = open(fn, "w+b") self.beginning = self.f.tell() self.setup() def setup(self): # Reset everything. self.f.seek(self.beginning, os.SEEK_SET) self.whereToWriteNewIFDOffset = None self.offsetOfNewPage = 0 self.IIMM = iimm = self.f.read(4) if not iimm: # empty file - first page self.isFirst = True return self.isFirst = False if iimm == b"II\x2a\x00": self.setEndian("<") elif iimm == b"MM\x00\x2a": self.setEndian(">") else: msg = "Invalid TIFF file header" raise RuntimeError(msg) self.skipIFDs() self.goToEnd() def finalize(self): if self.isFirst: return # fix offsets self.f.seek(self.offsetOfNewPage) iimm = self.f.read(4) if not iimm: # msg = "nothing written into new page" # raise RuntimeError(msg) # Make it easy to finish a frame without committing to a new one. return if iimm != self.IIMM: msg = "IIMM of new page doesn't match IIMM of first page" raise RuntimeError(msg) ifd_offset = self.readLong() ifd_offset += self.offsetOfNewPage self.f.seek(self.whereToWriteNewIFDOffset) self.writeLong(ifd_offset) self.f.seek(ifd_offset) self.fixIFD() def newFrame(self): # Call this to finish a frame. self.finalize() self.setup() def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): if self.close_fp: self.close() return False def tell(self): return self.f.tell() - self.offsetOfNewPage def seek(self, offset, whence=io.SEEK_SET): if whence == os.SEEK_SET: offset += self.offsetOfNewPage self.f.seek(offset, whence) return self.tell() def goToEnd(self): self.f.seek(0, os.SEEK_END) pos = self.f.tell() # pad to 16 byte boundary pad_bytes = 16 - pos % 16 if 0 < pad_bytes < 16: self.f.write(bytes(pad_bytes)) self.offsetOfNewPage = self.f.tell() def setEndian(self, endian): self.endian = endian self.longFmt = self.endian + "L" self.shortFmt = self.endian + "H" self.tagFormat = self.endian + "HHL" def skipIFDs(self): while True: ifd_offset = self.readLong() if ifd_offset == 0: self.whereToWriteNewIFDOffset = self.f.tell() - 4 break self.f.seek(ifd_offset) num_tags = self.readShort() self.f.seek(num_tags * 12, os.SEEK_CUR) def write(self, data): return self.f.write(data) def readShort(self): (value,) = struct.unpack(self.shortFmt, self.f.read(2)) return value def readLong(self): (value,) = struct.unpack(self.longFmt, self.f.read(4)) return value def rewriteLastShortToLong(self, value): self.f.seek(-2, os.SEEK_CUR) bytes_written = self.f.write(struct.pack(self.longFmt, value)) if bytes_written is not None and bytes_written != 4: msg = f"wrote only {bytes_written} bytes but wanted 4" raise RuntimeError(msg) def rewriteLastShort(self, value): self.f.seek(-2, os.SEEK_CUR) bytes_written = self.f.write(struct.pack(self.shortFmt, value)) if bytes_written is not None and bytes_written != 2: msg = f"wrote only {bytes_written} bytes but wanted 2" raise RuntimeError(msg) def rewriteLastLong(self, value): self.f.seek(-4, os.SEEK_CUR) bytes_written = self.f.write(struct.pack(self.longFmt, value)) if bytes_written is not None and bytes_written != 4: msg = f"wrote only {bytes_written} bytes but wanted 4" raise RuntimeError(msg) def writeShort(self, value): bytes_written = self.f.write(struct.pack(self.shortFmt, value)) if bytes_written is not None and bytes_written != 2: msg = f"wrote only {bytes_written} bytes but wanted 2" raise RuntimeError(msg) def writeLong(self, value): bytes_written = self.f.write(struct.pack(self.longFmt, value)) if bytes_written is not None and bytes_written != 4: msg = f"wrote only {bytes_written} bytes but wanted 4" raise RuntimeError(msg) def close(self): self.finalize() self.f.close() def fixIFD(self): num_tags = self.readShort() for i in range(num_tags): tag, field_type, count = struct.unpack(self.tagFormat, self.f.read(8)) field_size = self.fieldSizes[field_type] total_size = field_size * count is_local = total_size <= 4 if not is_local: offset = self.readLong() offset += self.offsetOfNewPage self.rewriteLastLong(offset) if tag in self.Tags: cur_pos = self.f.tell() if is_local: self.fixOffsets( count, isShort=(field_size == 2), isLong=(field_size == 4) ) self.f.seek(cur_pos + 4) else: self.f.seek(offset) self.fixOffsets( count, isShort=(field_size == 2), isLong=(field_size == 4) ) self.f.seek(cur_pos) offset = cur_pos = None elif is_local: # skip the locally stored value that is not an offset self.f.seek(4, os.SEEK_CUR) def fixOffsets(self, count, isShort=False, isLong=False): if not isShort and not isLong: msg = "offset is neither short nor long" raise RuntimeError(msg) for i in range(count): offset = self.readShort() if isShort else self.readLong() offset += self.offsetOfNewPage if isShort and offset >= 65536: # offset is now too large - we must convert shorts to longs if count != 1: msg = "not implemented" raise RuntimeError(msg) # XXX TODO # simple case - the offset is just one and therefore it is # local (not referenced with another offset) self.rewriteLastShortToLong(offset) self.f.seek(-10, os.SEEK_CUR) self.writeShort(TiffTags.LONG) # rewrite the type to LONG self.f.seek(8, os.SEEK_CUR) elif isShort: self.rewriteLastShort(offset) else: self.rewriteLastLong(offset) def _save_all(im, fp, filename): encoderinfo = im.encoderinfo.copy() encoderconfig = im.encoderconfig append_images = list(encoderinfo.get("append_images", [])) if not hasattr(im, "n_frames") and not append_images: return _save(im, fp, filename) cur_idx = im.tell() try: with AppendingTiffWriter(fp) as tf: for ims in [im] + append_images: ims.encoderinfo = encoderinfo ims.encoderconfig = encoderconfig if not hasattr(ims, "n_frames"): nfr = 1 else: nfr = ims.n_frames for idx in range(nfr): ims.seek(idx) ims.load() _save(ims, tf, filename) tf.newFrame() finally: im.seek(cur_idx)
null
174,106
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from ._binary import o16be as o16 from ._deprecate import deprecate from .JpegPresets import presets class ImageFile(Image.Image): """Base class for image file format handlers.""" def __init__(self, fp=None, filename=None): super().__init__() self._min_frame = 0 self.custom_mimetype = None self.tile = None """ A list of tile descriptors, or ``None`` """ self.readonly = 1 # until we know better self.decoderconfig = () self.decodermaxblock = MAXBLOCK if is_path(fp): # filename self.fp = open(fp, "rb") self.filename = fp self._exclusive_fp = True else: # stream self.fp = fp self.filename = filename # can be overridden self._exclusive_fp = None try: try: self._open() except ( IndexError, # end of data TypeError, # end of data (ord) KeyError, # unsupported mode EOFError, # got header but not the first frame struct.error, ) as v: raise SyntaxError(v) from v if not self.mode or self.size[0] <= 0 or self.size[1] <= 0: msg = "not identified by this driver" raise SyntaxError(msg) except BaseException: # close the file only if we have opened it this constructor if self._exclusive_fp: self.fp.close() raise def get_format_mimetype(self): if self.custom_mimetype: return self.custom_mimetype if self.format is not None: return Image.MIME.get(self.format.upper()) def __setstate__(self, state): self.tile = [] super().__setstate__(state) def verify(self): """Check file integrity""" # raise exception if something's wrong. must be called # directly after open, and closes file when finished. if self._exclusive_fp: self.fp.close() self.fp = None def load(self): """Load image data based on tile list""" if self.tile is None: msg = "cannot load this image" raise OSError(msg) pixel = Image.Image.load(self) if not self.tile: return pixel self.map = None use_mmap = self.filename and len(self.tile) == 1 # As of pypy 2.1.0, memory mapping was failing here. use_mmap = use_mmap and not hasattr(sys, "pypy_version_info") readonly = 0 # look for read/seek overrides try: read = self.load_read # don't use mmap if there are custom read/seek functions use_mmap = False except AttributeError: read = self.fp.read try: seek = self.load_seek use_mmap = False except AttributeError: seek = self.fp.seek if use_mmap: # try memory mapping decoder_name, extents, offset, args = self.tile[0] if ( decoder_name == "raw" and len(args) >= 3 and args[0] == self.mode and args[0] in Image._MAPMODES ): try: # use mmap, if possible import mmap with open(self.filename) as fp: self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ) if offset + self.size[1] * args[1] > self.map.size(): # buffer is not large enough raise OSError self.im = Image.core.map_buffer( self.map, self.size, decoder_name, offset, args ) readonly = 1 # After trashing self.im, # we might need to reload the palette data. if self.palette: self.palette.dirty = 1 except (AttributeError, OSError, ImportError): self.map = None self.load_prepare() err_code = -3 # initialize to unknown error if not self.map: # sort tiles in file order self.tile.sort(key=_tilesort) try: # FIXME: This is a hack to handle TIFF's JpegTables tag. prefix = self.tile_prefix except AttributeError: prefix = b"" # Remove consecutive duplicates that only differ by their offset self.tile = [ list(tiles)[-1] for _, tiles in itertools.groupby( self.tile, lambda tile: (tile[0], tile[1], tile[3]) ) ] for decoder_name, extents, offset, args in self.tile: seek(offset) decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) err_code = decoder.decode(b"")[1] else: b = prefix while True: try: s = read(self.decodermaxblock) except (IndexError, struct.error) as e: # truncated png/gif if LOAD_TRUNCATED_IMAGES: break else: msg = "image file is truncated" raise OSError(msg) from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: msg = ( "image file is truncated " f"({len(b)} bytes not processed)" ) raise OSError(msg) b = b + s n, err_code = decoder.decode(b) if n < 0: break b = b[n:] finally: # Need to cleanup here to prevent leaks decoder.cleanup() self.tile = [] self.readonly = readonly self.load_end() if self._exclusive_fp and self._close_exclusive_fp_after_loading: self.fp.close() self.fp = None if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0: # still raised if decoder fails to return anything raise_oserror(err_code) return Image.Image.load(self) def load_prepare(self): # create image memory if necessary if not self.im or self.im.mode != self.mode or self.im.size != self.size: self.im = Image.core.new(self.mode, self.size) # create palette (optional) if self.mode == "P": Image.Image.load(self) def load_end(self): # may be overridden pass # may be defined for contained formats # def load_seek(self, pos): # pass # may be defined for blocked formats (e.g. PNG) # def load_read(self, bytes): # pass def _seek_check(self, frame): if ( frame < self._min_frame # Only check upper limit on frames if additional seek operations # are not required to do so or ( not (hasattr(self, "_n_frames") and self._n_frames is None) and frame >= self.n_frames + self._min_frame ) ): msg = "attempt to seek outside sequence" raise EOFError(msg) return self.tell() != frame def Skip(self, marker): n = i16(self.fp.read(2)) - 2 ImageFile._safe_read(self.fp, n)
null
174,107
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from ._binary import o16be as o16 from ._deprecate import deprecate from .JpegPresets import presets class ImageFile(Image.Image): def __init__(self, fp=None, filename=None): def get_format_mimetype(self): def __setstate__(self, state): def verify(self): def load(self): def load_prepare(self): def load_end(self): def _seek_check(self, frame): def APP(self, marker): # # Application marker. Store these in the APP dictionary. # Also look for well-known application markers. n = i16(self.fp.read(2)) - 2 s = ImageFile._safe_read(self.fp, n) app = "APP%d" % (marker & 15) self.app[app] = s # compatibility self.applist.append((app, s)) if marker == 0xFFE0 and s[:4] == b"JFIF": # extract JFIF information self.info["jfif"] = version = i16(s, 5) # version self.info["jfif_version"] = divmod(version, 256) # extract JFIF properties try: jfif_unit = s[7] jfif_density = i16(s, 8), i16(s, 10) except Exception: pass else: if jfif_unit == 1: self.info["dpi"] = jfif_density self.info["jfif_unit"] = jfif_unit self.info["jfif_density"] = jfif_density elif marker == 0xFFE1 and s[:5] == b"Exif\0": if "exif" not in self.info: # extract EXIF information (incomplete) self.info["exif"] = s # FIXME: value will change self._exif_offset = self.fp.tell() - n + 6 elif marker == 0xFFE2 and s[:5] == b"FPXR\0": # extract FlashPix information (incomplete) self.info["flashpix"] = s # FIXME: value will change elif marker == 0xFFE2 and s[:12] == b"ICC_PROFILE\0": # Since an ICC profile can be larger than the maximum size of # a JPEG marker (64K), we need provisions to split it into # multiple markers. The format defined by the ICC specifies # one or more APP2 markers containing the following data: # Identifying string ASCII "ICC_PROFILE\0" (12 bytes) # Marker sequence number 1, 2, etc (1 byte) # Number of markers Total of APP2's used (1 byte) # Profile data (remainder of APP2 data) # Decoders should use the marker sequence numbers to # reassemble the profile, rather than assuming that the APP2 # markers appear in the correct sequence. self.icclist.append(s) elif marker == 0xFFED and s[:14] == b"Photoshop 3.0\x00": # parse the image resource block offset = 14 photoshop = self.info.setdefault("photoshop", {}) while s[offset : offset + 4] == b"8BIM": try: offset += 4 # resource code code = i16(s, offset) offset += 2 # resource name (usually empty) name_len = s[offset] # name = s[offset+1:offset+1+name_len] offset += 1 + name_len offset += offset & 1 # align # resource data block size = i32(s, offset) offset += 4 data = s[offset : offset + size] if code == 0x03ED: # ResolutionInfo data = { "XResolution": i32(data, 0) / 65536, "DisplayedUnitsX": i16(data, 4), "YResolution": i32(data, 8) / 65536, "DisplayedUnitsY": i16(data, 12), } photoshop[code] = data offset += size offset += offset & 1 # align except struct.error: break # insufficient data elif marker == 0xFFEE and s[:5] == b"Adobe": self.info["adobe"] = i16(s, 5) # extract Adobe custom properties try: adobe_transform = s[11] except IndexError: pass else: self.info["adobe_transform"] = adobe_transform elif marker == 0xFFE2 and s[:4] == b"MPF\0": # extract MPO information self.info["mp"] = s[4:] # offset is current location minus buffer size # plus constant header size self.info["mpoffset"] = self.fp.tell() - n + 4 # If DPI isn't in JPEG header, fetch from EXIF if "dpi" not in self.info and "exif" in self.info: try: exif = self.getexif() resolution_unit = exif[0x0128] x_resolution = exif[0x011A] try: dpi = float(x_resolution[0]) / x_resolution[1] except TypeError: dpi = x_resolution if math.isnan(dpi): raise ValueError if resolution_unit == 3: # cm # 1 dpcm = 2.54 dpi dpi *= 2.54 self.info["dpi"] = dpi, dpi except (TypeError, KeyError, SyntaxError, ValueError, ZeroDivisionError): # SyntaxError for invalid/unreadable EXIF # KeyError for dpi not included # ZeroDivisionError for invalid dpi rational value # ValueError or TypeError for dpi being an invalid float self.info["dpi"] = 72, 72
null
174,108
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from ._binary import o16be as o16 from ._deprecate import deprecate from .JpegPresets import presets class ImageFile(Image.Image): """Base class for image file format handlers.""" def __init__(self, fp=None, filename=None): super().__init__() self._min_frame = 0 self.custom_mimetype = None self.tile = None """ A list of tile descriptors, or ``None`` """ self.readonly = 1 # until we know better self.decoderconfig = () self.decodermaxblock = MAXBLOCK if is_path(fp): # filename self.fp = open(fp, "rb") self.filename = fp self._exclusive_fp = True else: # stream self.fp = fp self.filename = filename # can be overridden self._exclusive_fp = None try: try: self._open() except ( IndexError, # end of data TypeError, # end of data (ord) KeyError, # unsupported mode EOFError, # got header but not the first frame struct.error, ) as v: raise SyntaxError(v) from v if not self.mode or self.size[0] <= 0 or self.size[1] <= 0: msg = "not identified by this driver" raise SyntaxError(msg) except BaseException: # close the file only if we have opened it this constructor if self._exclusive_fp: self.fp.close() raise def get_format_mimetype(self): if self.custom_mimetype: return self.custom_mimetype if self.format is not None: return Image.MIME.get(self.format.upper()) def __setstate__(self, state): self.tile = [] super().__setstate__(state) def verify(self): """Check file integrity""" # raise exception if something's wrong. must be called # directly after open, and closes file when finished. if self._exclusive_fp: self.fp.close() self.fp = None def load(self): """Load image data based on tile list""" if self.tile is None: msg = "cannot load this image" raise OSError(msg) pixel = Image.Image.load(self) if not self.tile: return pixel self.map = None use_mmap = self.filename and len(self.tile) == 1 # As of pypy 2.1.0, memory mapping was failing here. use_mmap = use_mmap and not hasattr(sys, "pypy_version_info") readonly = 0 # look for read/seek overrides try: read = self.load_read # don't use mmap if there are custom read/seek functions use_mmap = False except AttributeError: read = self.fp.read try: seek = self.load_seek use_mmap = False except AttributeError: seek = self.fp.seek if use_mmap: # try memory mapping decoder_name, extents, offset, args = self.tile[0] if ( decoder_name == "raw" and len(args) >= 3 and args[0] == self.mode and args[0] in Image._MAPMODES ): try: # use mmap, if possible import mmap with open(self.filename) as fp: self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ) if offset + self.size[1] * args[1] > self.map.size(): # buffer is not large enough raise OSError self.im = Image.core.map_buffer( self.map, self.size, decoder_name, offset, args ) readonly = 1 # After trashing self.im, # we might need to reload the palette data. if self.palette: self.palette.dirty = 1 except (AttributeError, OSError, ImportError): self.map = None self.load_prepare() err_code = -3 # initialize to unknown error if not self.map: # sort tiles in file order self.tile.sort(key=_tilesort) try: # FIXME: This is a hack to handle TIFF's JpegTables tag. prefix = self.tile_prefix except AttributeError: prefix = b"" # Remove consecutive duplicates that only differ by their offset self.tile = [ list(tiles)[-1] for _, tiles in itertools.groupby( self.tile, lambda tile: (tile[0], tile[1], tile[3]) ) ] for decoder_name, extents, offset, args in self.tile: seek(offset) decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) err_code = decoder.decode(b"")[1] else: b = prefix while True: try: s = read(self.decodermaxblock) except (IndexError, struct.error) as e: # truncated png/gif if LOAD_TRUNCATED_IMAGES: break else: msg = "image file is truncated" raise OSError(msg) from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: msg = ( "image file is truncated " f"({len(b)} bytes not processed)" ) raise OSError(msg) b = b + s n, err_code = decoder.decode(b) if n < 0: break b = b[n:] finally: # Need to cleanup here to prevent leaks decoder.cleanup() self.tile = [] self.readonly = readonly self.load_end() if self._exclusive_fp and self._close_exclusive_fp_after_loading: self.fp.close() self.fp = None if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0: # still raised if decoder fails to return anything raise_oserror(err_code) return Image.Image.load(self) def load_prepare(self): # create image memory if necessary if not self.im or self.im.mode != self.mode or self.im.size != self.size: self.im = Image.core.new(self.mode, self.size) # create palette (optional) if self.mode == "P": Image.Image.load(self) def load_end(self): # may be overridden pass # may be defined for contained formats # def load_seek(self, pos): # pass # may be defined for blocked formats (e.g. PNG) # def load_read(self, bytes): # pass def _seek_check(self, frame): if ( frame < self._min_frame # Only check upper limit on frames if additional seek operations # are not required to do so or ( not (hasattr(self, "_n_frames") and self._n_frames is None) and frame >= self.n_frames + self._min_frame ) ): msg = "attempt to seek outside sequence" raise EOFError(msg) return self.tell() != frame def COM(self, marker): # # Comment marker. Store these in the APP dictionary. n = i16(self.fp.read(2)) - 2 s = ImageFile._safe_read(self.fp, n) self.info["comment"] = s self.app["COM"] = s # compatibility self.applist.append(("COM", s))
null
174,109
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from ._binary import o16be as o16 from ._deprecate import deprecate from .JpegPresets import presets class ImageFile(Image.Image): """Base class for image file format handlers.""" def __init__(self, fp=None, filename=None): super().__init__() self._min_frame = 0 self.custom_mimetype = None self.tile = None """ A list of tile descriptors, or ``None`` """ self.readonly = 1 # until we know better self.decoderconfig = () self.decodermaxblock = MAXBLOCK if is_path(fp): # filename self.fp = open(fp, "rb") self.filename = fp self._exclusive_fp = True else: # stream self.fp = fp self.filename = filename # can be overridden self._exclusive_fp = None try: try: self._open() except ( IndexError, # end of data TypeError, # end of data (ord) KeyError, # unsupported mode EOFError, # got header but not the first frame struct.error, ) as v: raise SyntaxError(v) from v if not self.mode or self.size[0] <= 0 or self.size[1] <= 0: msg = "not identified by this driver" raise SyntaxError(msg) except BaseException: # close the file only if we have opened it this constructor if self._exclusive_fp: self.fp.close() raise def get_format_mimetype(self): if self.custom_mimetype: return self.custom_mimetype if self.format is not None: return Image.MIME.get(self.format.upper()) def __setstate__(self, state): self.tile = [] super().__setstate__(state) def verify(self): """Check file integrity""" # raise exception if something's wrong. must be called # directly after open, and closes file when finished. if self._exclusive_fp: self.fp.close() self.fp = None def load(self): """Load image data based on tile list""" if self.tile is None: msg = "cannot load this image" raise OSError(msg) pixel = Image.Image.load(self) if not self.tile: return pixel self.map = None use_mmap = self.filename and len(self.tile) == 1 # As of pypy 2.1.0, memory mapping was failing here. use_mmap = use_mmap and not hasattr(sys, "pypy_version_info") readonly = 0 # look for read/seek overrides try: read = self.load_read # don't use mmap if there are custom read/seek functions use_mmap = False except AttributeError: read = self.fp.read try: seek = self.load_seek use_mmap = False except AttributeError: seek = self.fp.seek if use_mmap: # try memory mapping decoder_name, extents, offset, args = self.tile[0] if ( decoder_name == "raw" and len(args) >= 3 and args[0] == self.mode and args[0] in Image._MAPMODES ): try: # use mmap, if possible import mmap with open(self.filename) as fp: self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ) if offset + self.size[1] * args[1] > self.map.size(): # buffer is not large enough raise OSError self.im = Image.core.map_buffer( self.map, self.size, decoder_name, offset, args ) readonly = 1 # After trashing self.im, # we might need to reload the palette data. if self.palette: self.palette.dirty = 1 except (AttributeError, OSError, ImportError): self.map = None self.load_prepare() err_code = -3 # initialize to unknown error if not self.map: # sort tiles in file order self.tile.sort(key=_tilesort) try: # FIXME: This is a hack to handle TIFF's JpegTables tag. prefix = self.tile_prefix except AttributeError: prefix = b"" # Remove consecutive duplicates that only differ by their offset self.tile = [ list(tiles)[-1] for _, tiles in itertools.groupby( self.tile, lambda tile: (tile[0], tile[1], tile[3]) ) ] for decoder_name, extents, offset, args in self.tile: seek(offset) decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) err_code = decoder.decode(b"")[1] else: b = prefix while True: try: s = read(self.decodermaxblock) except (IndexError, struct.error) as e: # truncated png/gif if LOAD_TRUNCATED_IMAGES: break else: msg = "image file is truncated" raise OSError(msg) from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: msg = ( "image file is truncated " f"({len(b)} bytes not processed)" ) raise OSError(msg) b = b + s n, err_code = decoder.decode(b) if n < 0: break b = b[n:] finally: # Need to cleanup here to prevent leaks decoder.cleanup() self.tile = [] self.readonly = readonly self.load_end() if self._exclusive_fp and self._close_exclusive_fp_after_loading: self.fp.close() self.fp = None if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0: # still raised if decoder fails to return anything raise_oserror(err_code) return Image.Image.load(self) def load_prepare(self): # create image memory if necessary if not self.im or self.im.mode != self.mode or self.im.size != self.size: self.im = Image.core.new(self.mode, self.size) # create palette (optional) if self.mode == "P": Image.Image.load(self) def load_end(self): # may be overridden pass # may be defined for contained formats # def load_seek(self, pos): # pass # may be defined for blocked formats (e.g. PNG) # def load_read(self, bytes): # pass def _seek_check(self, frame): if ( frame < self._min_frame # Only check upper limit on frames if additional seek operations # are not required to do so or ( not (hasattr(self, "_n_frames") and self._n_frames is None) and frame >= self.n_frames + self._min_frame ) ): msg = "attempt to seek outside sequence" raise EOFError(msg) return self.tell() != frame def SOF(self, marker): # # Start of frame marker. Defines the size and mode of the # image. JPEG is colour blind, so we use some simple # heuristics to map the number of layers to an appropriate # mode. Note that this could be made a bit brighter, by # looking for JFIF and Adobe APP markers. n = i16(self.fp.read(2)) - 2 s = ImageFile._safe_read(self.fp, n) self._size = i16(s, 3), i16(s, 1) self.bits = s[0] if self.bits != 8: msg = f"cannot handle {self.bits}-bit layers" raise SyntaxError(msg) self.layers = s[5] if self.layers == 1: self.mode = "L" elif self.layers == 3: self.mode = "RGB" elif self.layers == 4: self.mode = "CMYK" else: msg = f"cannot handle {self.layers}-layer images" raise SyntaxError(msg) if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]: self.info["progressive"] = self.info["progression"] = 1 if self.icclist: # fixup icc profile self.icclist.sort() # sort by sequence number if self.icclist[0][13] == len(self.icclist): profile = [] for p in self.icclist: profile.append(p[14:]) icc_profile = b"".join(profile) else: icc_profile = None # wrong number of fragments self.info["icc_profile"] = icc_profile self.icclist = [] for i in range(6, len(s), 3): t = s[i : i + 3] # 4-tuples: id, vsamp, hsamp, qtable self.layer.append((t[0], t[1] // 16, t[1] & 15, t[2]))
null
174,110
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from ._binary import o16be as o16 from ._deprecate import deprecate from .JpegPresets import presets zigzag_index = ( 0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63, ) class ImageFile(Image.Image): """Base class for image file format handlers.""" def __init__(self, fp=None, filename=None): super().__init__() self._min_frame = 0 self.custom_mimetype = None self.tile = None """ A list of tile descriptors, or ``None`` """ self.readonly = 1 # until we know better self.decoderconfig = () self.decodermaxblock = MAXBLOCK if is_path(fp): # filename self.fp = open(fp, "rb") self.filename = fp self._exclusive_fp = True else: # stream self.fp = fp self.filename = filename # can be overridden self._exclusive_fp = None try: try: self._open() except ( IndexError, # end of data TypeError, # end of data (ord) KeyError, # unsupported mode EOFError, # got header but not the first frame struct.error, ) as v: raise SyntaxError(v) from v if not self.mode or self.size[0] <= 0 or self.size[1] <= 0: msg = "not identified by this driver" raise SyntaxError(msg) except BaseException: # close the file only if we have opened it this constructor if self._exclusive_fp: self.fp.close() raise def get_format_mimetype(self): if self.custom_mimetype: return self.custom_mimetype if self.format is not None: return Image.MIME.get(self.format.upper()) def __setstate__(self, state): self.tile = [] super().__setstate__(state) def verify(self): """Check file integrity""" # raise exception if something's wrong. must be called # directly after open, and closes file when finished. if self._exclusive_fp: self.fp.close() self.fp = None def load(self): """Load image data based on tile list""" if self.tile is None: msg = "cannot load this image" raise OSError(msg) pixel = Image.Image.load(self) if not self.tile: return pixel self.map = None use_mmap = self.filename and len(self.tile) == 1 # As of pypy 2.1.0, memory mapping was failing here. use_mmap = use_mmap and not hasattr(sys, "pypy_version_info") readonly = 0 # look for read/seek overrides try: read = self.load_read # don't use mmap if there are custom read/seek functions use_mmap = False except AttributeError: read = self.fp.read try: seek = self.load_seek use_mmap = False except AttributeError: seek = self.fp.seek if use_mmap: # try memory mapping decoder_name, extents, offset, args = self.tile[0] if ( decoder_name == "raw" and len(args) >= 3 and args[0] == self.mode and args[0] in Image._MAPMODES ): try: # use mmap, if possible import mmap with open(self.filename) as fp: self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ) if offset + self.size[1] * args[1] > self.map.size(): # buffer is not large enough raise OSError self.im = Image.core.map_buffer( self.map, self.size, decoder_name, offset, args ) readonly = 1 # After trashing self.im, # we might need to reload the palette data. if self.palette: self.palette.dirty = 1 except (AttributeError, OSError, ImportError): self.map = None self.load_prepare() err_code = -3 # initialize to unknown error if not self.map: # sort tiles in file order self.tile.sort(key=_tilesort) try: # FIXME: This is a hack to handle TIFF's JpegTables tag. prefix = self.tile_prefix except AttributeError: prefix = b"" # Remove consecutive duplicates that only differ by their offset self.tile = [ list(tiles)[-1] for _, tiles in itertools.groupby( self.tile, lambda tile: (tile[0], tile[1], tile[3]) ) ] for decoder_name, extents, offset, args in self.tile: seek(offset) decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) err_code = decoder.decode(b"")[1] else: b = prefix while True: try: s = read(self.decodermaxblock) except (IndexError, struct.error) as e: # truncated png/gif if LOAD_TRUNCATED_IMAGES: break else: msg = "image file is truncated" raise OSError(msg) from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: msg = ( "image file is truncated " f"({len(b)} bytes not processed)" ) raise OSError(msg) b = b + s n, err_code = decoder.decode(b) if n < 0: break b = b[n:] finally: # Need to cleanup here to prevent leaks decoder.cleanup() self.tile = [] self.readonly = readonly self.load_end() if self._exclusive_fp and self._close_exclusive_fp_after_loading: self.fp.close() self.fp = None if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0: # still raised if decoder fails to return anything raise_oserror(err_code) return Image.Image.load(self) def load_prepare(self): # create image memory if necessary if not self.im or self.im.mode != self.mode or self.im.size != self.size: self.im = Image.core.new(self.mode, self.size) # create palette (optional) if self.mode == "P": Image.Image.load(self) def load_end(self): # may be overridden pass # may be defined for contained formats # def load_seek(self, pos): # pass # may be defined for blocked formats (e.g. PNG) # def load_read(self, bytes): # pass def _seek_check(self, frame): if ( frame < self._min_frame # Only check upper limit on frames if additional seek operations # are not required to do so or ( not (hasattr(self, "_n_frames") and self._n_frames is None) and frame >= self.n_frames + self._min_frame ) ): msg = "attempt to seek outside sequence" raise EOFError(msg) return self.tell() != frame def DQT(self, marker): # # Define quantization table. Note that there might be more # than one table in each marker. # FIXME: The quantization tables can be used to estimate the # compression quality. n = i16(self.fp.read(2)) - 2 s = ImageFile._safe_read(self.fp, n) while len(s): v = s[0] precision = 1 if (v // 16 == 0) else 2 # in bytes qt_length = 1 + precision * 64 if len(s) < qt_length: msg = "bad quantization table marker" raise SyntaxError(msg) data = array.array("B" if precision == 1 else "H", s[1:qt_length]) if sys.byteorder == "little" and precision > 1: data.byteswap() # the values are always big-endian self.quantization[v & 15] = [data[i] for i in zigzag_index] s = s[qt_length:]
null
174,111
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from ._binary import o16be as o16 from ._deprecate import deprecate from .JpegPresets import presets def _accept(prefix): # Magic number was taken from https://en.wikipedia.org/wiki/JPEG return prefix[:3] == b"\xFF\xD8\xFF"
null
174,112
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from ._binary import o16be as o16 from ._deprecate import deprecate from .JpegPresets import presets def _getexif(self): if "exif" not in self.info: return None return self.getexif()._get_merged_dict()
null
174,113
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from ._binary import o16be as o16 from ._deprecate import deprecate from .JpegPresets import presets def deprecate( deprecated: str, when: int | None, replacement: str | None = None, *, action: str | None = None, plural: bool = False, ) -> None: def convert_dict_qtables(qtables): deprecate("convert_dict_qtables", 10, action="Conversion is no longer needed") return qtables
null
174,114
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from ._binary import o16be as o16 from ._deprecate import deprecate from .JpegPresets import presets def _save_cjpeg(im, fp, filename): # ALTERNATIVE: handle JPEGs via the IJG command line utilities. tempfile = im._dump() subprocess.check_call(["cjpeg", "-outfile", filename, tempfile]) try: os.unlink(tempfile) except OSError: pass
null
174,115
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from ._binary import o16be as o16 from ._deprecate import deprecate from .JpegPresets import presets class JpegImageFile(ImageFile.ImageFile): format = "JPEG" format_description = "JPEG (ISO 10918)" def _open(self): s = self.fp.read(3) if not _accept(s): msg = "not a JPEG file" raise SyntaxError(msg) s = b"\xFF" # Create attributes self.bits = self.layers = 0 # JPEG specifics (internal) self.layer = [] self.huffman_dc = {} self.huffman_ac = {} self.quantization = {} self.app = {} # compatibility self.applist = [] self.icclist = [] while True: i = s[0] if i == 0xFF: s = s + self.fp.read(1) i = i16(s) else: # Skip non-0xFF junk s = self.fp.read(1) continue if i in MARKER: name, description, handler = MARKER[i] if handler is not None: handler(self, i) if i == 0xFFDA: # start of scan rawmode = self.mode if self.mode == "CMYK": rawmode = "CMYK;I" # assume adobe conventions self.tile = [("jpeg", (0, 0) + self.size, 0, (rawmode, ""))] # self.__offset = self.fp.tell() break s = self.fp.read(1) elif i == 0 or i == 0xFFFF: # padded marker or junk; move on s = b"\xff" elif i == 0xFF00: # Skip extraneous data (escaped 0xFF) s = self.fp.read(1) else: msg = "no marker found" raise SyntaxError(msg) def load_read(self, read_bytes): """ internal: read more image data For premature EOF and LOAD_TRUNCATED_IMAGES adds EOI marker so libjpeg can finish decoding """ s = self.fp.read(read_bytes) if not s and ImageFile.LOAD_TRUNCATED_IMAGES and not hasattr(self, "_ended"): # Premature EOF. # Pretend file is finished adding EOI marker self._ended = True return b"\xFF\xD9" return s def draft(self, mode, size): if len(self.tile) != 1: return # Protect from second call if self.decoderconfig: return d, e, o, a = self.tile[0] scale = 1 original_size = self.size if a[0] == "RGB" and mode in ["L", "YCbCr"]: self.mode = mode a = mode, "" if size: scale = min(self.size[0] // size[0], self.size[1] // size[1]) for s in [8, 4, 2, 1]: if scale >= s: break e = ( e[0], e[1], (e[2] - e[0] + s - 1) // s + e[0], (e[3] - e[1] + s - 1) // s + e[1], ) self._size = ((self.size[0] + s - 1) // s, (self.size[1] + s - 1) // s) scale = s self.tile = [(d, e, o, a)] self.decoderconfig = (scale, 0) box = (0, 0, original_size[0] / scale, original_size[1] / scale) return self.mode, box def load_djpeg(self): # ALTERNATIVE: handle JPEGs via the IJG command line utilities f, path = tempfile.mkstemp() os.close(f) if os.path.exists(self.filename): subprocess.check_call(["djpeg", "-outfile", path, self.filename]) else: msg = "Invalid Filename" raise ValueError(msg) try: with Image.open(path) as _im: _im.load() self.im = _im.im finally: try: os.unlink(path) except OSError: pass self.mode = self.im.mode self._size = self.im.size self.tile = [] def _getexif(self): return _getexif(self) def _getmp(self): return _getmp(self) def getxmp(self): """ Returns a dictionary containing the XMP tags. Requires defusedxml to be installed. :returns: XMP tags in a dictionary. """ for segment, content in self.applist: if segment == "APP1": marker, xmp_tags = content.rsplit(b"\x00", 1) if marker == b"http://ns.adobe.com/xap/1.0/": return self._getxmp(xmp_tags) return {} def _getmp(self): # Extract MP information. This method was inspired by the "highly # experimental" _getexif version that's been in use for years now, # itself based on the ImageFileDirectory class in the TIFF plugin. # The MP record essentially consists of a TIFF file embedded in a JPEG # application marker. try: data = self.info["mp"] except KeyError: return None file_contents = io.BytesIO(data) head = file_contents.read(8) endianness = ">" if head[:4] == b"\x4d\x4d\x00\x2a" else "<" # process dictionary from . import TiffImagePlugin try: info = TiffImagePlugin.ImageFileDirectory_v2(head) file_contents.seek(info.next) info.load(file_contents) mp = dict(info) except Exception as e: msg = "malformed MP Index (unreadable directory)" raise SyntaxError(msg) from e # it's an error not to have a number of images try: quant = mp[0xB001] except KeyError as e: msg = "malformed MP Index (no number of images)" raise SyntaxError(msg) from e # get MP entries mpentries = [] try: rawmpentries = mp[0xB002] for entrynum in range(0, quant): unpackedentry = struct.unpack_from( f"{endianness}LLLHH", rawmpentries, entrynum * 16 ) labels = ("Attribute", "Size", "DataOffset", "EntryNo1", "EntryNo2") mpentry = dict(zip(labels, unpackedentry)) mpentryattr = { "DependentParentImageFlag": bool(mpentry["Attribute"] & (1 << 31)), "DependentChildImageFlag": bool(mpentry["Attribute"] & (1 << 30)), "RepresentativeImageFlag": bool(mpentry["Attribute"] & (1 << 29)), "Reserved": (mpentry["Attribute"] & (3 << 27)) >> 27, "ImageDataFormat": (mpentry["Attribute"] & (7 << 24)) >> 24, "MPType": mpentry["Attribute"] & 0x00FFFFFF, } if mpentryattr["ImageDataFormat"] == 0: mpentryattr["ImageDataFormat"] = "JPEG" else: msg = "unsupported picture format in MPO" raise SyntaxError(msg) mptypemap = { 0x000000: "Undefined", 0x010001: "Large Thumbnail (VGA Equivalent)", 0x010002: "Large Thumbnail (Full HD Equivalent)", 0x020001: "Multi-Frame Image (Panorama)", 0x020002: "Multi-Frame Image: (Disparity)", 0x020003: "Multi-Frame Image: (Multi-Angle)", 0x030000: "Baseline MP Primary Image", } mpentryattr["MPType"] = mptypemap.get(mpentryattr["MPType"], "Unknown") mpentry["Attribute"] = mpentryattr mpentries.append(mpentry) mp[0xB002] = mpentries except KeyError as e: msg = "malformed MP Index (bad MP Entry)" raise SyntaxError(msg) from e # Next we should try and parse the individual image unique ID list; # we don't because I've never seen this actually used in a real MPO # file and so can't test it. return mp class MpoImageFile(JpegImagePlugin.JpegImageFile): format = "MPO" format_description = "MPO (CIPA DC-007)" _close_exclusive_fp_after_loading = False def _open(self): self.fp.seek(0) # prep the fp in order to pass the JPEG test JpegImagePlugin.JpegImageFile._open(self) self._after_jpeg_open() def _after_jpeg_open(self, mpheader=None): self._initial_size = self.size self.mpinfo = mpheader if mpheader is not None else self._getmp() self.n_frames = self.mpinfo[0xB001] self.__mpoffsets = [ mpent["DataOffset"] + self.info["mpoffset"] for mpent in self.mpinfo[0xB002] ] self.__mpoffsets[0] = 0 # Note that the following assertion will only be invalid if something # gets broken within JpegImagePlugin. assert self.n_frames == len(self.__mpoffsets) del self.info["mpoffset"] # no longer needed self.is_animated = self.n_frames > 1 self._fp = self.fp # FIXME: hack self._fp.seek(self.__mpoffsets[0]) # get ready to read first frame self.__frame = 0 self.offset = 0 # for now we can only handle reading and individual frame extraction self.readonly = 1 def load_seek(self, pos): self._fp.seek(pos) def seek(self, frame): if not self._seek_check(frame): return self.fp = self._fp self.offset = self.__mpoffsets[frame] self.fp.seek(self.offset + 2) # skip SOI marker segment = self.fp.read(2) if not segment: msg = "No data found for frame" raise ValueError(msg) self._size = self._initial_size if i16(segment) == 0xFFE1: # APP1 n = i16(self.fp.read(2)) - 2 self.info["exif"] = ImageFile._safe_read(self.fp, n) self._reload_exif() mptype = self.mpinfo[0xB002][frame]["Attribute"]["MPType"] if mptype.startswith("Large Thumbnail"): exif = self.getexif().get_ifd(ExifTags.IFD.Exif) if 40962 in exif and 40963 in exif: self._size = (exif[40962], exif[40963]) elif "exif" in self.info: del self.info["exif"] self._reload_exif() self.tile = [("jpeg", (0, 0) + self.size, self.offset, (self.mode, ""))] self.__frame = frame def tell(self): return self.__frame def adopt(jpeg_instance, mpheader=None): """ Transform the instance of JpegImageFile into an instance of MpoImageFile. After the call, the JpegImageFile is extended to be an MpoImageFile. This is essentially useful when opening a JPEG file that reveals itself as an MPO, to avoid double call to _open. """ jpeg_instance.__class__ = MpoImageFile jpeg_instance._after_jpeg_open(mpheader) return jpeg_instance def jpeg_factory(fp=None, filename=None): im = JpegImageFile(fp, filename) try: mpheader = im._getmp() if mpheader[45057] > 1: # It's actually an MPO from .MpoImagePlugin import MpoImageFile # Don't reload everything, just convert it. im = MpoImageFile.adopt(im, mpheader) except (TypeError, IndexError): # It is really a JPEG pass except SyntaxError: warnings.warn( "Image appears to be a malformed MPO file, it will be " "interpreted as a base JPEG file" ) return im
null
174,116
import os import shutil import subprocess import sys import tempfile from . import Image class Image: def __init__(self): def __getattr__(self, name): def width(self): def height(self): def size(self): def _new(self, im): def __enter__(self): def __exit__(self, *args): def close(self): def _copy(self): def _ensure_mutable(self): def _dump(self, file=None, format=None, **options): def __eq__(self, other): def __repr__(self): def _repr_pretty_(self, p, cycle): def _repr_png_(self): def __array_interface__(self): def __getstate__(self): def __setstate__(self, state): def tobytes(self, encoder_name="raw", *args): def tobitmap(self, name="image"): def frombytes(self, data, decoder_name="raw", *args): def load(self): def verify(self): def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): def convert_transparency(m, v): def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): def copy(self): def crop(self, box=None): def _crop(self, im, box): def draft(self, mode, size): def _expand(self, xmargin, ymargin=None): def filter(self, filter): def getbands(self): def getbbox(self): def getcolors(self, maxcolors=256): def getdata(self, band=None): def getextrema(self): def _getxmp(self, xmp_tags): def get_name(tag): def get_value(element): def getexif(self): def _reload_exif(self): def get_child_images(self): def getim(self): def getpalette(self, rawmode="RGB"): def apply_transparency(self): def getpixel(self, xy): def getprojection(self): def histogram(self, mask=None, extrema=None): def entropy(self, mask=None, extrema=None): def paste(self, im, box=None, mask=None): def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): def point(self, lut, mode=None): def putalpha(self, alpha): def putdata(self, data, scale=1.0, offset=0.0): def putpalette(self, data, rawmode="RGB"): def putpixel(self, xy, value): def remap_palette(self, dest_map, source_palette=None): def _get_safe_box(self, size, resample, box): def resize(self, size, resample=None, box=None, reducing_gap=None): def reduce(self, factor, box=None): def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): def transform(x, y, matrix): def save(self, fp, format=None, **params): def seek(self, frame): def show(self, title=None): def split(self): def getchannel(self, channel): def tell(self): def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): def preserve_aspect_ratio(): def round_aspect(number, key): def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): def transpose(self, method): def effect_spread(self, distance): def toqimage(self): def toqpixmap(self): def grab(bbox=None, include_layered_windows=False, all_screens=False, xdisplay=None): if xdisplay is None: if sys.platform == "darwin": fh, filepath = tempfile.mkstemp(".png") os.close(fh) args = ["screencapture"] if bbox: left, top, right, bottom = bbox args += ["-R", f"{left},{top},{right-left},{bottom-top}"] subprocess.call(args + ["-x", filepath]) im = Image.open(filepath) im.load() os.unlink(filepath) if bbox: im_resized = im.resize((right - left, bottom - top)) im.close() return im_resized return im elif sys.platform == "win32": offset, size, data = Image.core.grabscreen_win32( include_layered_windows, all_screens ) im = Image.frombytes( "RGB", size, data, # RGB, 32-bit line padding, origin lower left corner "raw", "BGR", (size[0] * 3 + 3) & -4, -1, ) if bbox: x0, y0 = offset left, top, right, bottom = bbox im = im.crop((left - x0, top - y0, right - x0, bottom - y0)) return im elif shutil.which("gnome-screenshot"): fh, filepath = tempfile.mkstemp(".png") os.close(fh) subprocess.call(["gnome-screenshot", "-f", filepath]) im = Image.open(filepath) im.load() os.unlink(filepath) if bbox: im_cropped = im.crop(bbox) im.close() return im_cropped return im # use xdisplay=None for default display on non-win32/macOS systems if not Image.core.HAVE_XCB: msg = "Pillow was built without XCB support" raise OSError(msg) size, data = Image.core.grabscreen_x11(xdisplay) im = Image.frombytes("RGB", size, data, "raw", "BGRX", size[0] * 4, 1) if bbox: im = im.crop(bbox) return im
null
174,117
import os import shutil import subprocess import sys import tempfile from . import Image class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": deprecate("Image categories", 10, "is_animated", plural=True) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None def close(self): """ Closes the file pointer, if possible. This operation will destroy the image core and release its memory. The image data will be unusable afterward. This function is required to close images that have multiple frames or have not had their file read and closed by the :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for more information. """ try: if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = DeferredError(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_pretty_(self, p, cycle): """IPython plain text display support""" # Same as __repr__ but without unpredictable id(self), # to keep Jupyter notebook `text/plain` output stable. p.text( "<%s.%s image mode=%s size=%dx%d>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], ) ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: msg = "Could not save to PNG for display" raise ValueError(msg) from e return b.getvalue() def __array_interface__(self): # numpy array interface support new = {"version": 3} try: if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() except Exception as e: if not isinstance(e, (MemoryError, RecursionError)): try: import numpy from packaging.version import parse as parse_version except ImportError: pass else: if parse_version(numpy.__version__) < parse_version("1.23"): warnings.warn(e) raise new["shape"], new["typestr"] = _conv_type_shape(self) return new def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. A list of C encoders can be seen under codecs section of the function array in :file:`_imaging.c`. Python encoders are registered within the relevant plugins. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() if self.width == 0 or self.height == 0: return b"" # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c output = [] while True: bytes_consumed, errcode, data = e.encode(bufsize) output.append(data) if errcode: break if errcode < 0: msg = f"encoder error {errcode} in tobytes" raise RuntimeError(msg) return b"".join(output) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": msg = "not a bitmap" raise ValueError(msg) data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: msg = "not enough image data" raise ValueError(msg) if s[1] != 0: msg = "cannot decode image data" raise ValueError(msg) def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im is not None and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: palette_mode = "RGBA" if mode.startswith("RGBA") else "RGB" self.palette.mode = palette_mode self.palette.palette = self.im.getpalette(palette_mode, palette_mode) if self.im is not None: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK". The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is ``None``, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. When converting from "PA", if an "RGBA" palette is present, the alpha channel from the image will be used instead of the values from the palette. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`Palette.WEB` or :data:`Palette.ADAPTIVE`. :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): msg = "illegal conversion" raise ValueError(msg) im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if (self.mode in ("1", "L", "I") and mode in ("LA", "RGBA")) or ( self.mode == "RGB" and mode == "RGBA" ): # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: msg = "Transparency for P mode should be bytes or int" raise ValueError(msg) if mode == "P" and palette == Palette.ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new if "LAB" in (self.mode, mode): other_mode = mode if self.mode == "LAB" else self.mode if other_mode in ("RGB", "RGBA", "RGBX"): from . import ImageCms srgb = ImageCms.createProfile("sRGB") lab = ImageCms.createProfile("LAB") profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab] transform = ImageCms.buildTransform( profiles[0], profiles[1], self.mode, mode ) return transform.apply(self) # colorspace conversion if dither is None: dither = Dither.FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again modebase = getmodebase(self.mode) if modebase == self.mode: raise im = self.im.convert(modebase) im = im.convert(mode, dither) except KeyError as e: msg = "illegal conversion" raise ValueError(msg) from e new_im = self._new(im) if mode == "P" and palette != Palette.ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`Quantize.MEDIANCUT` (median cut), :data:`Quantize.MAXCOVERAGE` (maximum coverage), :data:`Quantize.FASTOCTREE` (fast octree), :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`Quantize.MEDIANCUT` will be used. The exception to this is RGBA images. :data:`Quantize.MEDIANCUT` and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so :data:`Quantize.FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). :returns: A new image """ self.load() if method is None: # defaults: method = Quantize.MEDIANCUT if self.mode == "RGBA": method = Quantize.FASTOCTREE if self.mode == "RGBA" and method not in ( Quantize.FASTOCTREE, Quantize.LIBIMAGEQUANT, ): # Caller specified an invalid mode. msg = ( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) raise ValueError(msg) if palette: # use palette from reference image palette.load() if palette.mode != "P": msg = "bad mode for palette image" raise ValueError(msg) if self.mode != "RGB" and self.mode != "L": msg = "only RGB or L mode images can be quantized to a palette" raise ValueError(msg) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() if box[2] < box[0]: msg = "Coordinate 'right' is less than 'left'" raise ValueError(msg) elif box[3] < box[1]: msg = "Coordinate 'lower' is less than 'upper'" raise ValueError(msg) self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size in pixels, as a 2-tuple: (width, height). """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): msg = "filter argument should be ImageFilter.Filter instance or class" raise TypeError(msg) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): """ Gets EXIF data from the image. :returns: an :py:class:`~PIL.Image.Exif` object. """ if self._exif is None: self._exif = Exif() self._exif._loaded = False elif self._exif._loaded: return self._exif self._exif._loaded = True exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.bigtiff = self.tag_v2._bigtiff self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation(="|>)([0-9])', xmp_tags) if match: self._exif[0x0112] = int(match[2]) return self._exif def _reload_exif(self): if self._exif is None or not self._exif._loaded: return self._exif._loaded = False self.getexif() def get_child_images(self): child_images = [] exif = self.getexif() ifds = [] if ExifTags.Base.SubIFDs in exif: subifd_offsets = exif[ExifTags.Base.SubIFDs] if subifd_offsets: if not isinstance(subifd_offsets, tuple): subifd_offsets = (subifd_offsets,) for subifd_offset in subifd_offsets: ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset)) ifd1 = exif.get_ifd(ExifTags.IFD.IFD1) if ifd1 and ifd1.get(513): ifds.append((ifd1, exif._info.next)) offset = None for ifd, ifd_offset in ifds: current_offset = self.fp.tell() if offset is None: offset = current_offset fp = self.fp thumbnail_offset = ifd.get(513) if thumbnail_offset is not None: try: thumbnail_offset += self._exif_offset except AttributeError: pass self.fp.seek(thumbnail_offset) data = self.fp.read(ifd.get(514)) fp = io.BytesIO(data) with open(fp) as im: if thumbnail_offset is None: im._frame_pos = [ifd_offset] im._seek(0) im.load() child_images.append(im) if offset is not None: self.fp.seek(offset) return child_images def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self, rawmode="RGB"): """ Returns the image palette as a list. :param rawmode: The mode in which to return the palette. ``None`` will return the palette in its current mode. .. versionadded:: 9.1.0 :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: mode = self.im.getpalettemode() except ValueError: return None # no palette if rawmode is None: rawmode = mode return list(self.im.getpalette(mode, rawmode)) def apply_transparency(self): """ If a P mode image has a "transparency" key in the info dictionary, remove the key and instead apply the transparency to the palette. Otherwise, the image is unchanged. """ if self.mode != "P" or "transparency" not in self.info: return from . import ImagePalette palette = self.getpalette("RGBA") transparency = self.info["transparency"] if isinstance(transparency, bytes): for i, alpha in enumerate(transparency): palette[i * 4 + 3] = alpha else: palette[transparency * 4 + 3] = 0 self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette)) self.palette.dirty = 1 del self.info["transparency"] def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. Counts are grouped into 256 bins for each band, even if the image has more than 8 bits per band. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", "LA", "RGBA" or "RGBa" images (if present, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? msg = "cannot determine region size; use 4-item box" raise ValueError(msg) box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): msg = "Source must be a tuple" raise ValueError(msg) if not isinstance(dest, (list, tuple)): msg = "Destination must be a tuple" raise ValueError(msg) if not len(source) in (2, 4): msg = "Source must be a 2 or 4-tuple" raise ValueError(msg) if not len(dest) == 2: msg = "Destination must be a 2-tuple" raise ValueError(msg) if min(source) < 0: msg = "Source must be non-negative" raise ValueError(msg) if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case msg = "point operation not supported for this mode" raise ValueError(msg) if mode != "F": lut = [round(i) for i in lut] return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: msg = "illegal image mode" raise ValueError(msg) from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): msg = "illegal image mode" raise ValueError(msg) alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): msg = "illegal image mode" raise ValueError(msg) if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P and PA images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode in ("P", "PA") and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P or PA image if self.mode == "PA": alpha = value[3] if len(value) == 4 else 255 value = value[:3] value = self.palette.getcolor(value, self) if self.mode == "PA": value = (value, alpha) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): msg = "illegal image mode" raise ValueError(msg) bands = 3 palette_mode = "RGB" if source_palette is None: if self.mode == "P": self.load() palette_mode = self.im.getpalettemode() if palette_mode == "RGBA": bands = 4 source_palette = self.im.getpalette(palette_mode, palette_mode) else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[ oldPosition * bands : oldPosition * bands + bands ] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette( palette_mode, palette=mapping_palette * bands ) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette(palette_mode + ";L", m_im.palette.tobytes()) m_im = m_im.convert("L") m_im.putpalette(palette_bytes, palette_mode) m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes) if "transparency" in self.info: try: m_im.info["transparency"] = dest_map.index(self.info["transparency"]) except ValueError: if "transparency" in m_im.info: del m_im.info["transparency"] return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`Resampling.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`Resampling.NEAREST`. Otherwise, the default filter is :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = Resampling.NEAREST if type_special else Resampling.BICUBIC elif resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, Resampling.LANCZOS, Resampling.BOX, Resampling.HAMMING, ): msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), (Resampling.BOX, "Image.Resampling.BOX"), (Resampling.HAMMING, "Image.Resampling.HAMMING"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) if reducing_gap is not None and reducing_gap < 1.0: msg = "reducing_gap must be 1.0 or greater" raise ValueError(msg) size = tuple(size) self.load() if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = Resampling.NEAREST if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != Resampling.NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(Transpose.ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose( Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270 ) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform( (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor ) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif is_path(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and is_path(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: msg = f"unknown file extension: {ext}" raise ValueError(msg) from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] created = False if open_fp: created = not os.path.exists(filename) if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) except Exception: if open_fp: fp.close() if created: try: os.remove(filename) except PermissionError: pass raise if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: msg = f'The image has no channel "{channel}"' raise ValueError(msg) from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: Optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If omitted, it defaults to :py:data:`Resampling.BICUBIC`. (was :py:data:`Resampling.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ provided_size = tuple(map(math.floor, size)) def preserve_aspect_ratio(): def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) x, y = provided_size if x >= self.width and y >= self.height: return aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) return x, y box = None if reducing_gap is not None: size = preserve_aspect_ratio() if size is None: return res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if box is None: self.load() # load() may have changed the size of the image size = preserve_aspect_ratio() if size is None: return if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size in pixels, as a 2-tuple: (width, height). :param method: The transformation method. This is one of :py:data:`Transform.EXTENT` (cut out a rectangular subregion), :py:data:`Transform.AFFINE` (affine transform), :py:data:`Transform.PERSPECTIVE` (perspective transform), :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or :py:data:`Transform.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.Transform.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: msg = "missing method data" raise ValueError(msg) im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == Transform.MESH: # list of quads for box, quad in data: im.__transformer( box, self, Transform.QUAD, quad, resample, fillcolor is None ) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): w = box[2] - box[0] h = box[3] - box[1] if method == Transform.AFFINE: data = data[:6] elif method == Transform.EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = Transform.AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == Transform.PERSPECTIVE: data = data[:8] elif method == Transform.QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: msg = "unknown transformation method" raise ValueError(msg) if resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, ): if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS): msg = { Resampling.BOX: "Image.Resampling.BOX", Resampling.HAMMING: "Image.Resampling.HAMMING", Resampling.LANCZOS: "Image.Resampling.LANCZOS", }[resample] + f" ({resample}) cannot be used." else: msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) image.load() self.load() if image.mode in ("1", "P"): resample = Resampling.NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`, :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`, :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`, :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqpixmap(self) def grabclipboard(): if sys.platform == "darwin": fh, filepath = tempfile.mkstemp(".jpg") os.close(fh) commands = [ 'set theFile to (open for access POSIX file "' + filepath + '" with write permission)', "try", " write (the clipboard as JPEG picture) to theFile", "end try", "close access theFile", ] script = ["osascript"] for command in commands: script += ["-e", command] subprocess.call(script) im = None if os.stat(filepath).st_size != 0: im = Image.open(filepath) im.load() os.unlink(filepath) return im elif sys.platform == "win32": fmt, data = Image.core.grabclipboard_win32() if fmt == "file": # CF_HDROP import struct o = struct.unpack_from("I", data)[0] if data[16] != 0: files = data[o:].decode("utf-16le").split("\0") else: files = data[o:].decode("mbcs").split("\0") return files[: files.index("")] if isinstance(data, bytes): import io data = io.BytesIO(data) if fmt == "png": from . import PngImagePlugin return PngImagePlugin.PngImageFile(data) elif fmt == "DIB": from . import BmpImagePlugin return BmpImagePlugin.DibImageFile(data) return None else: if shutil.which("wl-paste"): args = ["wl-paste"] elif shutil.which("xclip"): args = ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"] else: msg = "wl-paste or xclip is required for ImageGrab.grabclipboard() on Linux" raise NotImplementedError(msg) fh, filepath = tempfile.mkstemp() subprocess.call(args, stdout=fh) os.close(fh) im = Image.open(filepath) im.load() os.unlink(filepath) return im
null
174,120
import os import re from . import Image, ImageFile, ImagePalette for i in ["8", "8S", "16", "16S", "32", "32F"]: OPEN[f"L {i} image"] = ("F", f"F;{i}") OPEN[f"L*{i} image"] = ("F", f"F;{i}") for i in ["16", "16L", "16B"]: OPEN[f"L {i} image"] = (f"I;{i}", f"I;{i}") OPEN[f"L*{i} image"] = (f"I;{i}", f"I;{i}") for i in ["32S"]: OPEN[f"L {i} image"] = ("I", f"I;{i}") OPEN[f"L*{i} image"] = ("I", f"I;{i}") for i in range(2, 33): OPEN[f"L*{i} image"] = ("F", f"F;{i}") SAVE = { # mode: (im type, raw mode) "1": ("0 1", "1"), "L": ("Greyscale", "L"), "LA": ("LA", "LA;L"), "P": ("Greyscale", "P"), "PA": ("LA", "PA;L"), "I": ("L 32S", "I;32S"), "I;16": ("L 16", "I;16"), "I;16L": ("L 16L", "I;16L"), "I;16B": ("L 16B", "I;16B"), "F": ("L 32F", "F;32F"), "RGB": ("RGB", "RGB;L"), "RGBA": ("RGBA", "RGBA;L"), "RGBX": ("RGBX", "RGBX;L"), "CMYK": ("CMYK", "CMYK;L"), "YCbCr": ("YCC", "YCbCr;L"), } class ImageFile(Image.Image): """Base class for image file format handlers.""" def __init__(self, fp=None, filename=None): super().__init__() self._min_frame = 0 self.custom_mimetype = None self.tile = None """ A list of tile descriptors, or ``None`` """ self.readonly = 1 # until we know better self.decoderconfig = () self.decodermaxblock = MAXBLOCK if is_path(fp): # filename self.fp = open(fp, "rb") self.filename = fp self._exclusive_fp = True else: # stream self.fp = fp self.filename = filename # can be overridden self._exclusive_fp = None try: try: self._open() except ( IndexError, # end of data TypeError, # end of data (ord) KeyError, # unsupported mode EOFError, # got header but not the first frame struct.error, ) as v: raise SyntaxError(v) from v if not self.mode or self.size[0] <= 0 or self.size[1] <= 0: msg = "not identified by this driver" raise SyntaxError(msg) except BaseException: # close the file only if we have opened it this constructor if self._exclusive_fp: self.fp.close() raise def get_format_mimetype(self): if self.custom_mimetype: return self.custom_mimetype if self.format is not None: return Image.MIME.get(self.format.upper()) def __setstate__(self, state): self.tile = [] super().__setstate__(state) def verify(self): """Check file integrity""" # raise exception if something's wrong. must be called # directly after open, and closes file when finished. if self._exclusive_fp: self.fp.close() self.fp = None def load(self): """Load image data based on tile list""" if self.tile is None: msg = "cannot load this image" raise OSError(msg) pixel = Image.Image.load(self) if not self.tile: return pixel self.map = None use_mmap = self.filename and len(self.tile) == 1 # As of pypy 2.1.0, memory mapping was failing here. use_mmap = use_mmap and not hasattr(sys, "pypy_version_info") readonly = 0 # look for read/seek overrides try: read = self.load_read # don't use mmap if there are custom read/seek functions use_mmap = False except AttributeError: read = self.fp.read try: seek = self.load_seek use_mmap = False except AttributeError: seek = self.fp.seek if use_mmap: # try memory mapping decoder_name, extents, offset, args = self.tile[0] if ( decoder_name == "raw" and len(args) >= 3 and args[0] == self.mode and args[0] in Image._MAPMODES ): try: # use mmap, if possible import mmap with open(self.filename) as fp: self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ) if offset + self.size[1] * args[1] > self.map.size(): # buffer is not large enough raise OSError self.im = Image.core.map_buffer( self.map, self.size, decoder_name, offset, args ) readonly = 1 # After trashing self.im, # we might need to reload the palette data. if self.palette: self.palette.dirty = 1 except (AttributeError, OSError, ImportError): self.map = None self.load_prepare() err_code = -3 # initialize to unknown error if not self.map: # sort tiles in file order self.tile.sort(key=_tilesort) try: # FIXME: This is a hack to handle TIFF's JpegTables tag. prefix = self.tile_prefix except AttributeError: prefix = b"" # Remove consecutive duplicates that only differ by their offset self.tile = [ list(tiles)[-1] for _, tiles in itertools.groupby( self.tile, lambda tile: (tile[0], tile[1], tile[3]) ) ] for decoder_name, extents, offset, args in self.tile: seek(offset) decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) err_code = decoder.decode(b"")[1] else: b = prefix while True: try: s = read(self.decodermaxblock) except (IndexError, struct.error) as e: # truncated png/gif if LOAD_TRUNCATED_IMAGES: break else: msg = "image file is truncated" raise OSError(msg) from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: msg = ( "image file is truncated " f"({len(b)} bytes not processed)" ) raise OSError(msg) b = b + s n, err_code = decoder.decode(b) if n < 0: break b = b[n:] finally: # Need to cleanup here to prevent leaks decoder.cleanup() self.tile = [] self.readonly = readonly self.load_end() if self._exclusive_fp and self._close_exclusive_fp_after_loading: self.fp.close() self.fp = None if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0: # still raised if decoder fails to return anything raise_oserror(err_code) return Image.Image.load(self) def load_prepare(self): # create image memory if necessary if not self.im or self.im.mode != self.mode or self.im.size != self.size: self.im = Image.core.new(self.mode, self.size) # create palette (optional) if self.mode == "P": Image.Image.load(self) def load_end(self): # may be overridden pass # may be defined for contained formats # def load_seek(self, pos): # pass # may be defined for blocked formats (e.g. PNG) # def load_read(self, bytes): # pass def _seek_check(self, frame): if ( frame < self._min_frame # Only check upper limit on frames if additional seek operations # are not required to do so or ( not (hasattr(self, "_n_frames") and self._n_frames is None) and frame >= self.n_frames + self._min_frame ) ): msg = "attempt to seek outside sequence" raise EOFError(msg) return self.tell() != frame def _save(im, fp, filename): try: image_type, rawmode = SAVE[im.mode] except KeyError as e: msg = f"Cannot save {im.mode} images as IM" raise ValueError(msg) from e frames = im.encoderinfo.get("frames", 1) fp.write(f"Image type: {image_type} image\r\n".encode("ascii")) if filename: # Each line must be 100 characters or less, # or: SyntaxError("not an IM file") # 8 characters are used for "Name: " and "\r\n" # Keep just the filename, ditch the potentially overlong path name, ext = os.path.splitext(os.path.basename(filename)) name = "".join([name[: 92 - len(ext)], ext]) fp.write(f"Name: {name}\r\n".encode("ascii")) fp.write(("Image size (x*y): %d*%d\r\n" % im.size).encode("ascii")) fp.write(f"File size (no of images): {frames}\r\n".encode("ascii")) if im.mode in ["P", "PA"]: fp.write(b"Lut: 1\r\n") fp.write(b"\000" * (511 - fp.tell()) + b"\032") if im.mode in ["P", "PA"]: im_palette = im.im.getpalette("RGB", "RGB;L") colors = len(im_palette) // 3 palette = b"" for i in range(3): palette += im_palette[colors * i : colors * (i + 1)] palette += b"\x00" * (256 - colors) fp.write(palette) # 768 bytes ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))])
null
174,122
import os from . import Image, ImageFile from ._binary import i32be as i32 from ._binary import o8 def _accept(prefix): return prefix[:4] == b"qoif"
null
174,123
from math import log, pi, sin, sqrt from ._binary import o8 EPSILON = 1e-10 def log(x: SupportsFloat, base: SupportsFloat = ...) -> float: ... def curved(middle, pos): return pos ** (log(0.5) / log(max(middle, EPSILON)))
null
174,124
from math import log, pi, sin, sqrt from ._binary import o8 def linear(middle, pos): pi: float def sin(__x: SupportsFloat) -> float: def sine(middle, pos): return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0
null
174,125
from math import log, pi, sin, sqrt from ._binary import o8 def linear(middle, pos): if pos <= middle: if middle < EPSILON: return 0.0 else: return 0.5 * pos / middle else: pos = pos - middle middle = 1.0 - middle if middle < EPSILON: return 1.0 else: return 0.5 + 0.5 * pos / middle def sqrt(__x: SupportsFloat) -> float: ... def sphere_increasing(middle, pos): return sqrt(1.0 - (linear(middle, pos) - 1.0) ** 2)
null
174,126
from math import log, pi, sin, sqrt from ._binary import o8 def linear(middle, pos): def sqrt(__x: SupportsFloat) -> float: def sphere_decreasing(middle, pos): return 1.0 - sqrt(1.0 - linear(middle, pos) ** 2)
null
174,127
import os from . import Image, ImageFile, ImagePalette from ._binary import i16le as i16 from ._binary import i32le as i32 from ._binary import o8 from ._binary import o16le as o16 from ._binary import o32le as o32 def _accept(prefix): return prefix[:2] == b"BM"
null
174,128
import os from . import Image, ImageFile, ImagePalette from ._binary import i16le as i16 from ._binary import i32le as i32 from ._binary import o8 from ._binary import o16le as o16 from ._binary import o32le as o32 def _dib_accept(prefix): return i32(prefix) in [12, 40, 64, 108, 124]
null
174,129
import os from . import Image, ImageFile, ImagePalette from ._binary import i16le as i16 from ._binary import i32le as i32 from ._binary import o8 from ._binary import o16le as o16 from ._binary import o32le as o32 def _save(im, fp, filename, bitmap_header=True): try: rawmode, bits, colors = SAVE[im.mode] except KeyError as e: msg = f"cannot write mode {im.mode} as BMP" raise OSError(msg) from e info = im.encoderinfo dpi = info.get("dpi", (96, 96)) # 1 meter == 39.3701 inches ppm = tuple(map(lambda x: int(x * 39.3701 + 0.5), dpi)) stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3) header = 40 # or 64 for OS/2 version 2 image = stride * im.size[1] if im.mode == "1": palette = b"".join(o8(i) * 4 for i in (0, 255)) elif im.mode == "L": palette = b"".join(o8(i) * 4 for i in range(256)) elif im.mode == "P": palette = im.im.getpalette("RGB", "BGRX") colors = len(palette) // 4 else: palette = None # bitmap header if bitmap_header: offset = 14 + header + colors * 4 file_size = offset + image if file_size > 2**32 - 1: msg = "File size is too large for the BMP format" raise ValueError(msg) fp.write( b"BM" # file type (magic) + o32(file_size) # file size + o32(0) # reserved + o32(offset) # image data offset ) # bitmap info header fp.write( o32(header) # info header size + o32(im.size[0]) # width + o32(im.size[1]) # height + o16(1) # planes + o16(bits) # depth + o32(0) # compression (0=uncompressed) + o32(image) # size of bitmap + o32(ppm[0]) # resolution + o32(ppm[1]) # resolution + o32(colors) # colors used + o32(colors) # colors important ) fp.write(b"\0" * (header - 40)) # padding (for OS/2 format) if palette: fp.write(palette) ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))]) def _dib_save(im, fp, filename): _save(im, fp, filename, False)
null
174,130
import os from . import Image, ImageFile, ImagePalette from ._binary import i16le as i16 from ._binary import i32le as i32 from ._binary import o8 def _accept(prefix): return ( len(prefix) >= 6 and i16(prefix, 4) in [0xAF11, 0xAF12] and i16(prefix, 14) in [0, 3] # flags )
null
174,131
import warnings from io import BytesIO from math import ceil, log from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin from ._binary import i16le as i16 from ._binary import i32le as i32 from ._binary import o8 from ._binary import o16le as o16 from ._binary import o32le as o32 _MAGIC = b"\0\0\1\0" Image.register_open(IcoImageFile.format, IcoImageFile, _accept) Image.register_save(IcoImageFile.format, _save) Image.register_extension(IcoImageFile.format, ".ico") Image.register_mime(IcoImageFile.format, "image/x-icon") class BytesIO(BufferedIOBase, BinaryIO): def __init__(self, initial_bytes: bytes = ...) -> None: ... # BytesIO does not contain a "name" field. This workaround is necessary # to allow BytesIO sub-classes to add this field, as it is defined # as a read-only property on IO[]. name: Any def __enter__(self: _T) -> _T: ... def getvalue(self) -> bytes: ... def getbuffer(self) -> memoryview: ... if sys.version_info >= (3, 7): def read1(self, __size: Optional[int] = ...) -> bytes: ... else: def read1(self, __size: Optional[int]) -> bytes: ... # type: ignore class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": deprecate("Image categories", 10, "is_animated", plural=True) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None def close(self): """ Closes the file pointer, if possible. This operation will destroy the image core and release its memory. The image data will be unusable afterward. This function is required to close images that have multiple frames or have not had their file read and closed by the :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for more information. """ try: if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = DeferredError(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_pretty_(self, p, cycle): """IPython plain text display support""" # Same as __repr__ but without unpredictable id(self), # to keep Jupyter notebook `text/plain` output stable. p.text( "<%s.%s image mode=%s size=%dx%d>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], ) ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: msg = "Could not save to PNG for display" raise ValueError(msg) from e return b.getvalue() def __array_interface__(self): # numpy array interface support new = {"version": 3} try: if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() except Exception as e: if not isinstance(e, (MemoryError, RecursionError)): try: import numpy from packaging.version import parse as parse_version except ImportError: pass else: if parse_version(numpy.__version__) < parse_version("1.23"): warnings.warn(e) raise new["shape"], new["typestr"] = _conv_type_shape(self) return new def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. A list of C encoders can be seen under codecs section of the function array in :file:`_imaging.c`. Python encoders are registered within the relevant plugins. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() if self.width == 0 or self.height == 0: return b"" # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c output = [] while True: bytes_consumed, errcode, data = e.encode(bufsize) output.append(data) if errcode: break if errcode < 0: msg = f"encoder error {errcode} in tobytes" raise RuntimeError(msg) return b"".join(output) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": msg = "not a bitmap" raise ValueError(msg) data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: msg = "not enough image data" raise ValueError(msg) if s[1] != 0: msg = "cannot decode image data" raise ValueError(msg) def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im is not None and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: palette_mode = "RGBA" if mode.startswith("RGBA") else "RGB" self.palette.mode = palette_mode self.palette.palette = self.im.getpalette(palette_mode, palette_mode) if self.im is not None: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK". The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is ``None``, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. When converting from "PA", if an "RGBA" palette is present, the alpha channel from the image will be used instead of the values from the palette. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`Palette.WEB` or :data:`Palette.ADAPTIVE`. :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): msg = "illegal conversion" raise ValueError(msg) im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if (self.mode in ("1", "L", "I") and mode in ("LA", "RGBA")) or ( self.mode == "RGB" and mode == "RGBA" ): # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: msg = "Transparency for P mode should be bytes or int" raise ValueError(msg) if mode == "P" and palette == Palette.ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new if "LAB" in (self.mode, mode): other_mode = mode if self.mode == "LAB" else self.mode if other_mode in ("RGB", "RGBA", "RGBX"): from . import ImageCms srgb = ImageCms.createProfile("sRGB") lab = ImageCms.createProfile("LAB") profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab] transform = ImageCms.buildTransform( profiles[0], profiles[1], self.mode, mode ) return transform.apply(self) # colorspace conversion if dither is None: dither = Dither.FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again modebase = getmodebase(self.mode) if modebase == self.mode: raise im = self.im.convert(modebase) im = im.convert(mode, dither) except KeyError as e: msg = "illegal conversion" raise ValueError(msg) from e new_im = self._new(im) if mode == "P" and palette != Palette.ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`Quantize.MEDIANCUT` (median cut), :data:`Quantize.MAXCOVERAGE` (maximum coverage), :data:`Quantize.FASTOCTREE` (fast octree), :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`Quantize.MEDIANCUT` will be used. The exception to this is RGBA images. :data:`Quantize.MEDIANCUT` and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so :data:`Quantize.FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). :returns: A new image """ self.load() if method is None: # defaults: method = Quantize.MEDIANCUT if self.mode == "RGBA": method = Quantize.FASTOCTREE if self.mode == "RGBA" and method not in ( Quantize.FASTOCTREE, Quantize.LIBIMAGEQUANT, ): # Caller specified an invalid mode. msg = ( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) raise ValueError(msg) if palette: # use palette from reference image palette.load() if palette.mode != "P": msg = "bad mode for palette image" raise ValueError(msg) if self.mode != "RGB" and self.mode != "L": msg = "only RGB or L mode images can be quantized to a palette" raise ValueError(msg) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() if box[2] < box[0]: msg = "Coordinate 'right' is less than 'left'" raise ValueError(msg) elif box[3] < box[1]: msg = "Coordinate 'lower' is less than 'upper'" raise ValueError(msg) self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size in pixels, as a 2-tuple: (width, height). """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): msg = "filter argument should be ImageFilter.Filter instance or class" raise TypeError(msg) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): """ Gets EXIF data from the image. :returns: an :py:class:`~PIL.Image.Exif` object. """ if self._exif is None: self._exif = Exif() self._exif._loaded = False elif self._exif._loaded: return self._exif self._exif._loaded = True exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.bigtiff = self.tag_v2._bigtiff self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation(="|>)([0-9])', xmp_tags) if match: self._exif[0x0112] = int(match[2]) return self._exif def _reload_exif(self): if self._exif is None or not self._exif._loaded: return self._exif._loaded = False self.getexif() def get_child_images(self): child_images = [] exif = self.getexif() ifds = [] if ExifTags.Base.SubIFDs in exif: subifd_offsets = exif[ExifTags.Base.SubIFDs] if subifd_offsets: if not isinstance(subifd_offsets, tuple): subifd_offsets = (subifd_offsets,) for subifd_offset in subifd_offsets: ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset)) ifd1 = exif.get_ifd(ExifTags.IFD.IFD1) if ifd1 and ifd1.get(513): ifds.append((ifd1, exif._info.next)) offset = None for ifd, ifd_offset in ifds: current_offset = self.fp.tell() if offset is None: offset = current_offset fp = self.fp thumbnail_offset = ifd.get(513) if thumbnail_offset is not None: try: thumbnail_offset += self._exif_offset except AttributeError: pass self.fp.seek(thumbnail_offset) data = self.fp.read(ifd.get(514)) fp = io.BytesIO(data) with open(fp) as im: if thumbnail_offset is None: im._frame_pos = [ifd_offset] im._seek(0) im.load() child_images.append(im) if offset is not None: self.fp.seek(offset) return child_images def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self, rawmode="RGB"): """ Returns the image palette as a list. :param rawmode: The mode in which to return the palette. ``None`` will return the palette in its current mode. .. versionadded:: 9.1.0 :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: mode = self.im.getpalettemode() except ValueError: return None # no palette if rawmode is None: rawmode = mode return list(self.im.getpalette(mode, rawmode)) def apply_transparency(self): """ If a P mode image has a "transparency" key in the info dictionary, remove the key and instead apply the transparency to the palette. Otherwise, the image is unchanged. """ if self.mode != "P" or "transparency" not in self.info: return from . import ImagePalette palette = self.getpalette("RGBA") transparency = self.info["transparency"] if isinstance(transparency, bytes): for i, alpha in enumerate(transparency): palette[i * 4 + 3] = alpha else: palette[transparency * 4 + 3] = 0 self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette)) self.palette.dirty = 1 del self.info["transparency"] def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. Counts are grouped into 256 bins for each band, even if the image has more than 8 bits per band. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", "LA", "RGBA" or "RGBa" images (if present, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? msg = "cannot determine region size; use 4-item box" raise ValueError(msg) box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): msg = "Source must be a tuple" raise ValueError(msg) if not isinstance(dest, (list, tuple)): msg = "Destination must be a tuple" raise ValueError(msg) if not len(source) in (2, 4): msg = "Source must be a 2 or 4-tuple" raise ValueError(msg) if not len(dest) == 2: msg = "Destination must be a 2-tuple" raise ValueError(msg) if min(source) < 0: msg = "Source must be non-negative" raise ValueError(msg) if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case msg = "point operation not supported for this mode" raise ValueError(msg) if mode != "F": lut = [round(i) for i in lut] return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: msg = "illegal image mode" raise ValueError(msg) from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): msg = "illegal image mode" raise ValueError(msg) alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): msg = "illegal image mode" raise ValueError(msg) if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P and PA images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode in ("P", "PA") and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P or PA image if self.mode == "PA": alpha = value[3] if len(value) == 4 else 255 value = value[:3] value = self.palette.getcolor(value, self) if self.mode == "PA": value = (value, alpha) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): msg = "illegal image mode" raise ValueError(msg) bands = 3 palette_mode = "RGB" if source_palette is None: if self.mode == "P": self.load() palette_mode = self.im.getpalettemode() if palette_mode == "RGBA": bands = 4 source_palette = self.im.getpalette(palette_mode, palette_mode) else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[ oldPosition * bands : oldPosition * bands + bands ] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette( palette_mode, palette=mapping_palette * bands ) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette(palette_mode + ";L", m_im.palette.tobytes()) m_im = m_im.convert("L") m_im.putpalette(palette_bytes, palette_mode) m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes) if "transparency" in self.info: try: m_im.info["transparency"] = dest_map.index(self.info["transparency"]) except ValueError: if "transparency" in m_im.info: del m_im.info["transparency"] return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`Resampling.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`Resampling.NEAREST`. Otherwise, the default filter is :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = Resampling.NEAREST if type_special else Resampling.BICUBIC elif resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, Resampling.LANCZOS, Resampling.BOX, Resampling.HAMMING, ): msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), (Resampling.BOX, "Image.Resampling.BOX"), (Resampling.HAMMING, "Image.Resampling.HAMMING"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) if reducing_gap is not None and reducing_gap < 1.0: msg = "reducing_gap must be 1.0 or greater" raise ValueError(msg) size = tuple(size) self.load() if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = Resampling.NEAREST if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != Resampling.NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(Transpose.ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose( Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270 ) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform( (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor ) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif is_path(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and is_path(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: msg = f"unknown file extension: {ext}" raise ValueError(msg) from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] created = False if open_fp: created = not os.path.exists(filename) if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) except Exception: if open_fp: fp.close() if created: try: os.remove(filename) except PermissionError: pass raise if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: msg = f'The image has no channel "{channel}"' raise ValueError(msg) from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: Optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If omitted, it defaults to :py:data:`Resampling.BICUBIC`. (was :py:data:`Resampling.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ provided_size = tuple(map(math.floor, size)) def preserve_aspect_ratio(): def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) x, y = provided_size if x >= self.width and y >= self.height: return aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) return x, y box = None if reducing_gap is not None: size = preserve_aspect_ratio() if size is None: return res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if box is None: self.load() # load() may have changed the size of the image size = preserve_aspect_ratio() if size is None: return if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size in pixels, as a 2-tuple: (width, height). :param method: The transformation method. This is one of :py:data:`Transform.EXTENT` (cut out a rectangular subregion), :py:data:`Transform.AFFINE` (affine transform), :py:data:`Transform.PERSPECTIVE` (perspective transform), :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or :py:data:`Transform.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.Transform.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: msg = "missing method data" raise ValueError(msg) im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == Transform.MESH: # list of quads for box, quad in data: im.__transformer( box, self, Transform.QUAD, quad, resample, fillcolor is None ) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): w = box[2] - box[0] h = box[3] - box[1] if method == Transform.AFFINE: data = data[:6] elif method == Transform.EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = Transform.AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == Transform.PERSPECTIVE: data = data[:8] elif method == Transform.QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: msg = "unknown transformation method" raise ValueError(msg) if resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, ): if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS): msg = { Resampling.BOX: "Image.Resampling.BOX", Resampling.HAMMING: "Image.Resampling.HAMMING", Resampling.LANCZOS: "Image.Resampling.LANCZOS", }[resample] + f" ({resample}) cannot be used." else: msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) image.load() self.load() if image.mode in ("1", "P"): resample = Resampling.NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`, :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`, :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`, :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqpixmap(self) class ImageFile(Image.Image): """Base class for image file format handlers.""" def __init__(self, fp=None, filename=None): super().__init__() self._min_frame = 0 self.custom_mimetype = None self.tile = None """ A list of tile descriptors, or ``None`` """ self.readonly = 1 # until we know better self.decoderconfig = () self.decodermaxblock = MAXBLOCK if is_path(fp): # filename self.fp = open(fp, "rb") self.filename = fp self._exclusive_fp = True else: # stream self.fp = fp self.filename = filename # can be overridden self._exclusive_fp = None try: try: self._open() except ( IndexError, # end of data TypeError, # end of data (ord) KeyError, # unsupported mode EOFError, # got header but not the first frame struct.error, ) as v: raise SyntaxError(v) from v if not self.mode or self.size[0] <= 0 or self.size[1] <= 0: msg = "not identified by this driver" raise SyntaxError(msg) except BaseException: # close the file only if we have opened it this constructor if self._exclusive_fp: self.fp.close() raise def get_format_mimetype(self): if self.custom_mimetype: return self.custom_mimetype if self.format is not None: return Image.MIME.get(self.format.upper()) def __setstate__(self, state): self.tile = [] super().__setstate__(state) def verify(self): """Check file integrity""" # raise exception if something's wrong. must be called # directly after open, and closes file when finished. if self._exclusive_fp: self.fp.close() self.fp = None def load(self): """Load image data based on tile list""" if self.tile is None: msg = "cannot load this image" raise OSError(msg) pixel = Image.Image.load(self) if not self.tile: return pixel self.map = None use_mmap = self.filename and len(self.tile) == 1 # As of pypy 2.1.0, memory mapping was failing here. use_mmap = use_mmap and not hasattr(sys, "pypy_version_info") readonly = 0 # look for read/seek overrides try: read = self.load_read # don't use mmap if there are custom read/seek functions use_mmap = False except AttributeError: read = self.fp.read try: seek = self.load_seek use_mmap = False except AttributeError: seek = self.fp.seek if use_mmap: # try memory mapping decoder_name, extents, offset, args = self.tile[0] if ( decoder_name == "raw" and len(args) >= 3 and args[0] == self.mode and args[0] in Image._MAPMODES ): try: # use mmap, if possible import mmap with open(self.filename) as fp: self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ) if offset + self.size[1] * args[1] > self.map.size(): # buffer is not large enough raise OSError self.im = Image.core.map_buffer( self.map, self.size, decoder_name, offset, args ) readonly = 1 # After trashing self.im, # we might need to reload the palette data. if self.palette: self.palette.dirty = 1 except (AttributeError, OSError, ImportError): self.map = None self.load_prepare() err_code = -3 # initialize to unknown error if not self.map: # sort tiles in file order self.tile.sort(key=_tilesort) try: # FIXME: This is a hack to handle TIFF's JpegTables tag. prefix = self.tile_prefix except AttributeError: prefix = b"" # Remove consecutive duplicates that only differ by their offset self.tile = [ list(tiles)[-1] for _, tiles in itertools.groupby( self.tile, lambda tile: (tile[0], tile[1], tile[3]) ) ] for decoder_name, extents, offset, args in self.tile: seek(offset) decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) err_code = decoder.decode(b"")[1] else: b = prefix while True: try: s = read(self.decodermaxblock) except (IndexError, struct.error) as e: # truncated png/gif if LOAD_TRUNCATED_IMAGES: break else: msg = "image file is truncated" raise OSError(msg) from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: msg = ( "image file is truncated " f"({len(b)} bytes not processed)" ) raise OSError(msg) b = b + s n, err_code = decoder.decode(b) if n < 0: break b = b[n:] finally: # Need to cleanup here to prevent leaks decoder.cleanup() self.tile = [] self.readonly = readonly self.load_end() if self._exclusive_fp and self._close_exclusive_fp_after_loading: self.fp.close() self.fp = None if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0: # still raised if decoder fails to return anything raise_oserror(err_code) return Image.Image.load(self) def load_prepare(self): # create image memory if necessary if not self.im or self.im.mode != self.mode or self.im.size != self.size: self.im = Image.core.new(self.mode, self.size) # create palette (optional) if self.mode == "P": Image.Image.load(self) def load_end(self): # may be overridden pass # may be defined for contained formats # def load_seek(self, pos): # pass # may be defined for blocked formats (e.g. PNG) # def load_read(self, bytes): # pass def _seek_check(self, frame): if ( frame < self._min_frame # Only check upper limit on frames if additional seek operations # are not required to do so or ( not (hasattr(self, "_n_frames") and self._n_frames is None) and frame >= self.n_frames + self._min_frame ) ): msg = "attempt to seek outside sequence" raise EOFError(msg) return self.tell() != frame def o8(i): return bytes((i & 255,)) def _save(im, fp, filename): fp.write(_MAGIC) # (2+2) bmp = im.encoderinfo.get("bitmap_format") == "bmp" sizes = im.encoderinfo.get( "sizes", [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)], ) frames = [] provided_ims = [im] + im.encoderinfo.get("append_images", []) width, height = im.size for size in sorted(set(sizes)): if size[0] > width or size[1] > height or size[0] > 256 or size[1] > 256: continue for provided_im in provided_ims: if provided_im.size != size: continue frames.append(provided_im) if bmp: bits = BmpImagePlugin.SAVE[provided_im.mode][1] bits_used = [bits] for other_im in provided_ims: if other_im.size != size: continue bits = BmpImagePlugin.SAVE[other_im.mode][1] if bits not in bits_used: # Another image has been supplied for this size # with a different bit depth frames.append(other_im) bits_used.append(bits) break else: # TODO: invent a more convenient method for proportional scalings frame = provided_im.copy() frame.thumbnail(size, Image.Resampling.LANCZOS, reducing_gap=None) frames.append(frame) fp.write(o16(len(frames))) # idCount(2) offset = fp.tell() + len(frames) * 16 for frame in frames: width, height = frame.size # 0 means 256 fp.write(o8(width if width < 256 else 0)) # bWidth(1) fp.write(o8(height if height < 256 else 0)) # bHeight(1) bits, colors = BmpImagePlugin.SAVE[frame.mode][1:] if bmp else (32, 0) fp.write(o8(colors)) # bColorCount(1) fp.write(b"\0") # bReserved(1) fp.write(b"\0\0") # wPlanes(2) fp.write(o16(bits)) # wBitCount(2) image_io = BytesIO() if bmp: frame.save(image_io, "dib") if bits != 32: and_mask = Image.new("1", size) ImageFile._save( and_mask, image_io, [("raw", (0, 0) + size, 0, ("1", 0, -1))] ) else: frame.save(image_io, "png") image_io.seek(0) image_bytes = image_io.read() if bmp: image_bytes = image_bytes[:8] + o32(height * 2) + image_bytes[12:] bytes_len = len(image_bytes) fp.write(o32(bytes_len)) # dwBytesInRes(4) fp.write(o32(offset)) # dwImageOffset(4) current = fp.tell() fp.seek(offset) fp.write(image_bytes) offset = offset + bytes_len fp.seek(current)
null
174,132
import warnings from io import BytesIO from math import ceil, log from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin from ._binary import i16le as i16 from ._binary import i32le as i32 from ._binary import o8 from ._binary import o16le as o16 from ._binary import o32le as o32 _MAGIC = b"\0\0\1\0" def _accept(prefix): return prefix[:4] == _MAGIC
null
174,133
import array from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile from ._deprecate import deprecate class ImagePalette: """ Color palette for palette mapped images :param mode: The mode to use for the palette. See: :ref:`concept-modes`. Defaults to "RGB" :param palette: An optional palette. If given, it must be a bytearray, an array or a list of ints between 0-255. The list must consist of all channels for one color followed by the next color (e.g. RGBRGBRGB). Defaults to an empty palette. """ def __init__(self, mode="RGB", palette=None, size=0): self.mode = mode self.rawmode = None # if set, palette contains raw data self.palette = palette or bytearray() self.dirty = None if size != 0: deprecate("The size parameter", 10, None) if size != len(self.palette): msg = "wrong palette size" raise ValueError(msg) def palette(self): return self._palette def palette(self, palette): self._colors = None self._palette = palette def colors(self): if self._colors is None: mode_len = len(self.mode) self._colors = {} for i in range(0, len(self.palette), mode_len): color = tuple(self.palette[i : i + mode_len]) if color in self._colors: continue self._colors[color] = i // mode_len return self._colors def colors(self, colors): self._colors = colors def copy(self): new = ImagePalette() new.mode = self.mode new.rawmode = self.rawmode if self.palette is not None: new.palette = self.palette[:] new.dirty = self.dirty return new def getdata(self): """ Get palette contents in format suitable for the low-level ``im.putpalette`` primitive. .. warning:: This method is experimental. """ if self.rawmode: return self.rawmode, self.palette return self.mode, self.tobytes() def tobytes(self): """Convert palette to bytes. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(self.palette, bytes): return self.palette arr = array.array("B", self.palette) return arr.tobytes() # Declare tostring as an alias for tobytes tostring = tobytes def getcolor(self, color, image=None): """Given an rgb tuple, allocate palette entry. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(color, tuple): if self.mode == "RGB": if len(color) == 4: if color[3] != 255: msg = "cannot add non-opaque RGBA color to RGB palette" raise ValueError(msg) color = color[:3] elif self.mode == "RGBA": if len(color) == 3: color += (255,) try: return self.colors[color] except KeyError as e: # allocate new color slot if not isinstance(self.palette, bytearray): self._palette = bytearray(self.palette) index = len(self.palette) // 3 special_colors = () if image: special_colors = ( image.info.get("background"), image.info.get("transparency"), ) while index in special_colors: index += 1 if index >= 256: if image: # Search for an unused index for i, count in reversed(list(enumerate(image.histogram()))): if count == 0 and i not in special_colors: index = i break if index >= 256: msg = "cannot allocate more than 256 colors" raise ValueError(msg) from e self.colors[color] = index if index * 3 < len(self.palette): self._palette = ( self.palette[: index * 3] + bytes(color) + self.palette[index * 3 + 3 :] ) else: self._palette += bytes(color) self.dirty = 1 return index else: msg = f"unknown color specifier: {repr(color)}" raise ValueError(msg) def save(self, fp): """Save palette to text file. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(fp, str): fp = open(fp, "w") fp.write("# Palette\n") fp.write(f"# Mode: {self.mode}\n") for i in range(256): fp.write(f"{i}") for j in range(i * len(self.mode), (i + 1) * len(self.mode)): try: fp.write(f" {self.palette[j]}") except IndexError: fp.write(" 0") fp.write("\n") fp.close() def raw(rawmode, data): palette = ImagePalette() palette.rawmode = rawmode palette.palette = data palette.dirty = 1 return palette
null
174,134
import array from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile from ._deprecate import deprecate def make_gamma_lut(exp): lut = [] for i in range(256): lut.append(int(((i / 255.0) ** exp) * 255.0 + 0.5)) return lut
null
174,135
import array from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile from ._deprecate import deprecate class ImagePalette: """ Color palette for palette mapped images :param mode: The mode to use for the palette. See: :ref:`concept-modes`. Defaults to "RGB" :param palette: An optional palette. If given, it must be a bytearray, an array or a list of ints between 0-255. The list must consist of all channels for one color followed by the next color (e.g. RGBRGBRGB). Defaults to an empty palette. """ def __init__(self, mode="RGB", palette=None, size=0): self.mode = mode self.rawmode = None # if set, palette contains raw data self.palette = palette or bytearray() self.dirty = None if size != 0: deprecate("The size parameter", 10, None) if size != len(self.palette): msg = "wrong palette size" raise ValueError(msg) def palette(self): return self._palette def palette(self, palette): self._colors = None self._palette = palette def colors(self): if self._colors is None: mode_len = len(self.mode) self._colors = {} for i in range(0, len(self.palette), mode_len): color = tuple(self.palette[i : i + mode_len]) if color in self._colors: continue self._colors[color] = i // mode_len return self._colors def colors(self, colors): self._colors = colors def copy(self): new = ImagePalette() new.mode = self.mode new.rawmode = self.rawmode if self.palette is not None: new.palette = self.palette[:] new.dirty = self.dirty return new def getdata(self): """ Get palette contents in format suitable for the low-level ``im.putpalette`` primitive. .. warning:: This method is experimental. """ if self.rawmode: return self.rawmode, self.palette return self.mode, self.tobytes() def tobytes(self): """Convert palette to bytes. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(self.palette, bytes): return self.palette arr = array.array("B", self.palette) return arr.tobytes() # Declare tostring as an alias for tobytes tostring = tobytes def getcolor(self, color, image=None): """Given an rgb tuple, allocate palette entry. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(color, tuple): if self.mode == "RGB": if len(color) == 4: if color[3] != 255: msg = "cannot add non-opaque RGBA color to RGB palette" raise ValueError(msg) color = color[:3] elif self.mode == "RGBA": if len(color) == 3: color += (255,) try: return self.colors[color] except KeyError as e: # allocate new color slot if not isinstance(self.palette, bytearray): self._palette = bytearray(self.palette) index = len(self.palette) // 3 special_colors = () if image: special_colors = ( image.info.get("background"), image.info.get("transparency"), ) while index in special_colors: index += 1 if index >= 256: if image: # Search for an unused index for i, count in reversed(list(enumerate(image.histogram()))): if count == 0 and i not in special_colors: index = i break if index >= 256: msg = "cannot allocate more than 256 colors" raise ValueError(msg) from e self.colors[color] = index if index * 3 < len(self.palette): self._palette = ( self.palette[: index * 3] + bytes(color) + self.palette[index * 3 + 3 :] ) else: self._palette += bytes(color) self.dirty = 1 return index else: msg = f"unknown color specifier: {repr(color)}" raise ValueError(msg) def save(self, fp): """Save palette to text file. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(fp, str): fp = open(fp, "w") fp.write("# Palette\n") fp.write(f"# Mode: {self.mode}\n") for i in range(256): fp.write(f"{i}") for j in range(i * len(self.mode), (i + 1) * len(self.mode)): try: fp.write(f" {self.palette[j]}") except IndexError: fp.write(" 0") fp.write("\n") fp.close() def negative(mode="RGB"): palette = list(range(256 * len(mode))) palette.reverse() return ImagePalette(mode, [i // len(mode) for i in palette])
null
174,136
import array from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile from ._deprecate import deprecate class ImagePalette: """ Color palette for palette mapped images :param mode: The mode to use for the palette. See: :ref:`concept-modes`. Defaults to "RGB" :param palette: An optional palette. If given, it must be a bytearray, an array or a list of ints between 0-255. The list must consist of all channels for one color followed by the next color (e.g. RGBRGBRGB). Defaults to an empty palette. """ def __init__(self, mode="RGB", palette=None, size=0): self.mode = mode self.rawmode = None # if set, palette contains raw data self.palette = palette or bytearray() self.dirty = None if size != 0: deprecate("The size parameter", 10, None) if size != len(self.palette): msg = "wrong palette size" raise ValueError(msg) def palette(self): return self._palette def palette(self, palette): self._colors = None self._palette = palette def colors(self): if self._colors is None: mode_len = len(self.mode) self._colors = {} for i in range(0, len(self.palette), mode_len): color = tuple(self.palette[i : i + mode_len]) if color in self._colors: continue self._colors[color] = i // mode_len return self._colors def colors(self, colors): self._colors = colors def copy(self): new = ImagePalette() new.mode = self.mode new.rawmode = self.rawmode if self.palette is not None: new.palette = self.palette[:] new.dirty = self.dirty return new def getdata(self): """ Get palette contents in format suitable for the low-level ``im.putpalette`` primitive. .. warning:: This method is experimental. """ if self.rawmode: return self.rawmode, self.palette return self.mode, self.tobytes() def tobytes(self): """Convert palette to bytes. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(self.palette, bytes): return self.palette arr = array.array("B", self.palette) return arr.tobytes() # Declare tostring as an alias for tobytes tostring = tobytes def getcolor(self, color, image=None): """Given an rgb tuple, allocate palette entry. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(color, tuple): if self.mode == "RGB": if len(color) == 4: if color[3] != 255: msg = "cannot add non-opaque RGBA color to RGB palette" raise ValueError(msg) color = color[:3] elif self.mode == "RGBA": if len(color) == 3: color += (255,) try: return self.colors[color] except KeyError as e: # allocate new color slot if not isinstance(self.palette, bytearray): self._palette = bytearray(self.palette) index = len(self.palette) // 3 special_colors = () if image: special_colors = ( image.info.get("background"), image.info.get("transparency"), ) while index in special_colors: index += 1 if index >= 256: if image: # Search for an unused index for i, count in reversed(list(enumerate(image.histogram()))): if count == 0 and i not in special_colors: index = i break if index >= 256: msg = "cannot allocate more than 256 colors" raise ValueError(msg) from e self.colors[color] = index if index * 3 < len(self.palette): self._palette = ( self.palette[: index * 3] + bytes(color) + self.palette[index * 3 + 3 :] ) else: self._palette += bytes(color) self.dirty = 1 return index else: msg = f"unknown color specifier: {repr(color)}" raise ValueError(msg) def save(self, fp): """Save palette to text file. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(fp, str): fp = open(fp, "w") fp.write("# Palette\n") fp.write(f"# Mode: {self.mode}\n") for i in range(256): fp.write(f"{i}") for j in range(i * len(self.mode), (i + 1) * len(self.mode)): try: fp.write(f" {self.palette[j]}") except IndexError: fp.write(" 0") fp.write("\n") fp.close() def randint(a: int, b: int) -> int: ... def random(mode="RGB"): from random import randint palette = [] for i in range(256 * len(mode)): palette.append(randint(0, 255)) return ImagePalette(mode, palette)
null
174,137
import array from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile from ._deprecate import deprecate class ImagePalette: """ Color palette for palette mapped images :param mode: The mode to use for the palette. See: :ref:`concept-modes`. Defaults to "RGB" :param palette: An optional palette. If given, it must be a bytearray, an array or a list of ints between 0-255. The list must consist of all channels for one color followed by the next color (e.g. RGBRGBRGB). Defaults to an empty palette. """ def __init__(self, mode="RGB", palette=None, size=0): self.mode = mode self.rawmode = None # if set, palette contains raw data self.palette = palette or bytearray() self.dirty = None if size != 0: deprecate("The size parameter", 10, None) if size != len(self.palette): msg = "wrong palette size" raise ValueError(msg) def palette(self): return self._palette def palette(self, palette): self._colors = None self._palette = palette def colors(self): if self._colors is None: mode_len = len(self.mode) self._colors = {} for i in range(0, len(self.palette), mode_len): color = tuple(self.palette[i : i + mode_len]) if color in self._colors: continue self._colors[color] = i // mode_len return self._colors def colors(self, colors): self._colors = colors def copy(self): new = ImagePalette() new.mode = self.mode new.rawmode = self.rawmode if self.palette is not None: new.palette = self.palette[:] new.dirty = self.dirty return new def getdata(self): """ Get palette contents in format suitable for the low-level ``im.putpalette`` primitive. .. warning:: This method is experimental. """ if self.rawmode: return self.rawmode, self.palette return self.mode, self.tobytes() def tobytes(self): """Convert palette to bytes. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(self.palette, bytes): return self.palette arr = array.array("B", self.palette) return arr.tobytes() # Declare tostring as an alias for tobytes tostring = tobytes def getcolor(self, color, image=None): """Given an rgb tuple, allocate palette entry. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(color, tuple): if self.mode == "RGB": if len(color) == 4: if color[3] != 255: msg = "cannot add non-opaque RGBA color to RGB palette" raise ValueError(msg) color = color[:3] elif self.mode == "RGBA": if len(color) == 3: color += (255,) try: return self.colors[color] except KeyError as e: # allocate new color slot if not isinstance(self.palette, bytearray): self._palette = bytearray(self.palette) index = len(self.palette) // 3 special_colors = () if image: special_colors = ( image.info.get("background"), image.info.get("transparency"), ) while index in special_colors: index += 1 if index >= 256: if image: # Search for an unused index for i, count in reversed(list(enumerate(image.histogram()))): if count == 0 and i not in special_colors: index = i break if index >= 256: msg = "cannot allocate more than 256 colors" raise ValueError(msg) from e self.colors[color] = index if index * 3 < len(self.palette): self._palette = ( self.palette[: index * 3] + bytes(color) + self.palette[index * 3 + 3 :] ) else: self._palette += bytes(color) self.dirty = 1 return index else: msg = f"unknown color specifier: {repr(color)}" raise ValueError(msg) def save(self, fp): """Save palette to text file. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(fp, str): fp = open(fp, "w") fp.write("# Palette\n") fp.write(f"# Mode: {self.mode}\n") for i in range(256): fp.write(f"{i}") for j in range(i * len(self.mode), (i + 1) * len(self.mode)): try: fp.write(f" {self.palette[j]}") except IndexError: fp.write(" 0") fp.write("\n") fp.close() def make_linear_lut(black, white): lut = [] if black == 0: for i in range(256): lut.append(white * i // 255) else: raise NotImplementedError # FIXME return lut def sepia(white="#fff0c0"): bands = [make_linear_lut(0, band) for band in ImageColor.getrgb(white)] return ImagePalette("RGB", [bands[i % 3][i // 3] for i in range(256 * 3)])
null
174,138
from . import FitsImagePlugin, Image, ImageFile from ._deprecate import deprecate _handler = None class FITSStubImageFile(ImageFile.StubImageFile): format = FitsImagePlugin.FitsImageFile.format format_description = FitsImagePlugin.FitsImageFile.format_description def _open(self): offset = self.fp.tell() im = FitsImagePlugin.FitsImageFile(self.fp) self._size = im.size self.mode = im.mode self.tile = [] self.fp.seek(offset) loader = self._load() if loader: loader.open(self) def _load(self): return _handler Image.register_save(FITSStubImageFile.format, _save) class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": deprecate("Image categories", 10, "is_animated", plural=True) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None def close(self): """ Closes the file pointer, if possible. This operation will destroy the image core and release its memory. The image data will be unusable afterward. This function is required to close images that have multiple frames or have not had their file read and closed by the :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for more information. """ try: if getattr(self, "_fp", False): if self._fp != self.fp: self._fp.close() self._fp = DeferredError(ValueError("Operation on closed image")) if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = DeferredError(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_pretty_(self, p, cycle): """IPython plain text display support""" # Same as __repr__ but without unpredictable id(self), # to keep Jupyter notebook `text/plain` output stable. p.text( "<%s.%s image mode=%s size=%dx%d>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], ) ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: msg = "Could not save to PNG for display" raise ValueError(msg) from e return b.getvalue() def __array_interface__(self): # numpy array interface support new = {"version": 3} try: if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() except Exception as e: if not isinstance(e, (MemoryError, RecursionError)): try: import numpy from packaging.version import parse as parse_version except ImportError: pass else: if parse_version(numpy.__version__) < parse_version("1.23"): warnings.warn(e) raise new["shape"], new["typestr"] = _conv_type_shape(self) return new def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. A list of C encoders can be seen under codecs section of the function array in :file:`_imaging.c`. Python encoders are registered within the relevant plugins. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() if self.width == 0 or self.height == 0: return b"" # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c output = [] while True: bytes_consumed, errcode, data = e.encode(bufsize) output.append(data) if errcode: break if errcode < 0: msg = f"encoder error {errcode} in tobytes" raise RuntimeError(msg) return b"".join(output) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": msg = "not a bitmap" raise ValueError(msg) data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: msg = "not enough image data" raise ValueError(msg) if s[1] != 0: msg = "cannot decode image data" raise ValueError(msg) def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im is not None and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: palette_mode = "RGBA" if mode.startswith("RGBA") else "RGB" self.palette.mode = palette_mode self.palette.palette = self.im.getpalette(palette_mode, palette_mode) if self.im is not None: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK". The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is ``None``, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. When converting from "PA", if an "RGBA" palette is present, the alpha channel from the image will be used instead of the values from the palette. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`Palette.WEB` or :data:`Palette.ADAPTIVE`. :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): msg = "illegal conversion" raise ValueError(msg) im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if (self.mode in ("1", "L", "I") and mode in ("LA", "RGBA")) or ( self.mode == "RGB" and mode == "RGBA" ): # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: msg = "Transparency for P mode should be bytes or int" raise ValueError(msg) if mode == "P" and palette == Palette.ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new if "LAB" in (self.mode, mode): other_mode = mode if self.mode == "LAB" else self.mode if other_mode in ("RGB", "RGBA", "RGBX"): from . import ImageCms srgb = ImageCms.createProfile("sRGB") lab = ImageCms.createProfile("LAB") profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab] transform = ImageCms.buildTransform( profiles[0], profiles[1], self.mode, mode ) return transform.apply(self) # colorspace conversion if dither is None: dither = Dither.FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again modebase = getmodebase(self.mode) if modebase == self.mode: raise im = self.im.convert(modebase) im = im.convert(mode, dither) except KeyError as e: msg = "illegal conversion" raise ValueError(msg) from e new_im = self._new(im) if mode == "P" and palette != Palette.ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`Quantize.MEDIANCUT` (median cut), :data:`Quantize.MAXCOVERAGE` (maximum coverage), :data:`Quantize.FASTOCTREE` (fast octree), :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`Quantize.MEDIANCUT` will be used. The exception to this is RGBA images. :data:`Quantize.MEDIANCUT` and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so :data:`Quantize.FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` (default). :returns: A new image """ self.load() if method is None: # defaults: method = Quantize.MEDIANCUT if self.mode == "RGBA": method = Quantize.FASTOCTREE if self.mode == "RGBA" and method not in ( Quantize.FASTOCTREE, Quantize.LIBIMAGEQUANT, ): # Caller specified an invalid mode. msg = ( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) raise ValueError(msg) if palette: # use palette from reference image palette.load() if palette.mode != "P": msg = "bad mode for palette image" raise ValueError(msg) if self.mode != "RGB" and self.mode != "L": msg = "only RGB or L mode images can be quantized to a palette" raise ValueError(msg) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() if box[2] < box[0]: msg = "Coordinate 'right' is less than 'left'" raise ValueError(msg) elif box[3] < box[1]: msg = "Coordinate 'lower' is less than 'upper'" raise ValueError(msg) self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size in pixels, as a 2-tuple: (width, height). """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): msg = "filter argument should be ImageFilter.Filter instance or class" raise TypeError(msg) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): """ Gets EXIF data from the image. :returns: an :py:class:`~PIL.Image.Exif` object. """ if self._exif is None: self._exif = Exif() self._exif._loaded = False elif self._exif._loaded: return self._exif self._exif._loaded = True exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.bigtiff = self.tag_v2._bigtiff self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation(="|>)([0-9])', xmp_tags) if match: self._exif[0x0112] = int(match[2]) return self._exif def _reload_exif(self): if self._exif is None or not self._exif._loaded: return self._exif._loaded = False self.getexif() def get_child_images(self): child_images = [] exif = self.getexif() ifds = [] if ExifTags.Base.SubIFDs in exif: subifd_offsets = exif[ExifTags.Base.SubIFDs] if subifd_offsets: if not isinstance(subifd_offsets, tuple): subifd_offsets = (subifd_offsets,) for subifd_offset in subifd_offsets: ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset)) ifd1 = exif.get_ifd(ExifTags.IFD.IFD1) if ifd1 and ifd1.get(513): ifds.append((ifd1, exif._info.next)) offset = None for ifd, ifd_offset in ifds: current_offset = self.fp.tell() if offset is None: offset = current_offset fp = self.fp thumbnail_offset = ifd.get(513) if thumbnail_offset is not None: try: thumbnail_offset += self._exif_offset except AttributeError: pass self.fp.seek(thumbnail_offset) data = self.fp.read(ifd.get(514)) fp = io.BytesIO(data) with open(fp) as im: if thumbnail_offset is None: im._frame_pos = [ifd_offset] im._seek(0) im.load() child_images.append(im) if offset is not None: self.fp.seek(offset) return child_images def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self, rawmode="RGB"): """ Returns the image palette as a list. :param rawmode: The mode in which to return the palette. ``None`` will return the palette in its current mode. .. versionadded:: 9.1.0 :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: mode = self.im.getpalettemode() except ValueError: return None # no palette if rawmode is None: rawmode = mode return list(self.im.getpalette(mode, rawmode)) def apply_transparency(self): """ If a P mode image has a "transparency" key in the info dictionary, remove the key and instead apply the transparency to the palette. Otherwise, the image is unchanged. """ if self.mode != "P" or "transparency" not in self.info: return from . import ImagePalette palette = self.getpalette("RGBA") transparency = self.info["transparency"] if isinstance(transparency, bytes): for i, alpha in enumerate(transparency): palette[i * 4 + 3] = alpha else: palette[transparency * 4 + 3] = 0 self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette)) self.palette.dirty = 1 del self.info["transparency"] def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. Counts are grouped into 256 bins for each band, even if the image has more than 8 bits per band. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", "LA", "RGBA" or "RGBa" images (if present, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? msg = "cannot determine region size; use 4-item box" raise ValueError(msg) box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): msg = "Source must be a tuple" raise ValueError(msg) if not isinstance(dest, (list, tuple)): msg = "Destination must be a tuple" raise ValueError(msg) if not len(source) in (2, 4): msg = "Source must be a 2 or 4-tuple" raise ValueError(msg) if not len(dest) == 2: msg = "Destination must be a 2-tuple" raise ValueError(msg) if min(source) < 0: msg = "Source must be non-negative" raise ValueError(msg) if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case msg = "point operation not supported for this mode" raise ValueError(msg) if mode != "F": lut = [round(i) for i in lut] return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: msg = "illegal image mode" raise ValueError(msg) from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): msg = "illegal image mode" raise ValueError(msg) alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): msg = "illegal image mode" raise ValueError(msg) if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P and PA images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode in ("P", "PA") and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P or PA image if self.mode == "PA": alpha = value[3] if len(value) == 4 else 255 value = value[:3] value = self.palette.getcolor(value, self) if self.mode == "PA": value = (value, alpha) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): msg = "illegal image mode" raise ValueError(msg) bands = 3 palette_mode = "RGB" if source_palette is None: if self.mode == "P": self.load() palette_mode = self.im.getpalettemode() if palette_mode == "RGBA": bands = 4 source_palette = self.im.getpalette(palette_mode, palette_mode) else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[ oldPosition * bands : oldPosition * bands + bands ] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette( palette_mode, palette=mapping_palette * bands ) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette(palette_mode + ";L", m_im.palette.tobytes()) m_im = m_im.convert("L") m_im.putpalette(palette_bytes, palette_mode) m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes) if "transparency" in self.info: try: m_im.info["transparency"] = dest_map.index(self.info["transparency"]) except ValueError: if "transparency" in m_im.info: del m_im.info["transparency"] return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`Resampling.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`Resampling.NEAREST`. Otherwise, the default filter is :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = Resampling.NEAREST if type_special else Resampling.BICUBIC elif resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, Resampling.LANCZOS, Resampling.BOX, Resampling.HAMMING, ): msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), (Resampling.BOX, "Image.Resampling.BOX"), (Resampling.HAMMING, "Image.Resampling.HAMMING"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) if reducing_gap is not None and reducing_gap < 1.0: msg = "reducing_gap must be 1.0 or greater" raise ValueError(msg) size = tuple(size) self.load() if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = Resampling.NEAREST if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != Resampling.NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(Transpose.ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose( Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270 ) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform( (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor ) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif is_path(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and is_path(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: msg = f"unknown file extension: {ext}" raise ValueError(msg) from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] created = False if open_fp: created = not os.path.exists(filename) if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) except Exception: if open_fp: fp.close() if created: try: os.remove(filename) except PermissionError: pass raise if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: msg = f'The image has no channel "{channel}"' raise ValueError(msg) from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: Optional resampling filter. This can be one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. If omitted, it defaults to :py:data:`Resampling.BICUBIC`. (was :py:data:`Resampling.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ provided_size = tuple(map(math.floor, size)) def preserve_aspect_ratio(): def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) x, y = provided_size if x >= self.width and y >= self.height: return aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) return x, y box = None if reducing_gap is not None: size = preserve_aspect_ratio() if size is None: return res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if box is None: self.load() # load() may have changed the size of the image size = preserve_aspect_ratio() if size is None: return if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size in pixels, as a 2-tuple: (width, height). :param method: The transformation method. This is one of :py:data:`Transform.EXTENT` (cut out a rectangular subregion), :py:data:`Transform.AFFINE` (affine transform), :py:data:`Transform.PERSPECTIVE` (perspective transform), :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or :py:data:`Transform.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.Transform.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`Resampling.NEAREST` (use nearest neighbour), :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`Resampling.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: msg = "missing method data" raise ValueError(msg) im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == Transform.MESH: # list of quads for box, quad in data: im.__transformer( box, self, Transform.QUAD, quad, resample, fillcolor is None ) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): w = box[2] - box[0] h = box[3] - box[1] if method == Transform.AFFINE: data = data[:6] elif method == Transform.EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = Transform.AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == Transform.PERSPECTIVE: data = data[:8] elif method == Transform.QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: msg = "unknown transformation method" raise ValueError(msg) if resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, ): if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS): msg = { Resampling.BOX: "Image.Resampling.BOX", Resampling.HAMMING: "Image.Resampling.HAMMING", Resampling.LANCZOS: "Image.Resampling.LANCZOS", }[resample] + f" ({resample}) cannot be used." else: msg = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), ) ] msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg) image.load() self.load() if image.mode in ("1", "P"): resample = Resampling.NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`, :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`, :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`, :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: msg = "Qt bindings are not installed" raise ImportError(msg) return ImageQt.toqpixmap(self) def deprecate( deprecated: str, when: int | None, replacement: str | None = None, *, action: str | None = None, plural: bool = False, ) -> None: """ Deprecations helper. :param deprecated: Name of thing to be deprecated. :param when: Pillow major version to be removed in. :param replacement: Name of replacement. :param action: Instead of "replacement", give a custom call to action e.g. "Upgrade to new thing". :param plural: if the deprecated thing is plural, needing "are" instead of "is". Usually of the form: "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd). Use [replacement] instead." You can leave out the replacement sentence: "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd)" Or with another call to action: "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd). [action]." """ is_ = "are" if plural else "is" if when is None: removed = "a future version" elif when <= int(__version__.split(".")[0]): msg = f"{deprecated} {is_} deprecated and should be removed." raise RuntimeError(msg) elif when == 10: removed = "Pillow 10 (2023-07-01)" elif when == 11: removed = "Pillow 11 (2024-10-15)" else: msg = f"Unknown removal version: {when}. Update {__name__}?" raise ValueError(msg) if replacement and action: msg = "Use only one of 'replacement' and 'action'" raise ValueError(msg) if replacement: action = f". Use {replacement} instead." elif action: action = f". {action.rstrip('.')}." else: action = "" warnings.warn( f"{deprecated} {is_} deprecated and will be removed in {removed}{action}", DeprecationWarning, stacklevel=3, ) The provided code snippet includes necessary dependencies for implementing the `register_handler` function. Write a Python function `def register_handler(handler)` to solve the following problem: Install application-specific FITS image handler. :param handler: Handler object. Here is the function: def register_handler(handler): """ Install application-specific FITS image handler. :param handler: Handler object. """ global _handler _handler = handler deprecate( "FitsStubImagePlugin", 10, action="FITS images can now be read without " "a handler through FitsImagePlugin instead", ) # Override FitsImagePlugin with this handler # for backwards compatibility try: Image.ID.remove(FITSStubImageFile.format) except ValueError: pass Image.register_open( FITSStubImageFile.format, FITSStubImageFile, FitsImagePlugin._accept )
Install application-specific FITS image handler. :param handler: Handler object.
174,139
from . import FitsImagePlugin, Image, ImageFile from ._deprecate import deprecate def _save(im, fp, filename): msg = "FITS save handler not installed" raise OSError(msg)
null
174,141
import struct from io import BytesIO from . import Image, ImageFile from ._binary import o32le as o32 DDS_MAGIC = 0x20534444 DDSD_CAPS = 0x1 DDSD_HEIGHT = 0x2 DDSD_WIDTH = 0x4 DDSD_PITCH = 0x8 DDSD_PIXELFORMAT = 0x1000 DDSCAPS_TEXTURE = 0x1000 DDPF_ALPHAPIXELS = 0x1 DDPF_RGB = 0x40 DDPF_LUMINANCE = 0x20000 Image.register_open(DdsImageFile.format, DdsImageFile, _accept) Image.register_save(DdsImageFile.format, _save) Image.register_extension(DdsImageFile.format, ".dds") class Image: def __init__(self): def __getattr__(self, name): def width(self): def height(self): def size(self): def _new(self, im): def __enter__(self): def __exit__(self, *args): def close(self): def _copy(self): def _ensure_mutable(self): def _dump(self, file=None, format=None, **options): def __eq__(self, other): def __repr__(self): def _repr_pretty_(self, p, cycle): def _repr_png_(self): def __array_interface__(self): def __getstate__(self): def __setstate__(self, state): def tobytes(self, encoder_name="raw", *args): def tobitmap(self, name="image"): def frombytes(self, data, decoder_name="raw", *args): def load(self): def verify(self): def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): def convert_transparency(m, v): def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): def copy(self): def crop(self, box=None): def _crop(self, im, box): def draft(self, mode, size): def _expand(self, xmargin, ymargin=None): def filter(self, filter): def getbands(self): def getbbox(self): def getcolors(self, maxcolors=256): def getdata(self, band=None): def getextrema(self): def _getxmp(self, xmp_tags): def get_name(tag): def get_value(element): def getexif(self): def _reload_exif(self): def get_child_images(self): def getim(self): def getpalette(self, rawmode="RGB"): def apply_transparency(self): def getpixel(self, xy): def getprojection(self): def histogram(self, mask=None, extrema=None): def entropy(self, mask=None, extrema=None): def paste(self, im, box=None, mask=None): def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): def point(self, lut, mode=None): def putalpha(self, alpha): def putdata(self, data, scale=1.0, offset=0.0): def putpalette(self, data, rawmode="RGB"): def putpixel(self, xy, value): def remap_palette(self, dest_map, source_palette=None): def _get_safe_box(self, size, resample, box): def resize(self, size, resample=None, box=None, reducing_gap=None): def reduce(self, factor, box=None): def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): def transform(x, y, matrix): def save(self, fp, format=None, **params): def seek(self, frame): def show(self, title=None): def split(self): def getchannel(self, channel): def tell(self): def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): def preserve_aspect_ratio(): def round_aspect(number, key): def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): def transpose(self, method): def effect_spread(self, distance): def toqimage(self): def toqpixmap(self): class ImageFile(Image.Image): def __init__(self, fp=None, filename=None): def get_format_mimetype(self): def __setstate__(self, state): def verify(self): def load(self): def load_prepare(self): def load_end(self): def _seek_check(self, frame): def _save(im, fp, filename): if im.mode not in ("RGB", "RGBA", "L", "LA"): msg = f"cannot write mode {im.mode} as DDS" raise OSError(msg) rawmode = im.mode masks = [0xFF0000, 0xFF00, 0xFF] if im.mode in ("L", "LA"): pixel_flags = DDPF_LUMINANCE else: pixel_flags = DDPF_RGB rawmode = rawmode[::-1] if im.mode in ("LA", "RGBA"): pixel_flags |= DDPF_ALPHAPIXELS masks.append(0xFF000000) bitcount = len(masks) * 8 while len(masks) < 4: masks.append(0) fp.write( o32(DDS_MAGIC) + o32(124) # header size + o32( DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PITCH | DDSD_PIXELFORMAT ) # flags + o32(im.height) + o32(im.width) + o32((im.width * bitcount + 7) // 8) # pitch + o32(0) # depth + o32(0) # mipmaps + o32(0) * 11 # reserved + o32(32) # pfsize + o32(pixel_flags) # pfflags + o32(0) # fourcc + o32(bitcount) # bitcount + b"".join(o32(mask) for mask in masks) # rgbabitmask + o32(DDSCAPS_TEXTURE) # dwCaps + o32(0) # dwCaps2 + o32(0) # dwCaps3 + o32(0) # dwCaps4 + o32(0) # dwReserved2 ) if im.mode == "RGBA": r, g, b, a = im.split() im = Image.merge("RGBA", (a, r, g, b)) ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, 1))])
null
174,143
import os import shutil import subprocess import sys from shlex import quote from PIL import Image from ._deprecate import deprecate _viewers = [] class Viewer: """Base class for viewers.""" # main api def show(self, image, **options): """ The main function for displaying an image. Converts the given image to the target format and displays it. """ if not ( image.mode in ("1", "RGBA") or (self.format == "PNG" and image.mode in ("I;16", "LA")) ): base = Image.getmodebase(image.mode) if image.mode != base: image = image.convert(base) return self.show_image(image, **options) # hook methods format = None """The format to convert the image into.""" options = {} """Additional options used to convert the image.""" def get_format(self, image): """Return format name, or ``None`` to save as PGM/PPM.""" return self.format def get_command(self, file, **options): """ Returns the command used to display the file. Not implemented in the base class. """ raise NotImplementedError def save_image(self, image): """Save to temporary file and return filename.""" return image._dump(format=self.get_format(image), **self.options) def show_image(self, image, **options): """Display the given image.""" return self.show_file(self.save_image(image), **options) def show_file(self, path=None, **options): """ Display given file. Before Pillow 9.1.0, the first argument was ``file``. This is now deprecated, and will be removed in Pillow 10.0.0 (2023-07-01). ``path`` should be used instead. """ if path is None: if "file" in options: deprecate("The 'file' argument", 10, "'path'") path = options.pop("file") else: msg = "Missing required argument: 'path'" raise TypeError(msg) os.system(self.get_command(path, **options)) # nosec return 1 The provided code snippet includes necessary dependencies for implementing the `register` function. Write a Python function `def register(viewer, order=1)` to solve the following problem: The :py:func:`register` function is used to register additional viewers:: from PIL import ImageShow ImageShow.register(MyViewer()) # MyViewer will be used as a last resort ImageShow.register(MySecondViewer(), 0) # MySecondViewer will be prioritised ImageShow.register(ImageShow.XVViewer(), 0) # XVViewer will be prioritised :param viewer: The viewer to be registered. :param order: Zero or a negative integer to prepend this viewer to the list, a positive integer to append it. Here is the function: def register(viewer, order=1): """ The :py:func:`register` function is used to register additional viewers:: from PIL import ImageShow ImageShow.register(MyViewer()) # MyViewer will be used as a last resort ImageShow.register(MySecondViewer(), 0) # MySecondViewer will be prioritised ImageShow.register(ImageShow.XVViewer(), 0) # XVViewer will be prioritised :param viewer: The viewer to be registered. :param order: Zero or a negative integer to prepend this viewer to the list, a positive integer to append it. """ try: if issubclass(viewer, Viewer): viewer = viewer() except TypeError: pass # raised if viewer wasn't a class if order > 0: _viewers.append(viewer) else: _viewers.insert(0, viewer)
The :py:func:`register` function is used to register additional viewers:: from PIL import ImageShow ImageShow.register(MyViewer()) # MyViewer will be used as a last resort ImageShow.register(MySecondViewer(), 0) # MySecondViewer will be prioritised ImageShow.register(ImageShow.XVViewer(), 0) # XVViewer will be prioritised :param viewer: The viewer to be registered. :param order: Zero or a negative integer to prepend this viewer to the list, a positive integer to append it.
174,144
import itertools import os import struct from . import ( ExifTags, Image, ImageFile, ImageSequence, JpegImagePlugin, TiffImagePlugin, ) from ._binary import i16be as i16 from ._binary import o32le def _save(im, fp, filename): Image.register_save(MpoImageFile.format, _save) Image.register_save_all(MpoImageFile.format, _save_all) Image.register_extension(MpoImageFile.format, ".mpo") Image.register_mime(MpoImageFile.format, "image/mpo") class Image: def __init__(self): def __getattr__(self, name): def width(self): def height(self): def size(self): def _new(self, im): def __enter__(self): def __exit__(self, *args): def close(self): def _copy(self): def _ensure_mutable(self): def _dump(self, file=None, format=None, **options): def __eq__(self, other): def __repr__(self): def _repr_pretty_(self, p, cycle): def _repr_png_(self): def __array_interface__(self): def __getstate__(self): def __setstate__(self, state): def tobytes(self, encoder_name="raw", *args): def tobitmap(self, name="image"): def frombytes(self, data, decoder_name="raw", *args): def load(self): def verify(self): def convert( self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256 ): def convert_transparency(m, v): def quantize( self, colors=256, method=None, kmeans=0, palette=None, dither=Dither.FLOYDSTEINBERG, ): def copy(self): def crop(self, box=None): def _crop(self, im, box): def draft(self, mode, size): def _expand(self, xmargin, ymargin=None): def filter(self, filter): def getbands(self): def getbbox(self): def getcolors(self, maxcolors=256): def getdata(self, band=None): def getextrema(self): def _getxmp(self, xmp_tags): def get_name(tag): def get_value(element): def getexif(self): def _reload_exif(self): def get_child_images(self): def getim(self): def getpalette(self, rawmode="RGB"): def apply_transparency(self): def getpixel(self, xy): def getprojection(self): def histogram(self, mask=None, extrema=None): def entropy(self, mask=None, extrema=None): def paste(self, im, box=None, mask=None): def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): def point(self, lut, mode=None): def putalpha(self, alpha): def putdata(self, data, scale=1.0, offset=0.0): def putpalette(self, data, rawmode="RGB"): def putpixel(self, xy, value): def remap_palette(self, dest_map, source_palette=None): def _get_safe_box(self, size, resample, box): def resize(self, size, resample=None, box=None, reducing_gap=None): def reduce(self, factor, box=None): def rotate( self, angle, resample=Resampling.NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): def transform(x, y, matrix): def save(self, fp, format=None, **params): def seek(self, frame): def show(self, title=None): def split(self): def getchannel(self, channel): def tell(self): def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0): def preserve_aspect_ratio(): def round_aspect(number, key): def transform( self, size, method, data=None, resample=Resampling.NEAREST, fill=1, fillcolor=None, ): def __transformer( self, box, image, method, data, resample=Resampling.NEAREST, fill=1 ): def transpose(self, method): def effect_spread(self, distance): def toqimage(self): def toqpixmap(self): def o32le(i): def _save_all(im, fp, filename): append_images = im.encoderinfo.get("append_images", []) if not append_images: try: animated = im.is_animated except AttributeError: animated = False if not animated: _save(im, fp, filename) return mpf_offset = 28 offsets = [] for imSequence in itertools.chain([im], append_images): for im_frame in ImageSequence.Iterator(imSequence): if not offsets: # APP2 marker im_frame.encoderinfo["extra"] = ( b"\xFF\xE2" + struct.pack(">H", 6 + 82) + b"MPF\0" + b" " * 82 ) exif = im_frame.encoderinfo.get("exif") if isinstance(exif, Image.Exif): exif = exif.tobytes() im_frame.encoderinfo["exif"] = exif if exif: mpf_offset += 4 + len(exif) JpegImagePlugin._save(im_frame, fp, filename) offsets.append(fp.tell()) else: im_frame.save(fp, "JPEG") offsets.append(fp.tell() - offsets[-1]) ifd = TiffImagePlugin.ImageFileDirectory_v2() ifd[0xB000] = b"0100" ifd[0xB001] = len(offsets) mpentries = b"" data_offset = 0 for i, size in enumerate(offsets): if i == 0: mptype = 0x030000 # Baseline MP Primary Image else: mptype = 0x000000 # Undefined mpentries += struct.pack("<LLLHH", mptype, size, data_offset, 0, 0) if i == 0: data_offset -= mpf_offset data_offset += size ifd[0xB002] = mpentries fp.seek(mpf_offset) fp.write(b"II\x2A\x00" + o32le(8) + ifd.tobytes(8)) fp.seek(0, os.SEEK_END)
null
174,145
import io import os import struct from . import Image, ImageFile, _binary The provided code snippet includes necessary dependencies for implementing the `_parse_codestream` function. Write a Python function `def _parse_codestream(fp)` to solve the following problem: Parse the JPEG 2000 codestream to extract the size and component count from the SIZ marker segment, returning a PIL (size, mode) tuple. Here is the function: def _parse_codestream(fp): """Parse the JPEG 2000 codestream to extract the size and component count from the SIZ marker segment, returning a PIL (size, mode) tuple.""" hdr = fp.read(2) lsiz = _binary.i16be(hdr) siz = hdr + fp.read(lsiz - 2) lsiz, rsiz, xsiz, ysiz, xosiz, yosiz, _, _, _, _, csiz = struct.unpack_from( ">HHIIIIIIIIH", siz ) ssiz = [None] * csiz xrsiz = [None] * csiz yrsiz = [None] * csiz for i in range(csiz): ssiz[i], xrsiz[i], yrsiz[i] = struct.unpack_from(">BBB", siz, 36 + 3 * i) size = (xsiz - xosiz, ysiz - yosiz) if csiz == 1: if (yrsiz[0] & 0x7F) > 8: mode = "I;16" else: mode = "L" elif csiz == 2: mode = "LA" elif csiz == 3: mode = "RGB" elif csiz == 4: mode = "RGBA" else: mode = None return size, mode
Parse the JPEG 2000 codestream to extract the size and component count from the SIZ marker segment, returning a PIL (size, mode) tuple.
174,146
import io import os import struct from . import Image, ImageFile, _binary class BoxReader: """ A small helper class to read fields stored in JPEG2000 header boxes and to easily step into and read sub-boxes. """ def __init__(self, fp, length=-1): self.fp = fp self.has_length = length >= 0 self.length = length self.remaining_in_box = -1 def _can_read(self, num_bytes): if self.has_length and self.fp.tell() + num_bytes > self.length: # Outside box: ensure we don't read past the known file length return False if self.remaining_in_box >= 0: # Inside box contents: ensure read does not go past box boundaries return num_bytes <= self.remaining_in_box else: return True # No length known, just read def _read_bytes(self, num_bytes): if not self._can_read(num_bytes): msg = "Not enough data in header" raise SyntaxError(msg) data = self.fp.read(num_bytes) if len(data) < num_bytes: msg = f"Expected to read {num_bytes} bytes but only got {len(data)}." raise OSError(msg) if self.remaining_in_box > 0: self.remaining_in_box -= num_bytes return data def read_fields(self, field_format): size = struct.calcsize(field_format) data = self._read_bytes(size) return struct.unpack(field_format, data) def read_boxes(self): size = self.remaining_in_box data = self._read_bytes(size) return BoxReader(io.BytesIO(data), size) def has_next_box(self): if self.has_length: return self.fp.tell() + self.remaining_in_box < self.length else: return True def next_box_type(self): # Skip the rest of the box if it has not been read if self.remaining_in_box > 0: self.fp.seek(self.remaining_in_box, os.SEEK_CUR) self.remaining_in_box = -1 # Read the length and type of the next box lbox, tbox = self.read_fields(">I4s") if lbox == 1: lbox = self.read_fields(">Q")[0] hlen = 16 else: hlen = 8 if lbox < hlen or not self._can_read(lbox - hlen): msg = "Invalid header length" raise SyntaxError(msg) self.remaining_in_box = lbox - hlen return tbox def _res_to_dpi(num, denom, exp): """Convert JPEG2000's (numerator, denominator, exponent-base-10) resolution, calculated as (num / denom) * 10^exp and stored in dots per meter, to floating-point dots per inch.""" if denom != 0: return (254 * num * (10**exp)) / (10000 * denom) The provided code snippet includes necessary dependencies for implementing the `_parse_jp2_header` function. Write a Python function `def _parse_jp2_header(fp)` to solve the following problem: Parse the JP2 header box to extract size, component count, color space information, and optionally DPI information, returning a (size, mode, mimetype, dpi) tuple. Here is the function: def _parse_jp2_header(fp): """Parse the JP2 header box to extract size, component count, color space information, and optionally DPI information, returning a (size, mode, mimetype, dpi) tuple.""" # Find the JP2 header box reader = BoxReader(fp) header = None mimetype = None while reader.has_next_box(): tbox = reader.next_box_type() if tbox == b"jp2h": header = reader.read_boxes() break elif tbox == b"ftyp": if reader.read_fields(">4s")[0] == b"jpx ": mimetype = "image/jpx" size = None mode = None bpc = None nc = None dpi = None # 2-tuple of DPI info, or None while header.has_next_box(): tbox = header.next_box_type() if tbox == b"ihdr": height, width, nc, bpc = header.read_fields(">IIHB") size = (width, height) if nc == 1 and (bpc & 0x7F) > 8: mode = "I;16" elif nc == 1: mode = "L" elif nc == 2: mode = "LA" elif nc == 3: mode = "RGB" elif nc == 4: mode = "RGBA" elif tbox == b"res ": res = header.read_boxes() while res.has_next_box(): tres = res.next_box_type() if tres == b"resc": vrcn, vrcd, hrcn, hrcd, vrce, hrce = res.read_fields(">HHHHBB") hres = _res_to_dpi(hrcn, hrcd, hrce) vres = _res_to_dpi(vrcn, vrcd, vrce) if hres is not None and vres is not None: dpi = (hres, vres) break if size is None or mode is None: msg = "Malformed JP2 header" raise SyntaxError(msg) return size, mode, mimetype, dpi
Parse the JP2 header box to extract size, component count, color space information, and optionally DPI information, returning a (size, mode, mimetype, dpi) tuple.
174,147
import io import os import struct from . import Image, ImageFile, _binary def _accept(prefix): return ( prefix[:4] == b"\xff\x4f\xff\x51" or prefix[:12] == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a" )
null
174,148
import io import os import struct from . import Image, ImageFile, _binary class ImageFile(Image.Image): """Base class for image file format handlers.""" def __init__(self, fp=None, filename=None): super().__init__() self._min_frame = 0 self.custom_mimetype = None self.tile = None """ A list of tile descriptors, or ``None`` """ self.readonly = 1 # until we know better self.decoderconfig = () self.decodermaxblock = MAXBLOCK if is_path(fp): # filename self.fp = open(fp, "rb") self.filename = fp self._exclusive_fp = True else: # stream self.fp = fp self.filename = filename # can be overridden self._exclusive_fp = None try: try: self._open() except ( IndexError, # end of data TypeError, # end of data (ord) KeyError, # unsupported mode EOFError, # got header but not the first frame struct.error, ) as v: raise SyntaxError(v) from v if not self.mode or self.size[0] <= 0 or self.size[1] <= 0: msg = "not identified by this driver" raise SyntaxError(msg) except BaseException: # close the file only if we have opened it this constructor if self._exclusive_fp: self.fp.close() raise def get_format_mimetype(self): if self.custom_mimetype: return self.custom_mimetype if self.format is not None: return Image.MIME.get(self.format.upper()) def __setstate__(self, state): self.tile = [] super().__setstate__(state) def verify(self): """Check file integrity""" # raise exception if something's wrong. must be called # directly after open, and closes file when finished. if self._exclusive_fp: self.fp.close() self.fp = None def load(self): """Load image data based on tile list""" if self.tile is None: msg = "cannot load this image" raise OSError(msg) pixel = Image.Image.load(self) if not self.tile: return pixel self.map = None use_mmap = self.filename and len(self.tile) == 1 # As of pypy 2.1.0, memory mapping was failing here. use_mmap = use_mmap and not hasattr(sys, "pypy_version_info") readonly = 0 # look for read/seek overrides try: read = self.load_read # don't use mmap if there are custom read/seek functions use_mmap = False except AttributeError: read = self.fp.read try: seek = self.load_seek use_mmap = False except AttributeError: seek = self.fp.seek if use_mmap: # try memory mapping decoder_name, extents, offset, args = self.tile[0] if ( decoder_name == "raw" and len(args) >= 3 and args[0] == self.mode and args[0] in Image._MAPMODES ): try: # use mmap, if possible import mmap with open(self.filename) as fp: self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ) if offset + self.size[1] * args[1] > self.map.size(): # buffer is not large enough raise OSError self.im = Image.core.map_buffer( self.map, self.size, decoder_name, offset, args ) readonly = 1 # After trashing self.im, # we might need to reload the palette data. if self.palette: self.palette.dirty = 1 except (AttributeError, OSError, ImportError): self.map = None self.load_prepare() err_code = -3 # initialize to unknown error if not self.map: # sort tiles in file order self.tile.sort(key=_tilesort) try: # FIXME: This is a hack to handle TIFF's JpegTables tag. prefix = self.tile_prefix except AttributeError: prefix = b"" # Remove consecutive duplicates that only differ by their offset self.tile = [ list(tiles)[-1] for _, tiles in itertools.groupby( self.tile, lambda tile: (tile[0], tile[1], tile[3]) ) ] for decoder_name, extents, offset, args in self.tile: seek(offset) decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) err_code = decoder.decode(b"")[1] else: b = prefix while True: try: s = read(self.decodermaxblock) except (IndexError, struct.error) as e: # truncated png/gif if LOAD_TRUNCATED_IMAGES: break else: msg = "image file is truncated" raise OSError(msg) from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: msg = ( "image file is truncated " f"({len(b)} bytes not processed)" ) raise OSError(msg) b = b + s n, err_code = decoder.decode(b) if n < 0: break b = b[n:] finally: # Need to cleanup here to prevent leaks decoder.cleanup() self.tile = [] self.readonly = readonly self.load_end() if self._exclusive_fp and self._close_exclusive_fp_after_loading: self.fp.close() self.fp = None if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0: # still raised if decoder fails to return anything raise_oserror(err_code) return Image.Image.load(self) def load_prepare(self): # create image memory if necessary if not self.im or self.im.mode != self.mode or self.im.size != self.size: self.im = Image.core.new(self.mode, self.size) # create palette (optional) if self.mode == "P": Image.Image.load(self) def load_end(self): # may be overridden pass # may be defined for contained formats # def load_seek(self, pos): # pass # may be defined for blocked formats (e.g. PNG) # def load_read(self, bytes): # pass def _seek_check(self, frame): if ( frame < self._min_frame # Only check upper limit on frames if additional seek operations # are not required to do so or ( not (hasattr(self, "_n_frames") and self._n_frames is None) and frame >= self.n_frames + self._min_frame ) ): msg = "attempt to seek outside sequence" raise EOFError(msg) return self.tell() != frame def _save(im, fp, filename): # Get the keyword arguments info = im.encoderinfo if filename.endswith(".j2k") or info.get("no_jp2", False): kind = "j2k" else: kind = "jp2" offset = info.get("offset", None) tile_offset = info.get("tile_offset", None) tile_size = info.get("tile_size", None) quality_mode = info.get("quality_mode", "rates") quality_layers = info.get("quality_layers", None) if quality_layers is not None and not ( isinstance(quality_layers, (list, tuple)) and all( [ isinstance(quality_layer, (int, float)) for quality_layer in quality_layers ] ) ): msg = "quality_layers must be a sequence of numbers" raise ValueError(msg) num_resolutions = info.get("num_resolutions", 0) cblk_size = info.get("codeblock_size", None) precinct_size = info.get("precinct_size", None) irreversible = info.get("irreversible", False) progression = info.get("progression", "LRCP") cinema_mode = info.get("cinema_mode", "no") mct = info.get("mct", 0) signed = info.get("signed", False) comment = info.get("comment") if isinstance(comment, str): comment = comment.encode() plt = info.get("plt", False) fd = -1 if hasattr(fp, "fileno"): try: fd = fp.fileno() except Exception: fd = -1 im.encoderconfig = ( offset, tile_offset, tile_size, quality_mode, quality_layers, num_resolutions, cblk_size, precinct_size, irreversible, progression, cinema_mode, mct, signed, fd, comment, plt, ) ImageFile._save(im, fp, [("jpeg2k", (0, 0) + im.size, 0, kind)])
null