id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
167,665
import re from . import Image, ImageFile 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 isPath(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: raise SyntaxError("not identified by this driver") 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 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: raise OSError("cannot load this image") 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) 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: decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: seek(offset) decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) status, err_code = decoder.decode(b"") 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: raise OSError("image file is truncated") from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: raise OSError( "image file is truncated " f"({len(b)} bytes not processed)" ) 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 ) ): raise EOFError("attempt to seek outside sequence") return self.tell() != frame def _save(im, fp, filename): if im.mode != "1": raise OSError(f"cannot write mode {im.mode} as XBM") 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
167,666
import io import itertools import logging 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 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 ] def _accept(prefix): return prefix[:4] in PREFIXES
null
167,667
import io import itertools import logging 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 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 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
167,668
import io import itertools import logging 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 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): class AppendingTiffWriter: def __init__(self, fn, new=False): def setup(self): def finalize(self): def newFrame(self): def __enter__(self): def __exit__(self, exc_type, exc_value, traceback): def tell(self): def seek(self, offset, whence=io.SEEK_SET): def goToEnd(self): def setEndian(self, endian): def skipIFDs(self): def write(self, data): def readShort(self): def readLong(self): def rewriteLastShortToLong(self, value): def rewriteLastShort(self, value): def rewriteLastLong(self, value): def writeShort(self, value): def writeLong(self, value): def close(self): def fixIFD(self): def fixOffsets(self, count, isShort=False, isLong=False): 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
167,669
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile, TiffImagePlugin from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 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 isPath(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: raise SyntaxError("not identified by this driver") 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 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: raise OSError("cannot load this image") 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) 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: decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: seek(offset) decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) status, err_code = decoder.decode(b"") 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: raise OSError("image file is truncated") from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: raise OSError( "image file is truncated " f"({len(b)} bytes not processed)" ) 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 ) ): raise EOFError("attempt to seek outside sequence") return self.tell() != frame def Skip(self, marker): n = i16(self.fp.read(2)) - 2 ImageFile._safe_read(self.fp, n)
null
167,670
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile, TiffImagePlugin from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 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 isPath(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: raise SyntaxError("not identified by this driver") 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 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: raise OSError("cannot load this image") 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) 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: decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: seek(offset) decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) status, err_code = decoder.decode(b"") 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: raise OSError("image file is truncated") from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: raise OSError( "image file is truncated " f"({len(b)} bytes not processed)" ) 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 ) ): raise EOFError("attempt to seek outside sequence") return self.tell() != 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 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
167,671
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile, TiffImagePlugin from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 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 isPath(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: raise SyntaxError("not identified by this driver") 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 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: raise OSError("cannot load this image") 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) 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: decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: seek(offset) decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) status, err_code = decoder.decode(b"") 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: raise OSError("image file is truncated") from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: raise OSError( "image file is truncated " f"({len(b)} bytes not processed)" ) 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 ) ): raise EOFError("attempt to seek outside sequence") 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
167,672
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile, TiffImagePlugin from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 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 isPath(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: raise SyntaxError("not identified by this driver") 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 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: raise OSError("cannot load this image") 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) 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: decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: seek(offset) decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) status, err_code = decoder.decode(b"") 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: raise OSError("image file is truncated") from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: raise OSError( "image file is truncated " f"({len(b)} bytes not processed)" ) 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 ) ): raise EOFError("attempt to seek outside sequence") 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: raise SyntaxError(f"cannot handle {self.bits}-bit layers") 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: raise SyntaxError(f"cannot handle {self.layers}-layer images") 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
167,673
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile, TiffImagePlugin from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 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 isPath(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: raise SyntaxError("not identified by this driver") 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 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: raise OSError("cannot load this image") 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) 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: decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: seek(offset) decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) status, err_code = decoder.decode(b"") 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: raise OSError("image file is truncated") from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: raise OSError( "image file is truncated " f"({len(b)} bytes not processed)" ) 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 ) ): raise EOFError("attempt to seek outside sequence") 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: raise SyntaxError("bad quantization table marker") 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
167,674
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile, TiffImagePlugin from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from .JpegPresets import presets def _accept(prefix): # Magic number was taken from https://en.wikipedia.org/wiki/JPEG return prefix[0:3] == b"\xFF\xD8\xFF"
null
167,675
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile, TiffImagePlugin from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from .JpegPresets import presets def _getexif(self): if "exif" not in self.info: return None return self.getexif()._get_merged_dict()
null
167,676
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile, TiffImagePlugin from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from .JpegPresets import presets def convert_dict_qtables(qtables): warnings.warn( "convert_dict_qtables is deprecated and will be removed in Pillow 10" "(2023-07-01). Conversion is no longer needed.", DeprecationWarning, ) return qtables
null
167,677
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile, TiffImagePlugin from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from .JpegPresets import presets RAWMODE = { "1": "L", "L": "L", "RGB": "RGB", "RGBX": "RGB", "CMYK": "CMYK;I", # assume adobe conventions "YCbCr": "YCbCr", } def get_sampling(im): # There's no subsampling when images have only 1 layer # (grayscale images) or when they are CMYK (4 layers), # so set subsampling to the default value. # # NOTE: currently Pillow can't encode JPEG to YCCK format. # If YCCK support is added in the future, subsampling code will have # to be updated (here and in JpegEncode.c) to deal with 4 layers. if not hasattr(im, "layers") or im.layers in (1, 4): return -1 sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3] return samplings.get(sampling, -1) Image.register_open(JpegImageFile.format, jpeg_factory, _accept) Image.register_save(JpegImageFile.format, _save) Image.register_extensions(JpegImageFile.format, [".jfif", ".jpe", ".jpg", ".jpeg"]) Image.register_mime(JpegImageFile.format, "image/jpeg") 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": warnings.warn( "Image categories are deprecated and will be removed in Pillow 10 " "(2023-07-01). Use is_animated instead.", DeprecationWarning, stacklevel=2, ) 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 hasattr(self, "_close__fp"): self._close__fp() 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 hasattr(self, "_close__fp"): self._close__fp() 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 = deferred_error(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.readonly == other.readonly 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_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: raise ValueError("Could not save to PNG for display") from e return b.getvalue() class _ArrayData: def __init__(self, new): self.__array_interface__ = new def __array__(self, dtype=None): # numpy array interface support import numpy as np new = {} shape, typestr = _conv_type_shape(self) new["shape"] = shape new["typestr"] = typestr new["version"] = 3 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() return np.array(self._ArrayData(new), dtype) def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) self.tile = [] 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. :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() # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c data = [] while True: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError(f"encoder error {s} in tobytes") return b"".join(data) 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": raise ValueError("not a bitmap") 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: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data") 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 and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() if mode == "RGBA": mode = "RGB" self.info["transparency"] = arr[3::4] arr = bytes( value for (index, value) in enumerate(arr) if index % 4 != 3 ) palette_length = 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: self.palette.mode = "RGB" self.palette.palette = self.im.getpalette()[: palette_length * 3] if self.im: 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=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 :data:`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. :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:`NONE` or :data:`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:`WEB` or :data:`ADAPTIVE`. :param colors: Number of colors to use for the :data:`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"): raise ValueError("illegal conversion") 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", "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: raise ValueError("Transparency for P mode should be bytes or int") if mode == "P" and 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 # colorspace conversion if dither is None: dither = FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError as e: raise ValueError("illegal conversion") from e new_im = self._new(im) if mode == "P" and 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=1): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`MEDIANCUT` (median cut), :data:`MAXCOVERAGE` (maximum coverage), :data:`FASTOCTREE` (fast octree), :data:`LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`MEDIANCUT` will be used. The exception to this is RGBA images. :data:`MEDIANCUT` and :data:`MAXCOVERAGE` do not support RGBA images, so :data:`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:`NONE` or :data:`FLOYDSTEINBERG` (default). Default: 1 (legacy setting) :returns: A new image """ self.load() if method is None: # defaults: method = MEDIANCUT if self.mode == "RGBA": method = FASTOCTREE if self.mode == "RGBA" and method not in (FASTOCTREE, LIBIMAGEQUANT): # Caller specified an invalid mode. raise ValueError( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) 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() 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. """ 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"): raise TypeError( "filter argument should be ImageFilter.Filter instance or class" ) 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 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): if self._exif is None: self._exif = Exif() 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.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[1]) return self._exif 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): """ Returns the image palette as a list. :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: return list(self.im.getpalette()) except ValueError: return None # no palette 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. 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" or "RGBA" images (in the latter case, 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? raise ValueError("cannot determine region size; use 4-item box") 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 ("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)): raise ValueError("Source must be a tuple") if not isinstance(dest, (list, tuple)): raise ValueError("Destination must be a tuple") if not len(source) in (2, 4): raise ValueError("Source must be a 2 or 4-tuple") if not len(dest) == 2: raise ValueError("Destination must be a 2-tuple") if min(source) < 0: raise ValueError("Source must be non-negative") 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 raise ValueError("point operation not supported for this mode") 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: raise ValueError("illegal image mode") 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"): raise ValueError("illegal image mode") 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" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): raise ValueError("illegal image mode") 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 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 == "P" and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P image value = self.palette.getcolor(value, self) 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"): raise ValueError("illegal image mode") if source_palette is None: if self.mode == "P": self.load() source_palette = self.im.getpalette("RGB")[:768] 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 * 3 : oldPosition * 3 + 3] 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("RGB", palette=mapping_palette * 3) # 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("RGB;L", m_im.palette.tobytes()) m_im = m_im.convert("L") # Internally, we require 768 bytes for a palette. new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b"\x00" m_im.putpalette(new_palette_bytes) m_im.palette = ImagePalette.ImagePalette("RGB", palette=palette_bytes) 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:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`PIL.Image.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`PIL.Image.NEAREST`. Otherwise, the default filter is :py:data:`PIL.Image.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 = NEAREST if type_special else BICUBIC elif resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING): message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (LANCZOS, "Image.LANCZOS"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), (BOX, "Image.BOX"), (HAMMING, "Image.HAMMING"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) if reducing_gap is not None and reducing_gap < 1.0: raise ValueError("reducing_gap must be 1.0 or greater") size = tuple(size) 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 = NEAREST if self.mode in ["LA", "RGBA"] and resample != 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 != 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=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:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.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:`PIL.Image.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(ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose(ROTATE_90 if angle == 90 else 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), 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 isPath(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 isPath(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: raise ValueError(f"unknown file extension: {ext}") from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] if open_fp: 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) finally: # do what we can to clean up 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: raise ValueError(f'The image has no channel "{channel}"') 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=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: Requested size. :param resample: Optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If omitted, it defaults to :py:data:`PIL.Image.BICUBIC`. (was :py:data:`PIL.Image.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 """ x, y = map(math.floor, size) if x >= self.width and y >= self.height: return def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) # preserve aspect ratio 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) ) size = (x, y) box = None if reducing_gap is not None: res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] 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=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. :param method: The transformation method. This is one of :py:data:`PIL.Image.EXTENT` (cut out a rectangular subregion), :py:data:`PIL.Image.AFFINE` (affine transform), :py:data:`PIL.Image.PERSPECTIVE` (perspective transform), :py:data:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or :py:data:`PIL.Image.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.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:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.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:`PIL.Image.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 != 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: raise ValueError("missing method data") 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 == MESH: # list of quads for box, quad in data: im.__transformer(box, self, 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=NEAREST, fill=1): w = box[2] - box[0] h = box[3] - box[1] if method == AFFINE: data = data[0:6] elif method == EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == PERSPECTIVE: data = data[0:8] elif method == QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[0: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: raise ValueError("unknown transformation method") if resample not in (NEAREST, BILINEAR, BICUBIC): if resample in (BOX, HAMMING, LANCZOS): message = { BOX: "Image.BOX", HAMMING: "Image.HAMMING", LANCZOS: "Image.LANCZOS/Image.ANTIALIAS", }[resample] + f" ({resample}) cannot be used." else: message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) image.load() self.load() if image.mode in ("1", "P"): resample = 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:`PIL.Image.FLIP_LEFT_RIGHT`, :py:data:`PIL.Image.FLIP_TOP_BOTTOM`, :py:data:`PIL.Image.ROTATE_90`, :py:data:`PIL.Image.ROTATE_180`, :py:data:`PIL.Image.ROTATE_270`, :py:data:`PIL.Image.TRANSPOSE` or :py:data:`PIL.Image.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: raise ImportError("Qt bindings are not installed") return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") 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 isPath(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: raise SyntaxError("not identified by this driver") 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 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: raise OSError("cannot load this image") 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) 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: decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: seek(offset) decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) status, err_code = decoder.decode(b"") 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: raise OSError("image file is truncated") from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: raise OSError( "image file is truncated " f"({len(b)} bytes not processed)" ) 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 ) ): raise EOFError("attempt to seek outside sequence") return self.tell() != frame def o8(i): return bytes((i & 255,)) presets = { 'web_low': {'subsampling': 2, # "4:2:0" 'quantization': [ [20, 16, 25, 39, 50, 46, 62, 68, 16, 18, 23, 38, 38, 53, 65, 68, 25, 23, 31, 38, 53, 65, 68, 68, 39, 38, 38, 53, 65, 68, 68, 68, 50, 38, 53, 65, 68, 68, 68, 68, 46, 53, 65, 68, 68, 68, 68, 68, 62, 65, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68], [21, 25, 32, 38, 54, 68, 68, 68, 25, 28, 24, 38, 54, 68, 68, 68, 32, 24, 32, 43, 66, 68, 68, 68, 38, 38, 43, 53, 68, 68, 68, 68, 54, 54, 66, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68] ]}, 'web_medium': {'subsampling': 2, # "4:2:0" 'quantization': [ [16, 11, 11, 16, 23, 27, 31, 30, 11, 12, 12, 15, 20, 23, 23, 30, 11, 12, 13, 16, 23, 26, 35, 47, 16, 15, 16, 23, 26, 37, 47, 64, 23, 20, 23, 26, 39, 51, 64, 64, 27, 23, 26, 37, 51, 64, 64, 64, 31, 23, 35, 47, 64, 64, 64, 64, 30, 30, 47, 64, 64, 64, 64, 64], [17, 15, 17, 21, 20, 26, 38, 48, 15, 19, 18, 17, 20, 26, 35, 43, 17, 18, 20, 22, 26, 30, 46, 53, 21, 17, 22, 28, 30, 39, 53, 64, 20, 20, 26, 30, 39, 48, 64, 64, 26, 26, 30, 39, 48, 63, 64, 64, 38, 35, 46, 53, 64, 64, 64, 64, 48, 43, 53, 64, 64, 64, 64, 64] ]}, 'web_high': {'subsampling': 0, # "4:4:4" 'quantization': [ [6, 4, 4, 6, 9, 11, 12, 16, 4, 5, 5, 6, 8, 10, 12, 12, 4, 5, 5, 6, 10, 12, 14, 19, 6, 6, 6, 11, 12, 15, 19, 28, 9, 8, 10, 12, 16, 20, 27, 31, 11, 10, 12, 15, 20, 27, 31, 31, 12, 12, 14, 19, 27, 31, 31, 31, 16, 12, 19, 28, 31, 31, 31, 31], [7, 7, 13, 24, 26, 31, 31, 31, 7, 12, 16, 21, 31, 31, 31, 31, 13, 16, 17, 31, 31, 31, 31, 31, 24, 21, 31, 31, 31, 31, 31, 31, 26, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31] ]}, 'web_very_high': {'subsampling': 0, # "4:4:4" 'quantization': [ [2, 2, 2, 2, 3, 4, 5, 6, 2, 2, 2, 2, 3, 4, 5, 6, 2, 2, 2, 2, 4, 5, 7, 9, 2, 2, 2, 4, 5, 7, 9, 12, 3, 3, 4, 5, 8, 10, 12, 12, 4, 4, 5, 7, 10, 12, 12, 12, 5, 5, 7, 9, 12, 12, 12, 12, 6, 6, 9, 12, 12, 12, 12, 12], [3, 3, 5, 9, 13, 15, 15, 15, 3, 4, 6, 11, 14, 12, 12, 12, 5, 6, 9, 14, 12, 12, 12, 12, 9, 11, 14, 12, 12, 12, 12, 12, 13, 14, 12, 12, 12, 12, 12, 12, 15, 12, 12, 12, 12, 12, 12, 12, 15, 12, 12, 12, 12, 12, 12, 12, 15, 12, 12, 12, 12, 12, 12, 12] ]}, 'web_maximum': {'subsampling': 0, # "4:4:4" 'quantization': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 2, 2, 3, 1, 1, 1, 1, 2, 2, 3, 3, 1, 1, 1, 2, 2, 3, 3, 3, 1, 1, 2, 2, 3, 3, 3, 3], [1, 1, 1, 2, 2, 3, 3, 3, 1, 1, 1, 2, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] ]}, 'low': {'subsampling': 2, # "4:2:0" 'quantization': [ [18, 14, 14, 21, 30, 35, 34, 17, 14, 16, 16, 19, 26, 23, 12, 12, 14, 16, 17, 21, 23, 12, 12, 12, 21, 19, 21, 23, 12, 12, 12, 12, 30, 26, 23, 12, 12, 12, 12, 12, 35, 23, 12, 12, 12, 12, 12, 12, 34, 12, 12, 12, 12, 12, 12, 12, 17, 12, 12, 12, 12, 12, 12, 12], [20, 19, 22, 27, 20, 20, 17, 17, 19, 25, 23, 14, 14, 12, 12, 12, 22, 23, 14, 14, 12, 12, 12, 12, 27, 14, 14, 12, 12, 12, 12, 12, 20, 14, 12, 12, 12, 12, 12, 12, 20, 12, 12, 12, 12, 12, 12, 12, 17, 12, 12, 12, 12, 12, 12, 12, 17, 12, 12, 12, 12, 12, 12, 12] ]}, 'medium': {'subsampling': 2, # "4:2:0" 'quantization': [ [12, 8, 8, 12, 17, 21, 24, 17, 8, 9, 9, 11, 15, 19, 12, 12, 8, 9, 10, 12, 19, 12, 12, 12, 12, 11, 12, 21, 12, 12, 12, 12, 17, 15, 19, 12, 12, 12, 12, 12, 21, 19, 12, 12, 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 12, 12, 17, 12, 12, 12, 12, 12, 12, 12], [13, 11, 13, 16, 20, 20, 17, 17, 11, 14, 14, 14, 14, 12, 12, 12, 13, 14, 14, 14, 12, 12, 12, 12, 16, 14, 14, 12, 12, 12, 12, 12, 20, 14, 12, 12, 12, 12, 12, 12, 20, 12, 12, 12, 12, 12, 12, 12, 17, 12, 12, 12, 12, 12, 12, 12, 17, 12, 12, 12, 12, 12, 12, 12] ]}, 'high': {'subsampling': 0, # "4:4:4" 'quantization': [ [6, 4, 4, 6, 9, 11, 12, 16, 4, 5, 5, 6, 8, 10, 12, 12, 4, 5, 5, 6, 10, 12, 12, 12, 6, 6, 6, 11, 12, 12, 12, 12, 9, 8, 10, 12, 12, 12, 12, 12, 11, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 16, 12, 12, 12, 12, 12, 12, 12], [7, 7, 13, 24, 20, 20, 17, 17, 7, 12, 16, 14, 14, 12, 12, 12, 13, 16, 14, 14, 12, 12, 12, 12, 24, 14, 14, 12, 12, 12, 12, 12, 20, 14, 12, 12, 12, 12, 12, 12, 20, 12, 12, 12, 12, 12, 12, 12, 17, 12, 12, 12, 12, 12, 12, 12, 17, 12, 12, 12, 12, 12, 12, 12] ]}, 'maximum': {'subsampling': 0, # "4:4:4" 'quantization': [ [2, 2, 2, 2, 3, 4, 5, 6, 2, 2, 2, 2, 3, 4, 5, 6, 2, 2, 2, 2, 4, 5, 7, 9, 2, 2, 2, 4, 5, 7, 9, 12, 3, 3, 4, 5, 8, 10, 12, 12, 4, 4, 5, 7, 10, 12, 12, 12, 5, 5, 7, 9, 12, 12, 12, 12, 6, 6, 9, 12, 12, 12, 12, 12], [3, 3, 5, 9, 13, 15, 15, 15, 3, 4, 6, 10, 14, 12, 12, 12, 5, 6, 9, 14, 12, 12, 12, 12, 9, 10, 14, 12, 12, 12, 12, 12, 13, 14, 12, 12, 12, 12, 12, 12, 15, 12, 12, 12, 12, 12, 12, 12, 15, 12, 12, 12, 12, 12, 12, 12, 15, 12, 12, 12, 12, 12, 12, 12] ]}, } def _save(im, fp, filename): try: rawmode = RAWMODE[im.mode] except KeyError as e: raise OSError(f"cannot write mode {im.mode} as JPEG") from e info = im.encoderinfo dpi = [round(x) for x in info.get("dpi", (0, 0))] quality = info.get("quality", -1) subsampling = info.get("subsampling", -1) qtables = info.get("qtables") if quality == "keep": quality = -1 subsampling = "keep" qtables = "keep" elif quality in presets: preset = presets[quality] quality = -1 subsampling = preset.get("subsampling", -1) qtables = preset.get("quantization") elif not isinstance(quality, int): raise ValueError("Invalid quality setting") else: if subsampling in presets: subsampling = presets[subsampling].get("subsampling", -1) if isinstance(qtables, str) and qtables in presets: qtables = presets[qtables].get("quantization") if subsampling == "4:4:4": subsampling = 0 elif subsampling == "4:2:2": subsampling = 1 elif subsampling == "4:2:0": subsampling = 2 elif subsampling == "4:1:1": # For compatibility. Before Pillow 4.3, 4:1:1 actually meant 4:2:0. # Set 4:2:0 if someone is still using that value. subsampling = 2 elif subsampling == "keep": if im.format != "JPEG": raise ValueError("Cannot use 'keep' when original image is not a JPEG") subsampling = get_sampling(im) def validate_qtables(qtables): if qtables is None: return qtables if isinstance(qtables, str): try: lines = [ int(num) for line in qtables.splitlines() for num in line.split("#", 1)[0].split() ] except ValueError as e: raise ValueError("Invalid quantization table") from e else: qtables = [lines[s : s + 64] for s in range(0, len(lines), 64)] if isinstance(qtables, (tuple, list, dict)): if isinstance(qtables, dict): qtables = [ qtables[key] for key in range(len(qtables)) if key in qtables ] elif isinstance(qtables, tuple): qtables = list(qtables) if not (0 < len(qtables) < 5): raise ValueError("None or too many quantization tables") for idx, table in enumerate(qtables): try: if len(table) != 64: raise TypeError table = array.array("H", table) except TypeError as e: raise ValueError("Invalid quantization table") from e else: qtables[idx] = list(table) return qtables if qtables == "keep": if im.format != "JPEG": raise ValueError("Cannot use 'keep' when original image is not a JPEG") qtables = getattr(im, "quantization", None) qtables = validate_qtables(qtables) extra = b"" icc_profile = info.get("icc_profile") if icc_profile: ICC_OVERHEAD_LEN = 14 MAX_BYTES_IN_MARKER = 65533 MAX_DATA_BYTES_IN_MARKER = MAX_BYTES_IN_MARKER - ICC_OVERHEAD_LEN markers = [] while icc_profile: markers.append(icc_profile[:MAX_DATA_BYTES_IN_MARKER]) icc_profile = icc_profile[MAX_DATA_BYTES_IN_MARKER:] i = 1 for marker in markers: size = struct.pack(">H", 2 + ICC_OVERHEAD_LEN + len(marker)) extra += ( b"\xFF\xE2" + size + b"ICC_PROFILE\0" + o8(i) + o8(len(markers)) + marker ) i += 1 # "progressive" is the official name, but older documentation # says "progression" # FIXME: issue a warning if the wrong form is used (post-1.1.7) progressive = info.get("progressive", False) or info.get("progression", False) optimize = info.get("optimize", False) exif = info.get("exif", b"") if isinstance(exif, Image.Exif): exif = exif.tobytes() # get keyword arguments im.encoderconfig = ( quality, progressive, info.get("smooth", 0), optimize, info.get("streamtype", 0), dpi[0], dpi[1], subsampling, qtables, extra, exif, ) # if we optimize, libjpeg needs a buffer big enough to hold the whole image # in a shot. Guessing on the size, at im.size bytes. (raw pixel size is # channels*size, this is a value that's been used in a django patch. # https://github.com/matthewwithanm/django-imagekit/issues/50 bufsize = 0 if optimize or progressive: # CMYK can be bigger if im.mode == "CMYK": bufsize = 4 * im.size[0] * im.size[1] # keep sets quality to -1, but the actual value may be high. elif quality >= 95 or quality == -1: bufsize = 2 * im.size[0] * im.size[1] else: bufsize = im.size[0] * im.size[1] # The EXIF info needs to be written as one block, + APP1, + one spare byte. # Ensure that our buffer is big enough. Same with the icc_profile block. bufsize = max(ImageFile.MAXBLOCK, bufsize, len(exif) + 5, len(extra) + 1) ImageFile._save(im, fp, [("jpeg", (0, 0) + im.size, 0, rawmode)], bufsize)
null
167,678
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile, TiffImagePlugin from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 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
167,679
import array import io import math import os import struct import subprocess import sys import tempfile import warnings from . import Image, ImageFile, TiffImagePlugin from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from .JpegPresets import presets class JpegImageFile(ImageFile.ImageFile): def _open(self): def load_read(self, read_bytes): def draft(self, mode, size): def load_djpeg(self): def _getexif(self): def _getmp(self): def getxmp(self): def _getmp(self): class MpoImageFile(JpegImagePlugin.JpegImageFile): def _open(self): def _after_jpeg_open(self, mpheader=None): def load_seek(self, pos): def seek(self, frame): def tell(self): def _close__fp(self): def adopt(jpeg_instance, mpheader=None): 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
167,680
import sys from . import Image if sys.platform == "darwin": import os import subprocess import tempfile 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": warnings.warn( "Image categories are deprecated and will be removed in Pillow 10 " "(2023-07-01). Use is_animated instead.", DeprecationWarning, stacklevel=2, ) 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 hasattr(self, "_close__fp"): self._close__fp() 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 hasattr(self, "_close__fp"): self._close__fp() 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 = deferred_error(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.readonly == other.readonly 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_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: raise ValueError("Could not save to PNG for display") from e return b.getvalue() class _ArrayData: def __init__(self, new): self.__array_interface__ = new def __array__(self, dtype=None): # numpy array interface support import numpy as np new = {} shape, typestr = _conv_type_shape(self) new["shape"] = shape new["typestr"] = typestr new["version"] = 3 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() return np.array(self._ArrayData(new), dtype) def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) self.tile = [] 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. :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() # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c data = [] while True: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError(f"encoder error {s} in tobytes") return b"".join(data) 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": raise ValueError("not a bitmap") 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: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data") 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 and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() if mode == "RGBA": mode = "RGB" self.info["transparency"] = arr[3::4] arr = bytes( value for (index, value) in enumerate(arr) if index % 4 != 3 ) palette_length = 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: self.palette.mode = "RGB" self.palette.palette = self.im.getpalette()[: palette_length * 3] if self.im: 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=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 :data:`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. :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:`NONE` or :data:`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:`WEB` or :data:`ADAPTIVE`. :param colors: Number of colors to use for the :data:`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"): raise ValueError("illegal conversion") 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", "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: raise ValueError("Transparency for P mode should be bytes or int") if mode == "P" and 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 # colorspace conversion if dither is None: dither = FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError as e: raise ValueError("illegal conversion") from e new_im = self._new(im) if mode == "P" and 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=1): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`MEDIANCUT` (median cut), :data:`MAXCOVERAGE` (maximum coverage), :data:`FASTOCTREE` (fast octree), :data:`LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`MEDIANCUT` will be used. The exception to this is RGBA images. :data:`MEDIANCUT` and :data:`MAXCOVERAGE` do not support RGBA images, so :data:`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:`NONE` or :data:`FLOYDSTEINBERG` (default). Default: 1 (legacy setting) :returns: A new image """ self.load() if method is None: # defaults: method = MEDIANCUT if self.mode == "RGBA": method = FASTOCTREE if self.mode == "RGBA" and method not in (FASTOCTREE, LIBIMAGEQUANT): # Caller specified an invalid mode. raise ValueError( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) 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() 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. """ 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"): raise TypeError( "filter argument should be ImageFilter.Filter instance or class" ) 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 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): if self._exif is None: self._exif = Exif() 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.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[1]) return self._exif 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): """ Returns the image palette as a list. :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: return list(self.im.getpalette()) except ValueError: return None # no palette 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. 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" or "RGBA" images (in the latter case, 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? raise ValueError("cannot determine region size; use 4-item box") 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 ("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)): raise ValueError("Source must be a tuple") if not isinstance(dest, (list, tuple)): raise ValueError("Destination must be a tuple") if not len(source) in (2, 4): raise ValueError("Source must be a 2 or 4-tuple") if not len(dest) == 2: raise ValueError("Destination must be a 2-tuple") if min(source) < 0: raise ValueError("Source must be non-negative") 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 raise ValueError("point operation not supported for this mode") 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: raise ValueError("illegal image mode") 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"): raise ValueError("illegal image mode") 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" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): raise ValueError("illegal image mode") 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 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 == "P" and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P image value = self.palette.getcolor(value, self) 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"): raise ValueError("illegal image mode") if source_palette is None: if self.mode == "P": self.load() source_palette = self.im.getpalette("RGB")[:768] 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 * 3 : oldPosition * 3 + 3] 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("RGB", palette=mapping_palette * 3) # 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("RGB;L", m_im.palette.tobytes()) m_im = m_im.convert("L") # Internally, we require 768 bytes for a palette. new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b"\x00" m_im.putpalette(new_palette_bytes) m_im.palette = ImagePalette.ImagePalette("RGB", palette=palette_bytes) 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:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`PIL.Image.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`PIL.Image.NEAREST`. Otherwise, the default filter is :py:data:`PIL.Image.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 = NEAREST if type_special else BICUBIC elif resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING): message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (LANCZOS, "Image.LANCZOS"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), (BOX, "Image.BOX"), (HAMMING, "Image.HAMMING"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) if reducing_gap is not None and reducing_gap < 1.0: raise ValueError("reducing_gap must be 1.0 or greater") size = tuple(size) 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 = NEAREST if self.mode in ["LA", "RGBA"] and resample != 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 != 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=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:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.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:`PIL.Image.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(ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose(ROTATE_90 if angle == 90 else 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), 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 isPath(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 isPath(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: raise ValueError(f"unknown file extension: {ext}") from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] if open_fp: 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) finally: # do what we can to clean up 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: raise ValueError(f'The image has no channel "{channel}"') 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=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: Requested size. :param resample: Optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If omitted, it defaults to :py:data:`PIL.Image.BICUBIC`. (was :py:data:`PIL.Image.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 """ x, y = map(math.floor, size) if x >= self.width and y >= self.height: return def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) # preserve aspect ratio 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) ) size = (x, y) box = None if reducing_gap is not None: res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] 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=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. :param method: The transformation method. This is one of :py:data:`PIL.Image.EXTENT` (cut out a rectangular subregion), :py:data:`PIL.Image.AFFINE` (affine transform), :py:data:`PIL.Image.PERSPECTIVE` (perspective transform), :py:data:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or :py:data:`PIL.Image.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.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:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.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:`PIL.Image.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 != 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: raise ValueError("missing method data") 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 == MESH: # list of quads for box, quad in data: im.__transformer(box, self, 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=NEAREST, fill=1): w = box[2] - box[0] h = box[3] - box[1] if method == AFFINE: data = data[0:6] elif method == EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == PERSPECTIVE: data = data[0:8] elif method == QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[0: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: raise ValueError("unknown transformation method") if resample not in (NEAREST, BILINEAR, BICUBIC): if resample in (BOX, HAMMING, LANCZOS): message = { BOX: "Image.BOX", HAMMING: "Image.HAMMING", LANCZOS: "Image.LANCZOS/Image.ANTIALIAS", }[resample] + f" ({resample}) cannot be used." else: message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) image.load() self.load() if image.mode in ("1", "P"): resample = 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:`PIL.Image.FLIP_LEFT_RIGHT`, :py:data:`PIL.Image.FLIP_TOP_BOTTOM`, :py:data:`PIL.Image.ROTATE_90`, :py:data:`PIL.Image.ROTATE_180`, :py:data:`PIL.Image.ROTATE_270`, :py:data:`PIL.Image.TRANSPOSE` or :py:data:`PIL.Image.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: raise ImportError("Qt bindings are not installed") return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.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) subprocess.call(["screencapture", "-x", filepath]) im = Image.open(filepath) im.load() os.unlink(filepath) if bbox: im_cropped = im.crop(bbox) im.close() return im_cropped 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 # use xdisplay=None for default display on non-win32/macOS systems if not Image.core.HAVE_XCB: raise OSError("Pillow was built without XCB support") 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
167,681
import sys from . import Image if sys.platform == "darwin": import os import subprocess import tempfile 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": warnings.warn( "Image categories are deprecated and will be removed in Pillow 10 " "(2023-07-01). Use is_animated instead.", DeprecationWarning, stacklevel=2, ) 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 hasattr(self, "_close__fp"): self._close__fp() 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 hasattr(self, "_close__fp"): self._close__fp() 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 = deferred_error(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.readonly == other.readonly 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_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: raise ValueError("Could not save to PNG for display") from e return b.getvalue() class _ArrayData: def __init__(self, new): self.__array_interface__ = new def __array__(self, dtype=None): # numpy array interface support import numpy as np new = {} shape, typestr = _conv_type_shape(self) new["shape"] = shape new["typestr"] = typestr new["version"] = 3 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() return np.array(self._ArrayData(new), dtype) def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) self.tile = [] 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. :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() # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c data = [] while True: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError(f"encoder error {s} in tobytes") return b"".join(data) 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": raise ValueError("not a bitmap") 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: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data") 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 and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() if mode == "RGBA": mode = "RGB" self.info["transparency"] = arr[3::4] arr = bytes( value for (index, value) in enumerate(arr) if index % 4 != 3 ) palette_length = 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: self.palette.mode = "RGB" self.palette.palette = self.im.getpalette()[: palette_length * 3] if self.im: 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=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 :data:`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. :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:`NONE` or :data:`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:`WEB` or :data:`ADAPTIVE`. :param colors: Number of colors to use for the :data:`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"): raise ValueError("illegal conversion") 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", "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: raise ValueError("Transparency for P mode should be bytes or int") if mode == "P" and 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 # colorspace conversion if dither is None: dither = FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError as e: raise ValueError("illegal conversion") from e new_im = self._new(im) if mode == "P" and 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=1): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`MEDIANCUT` (median cut), :data:`MAXCOVERAGE` (maximum coverage), :data:`FASTOCTREE` (fast octree), :data:`LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`MEDIANCUT` will be used. The exception to this is RGBA images. :data:`MEDIANCUT` and :data:`MAXCOVERAGE` do not support RGBA images, so :data:`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:`NONE` or :data:`FLOYDSTEINBERG` (default). Default: 1 (legacy setting) :returns: A new image """ self.load() if method is None: # defaults: method = MEDIANCUT if self.mode == "RGBA": method = FASTOCTREE if self.mode == "RGBA" and method not in (FASTOCTREE, LIBIMAGEQUANT): # Caller specified an invalid mode. raise ValueError( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) 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() 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. """ 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"): raise TypeError( "filter argument should be ImageFilter.Filter instance or class" ) 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 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): if self._exif is None: self._exif = Exif() 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.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[1]) return self._exif 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): """ Returns the image palette as a list. :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: return list(self.im.getpalette()) except ValueError: return None # no palette 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. 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" or "RGBA" images (in the latter case, 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? raise ValueError("cannot determine region size; use 4-item box") 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 ("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)): raise ValueError("Source must be a tuple") if not isinstance(dest, (list, tuple)): raise ValueError("Destination must be a tuple") if not len(source) in (2, 4): raise ValueError("Source must be a 2 or 4-tuple") if not len(dest) == 2: raise ValueError("Destination must be a 2-tuple") if min(source) < 0: raise ValueError("Source must be non-negative") 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 raise ValueError("point operation not supported for this mode") 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: raise ValueError("illegal image mode") 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"): raise ValueError("illegal image mode") 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" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): raise ValueError("illegal image mode") 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 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 == "P" and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P image value = self.palette.getcolor(value, self) 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"): raise ValueError("illegal image mode") if source_palette is None: if self.mode == "P": self.load() source_palette = self.im.getpalette("RGB")[:768] 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 * 3 : oldPosition * 3 + 3] 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("RGB", palette=mapping_palette * 3) # 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("RGB;L", m_im.palette.tobytes()) m_im = m_im.convert("L") # Internally, we require 768 bytes for a palette. new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b"\x00" m_im.putpalette(new_palette_bytes) m_im.palette = ImagePalette.ImagePalette("RGB", palette=palette_bytes) 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:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`PIL.Image.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`PIL.Image.NEAREST`. Otherwise, the default filter is :py:data:`PIL.Image.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 = NEAREST if type_special else BICUBIC elif resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING): message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (LANCZOS, "Image.LANCZOS"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), (BOX, "Image.BOX"), (HAMMING, "Image.HAMMING"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) if reducing_gap is not None and reducing_gap < 1.0: raise ValueError("reducing_gap must be 1.0 or greater") size = tuple(size) 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 = NEAREST if self.mode in ["LA", "RGBA"] and resample != 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 != 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=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:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.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:`PIL.Image.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(ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose(ROTATE_90 if angle == 90 else 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), 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 isPath(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 isPath(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: raise ValueError(f"unknown file extension: {ext}") from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] if open_fp: 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) finally: # do what we can to clean up 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: raise ValueError(f'The image has no channel "{channel}"') 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=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: Requested size. :param resample: Optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If omitted, it defaults to :py:data:`PIL.Image.BICUBIC`. (was :py:data:`PIL.Image.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 """ x, y = map(math.floor, size) if x >= self.width and y >= self.height: return def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) # preserve aspect ratio 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) ) size = (x, y) box = None if reducing_gap is not None: res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] 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=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. :param method: The transformation method. This is one of :py:data:`PIL.Image.EXTENT` (cut out a rectangular subregion), :py:data:`PIL.Image.AFFINE` (affine transform), :py:data:`PIL.Image.PERSPECTIVE` (perspective transform), :py:data:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or :py:data:`PIL.Image.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.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:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.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:`PIL.Image.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 != 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: raise ValueError("missing method data") 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 == MESH: # list of quads for box, quad in data: im.__transformer(box, self, 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=NEAREST, fill=1): w = box[2] - box[0] h = box[3] - box[1] if method == AFFINE: data = data[0:6] elif method == EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == PERSPECTIVE: data = data[0:8] elif method == QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[0: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: raise ValueError("unknown transformation method") if resample not in (NEAREST, BILINEAR, BICUBIC): if resample in (BOX, HAMMING, LANCZOS): message = { BOX: "Image.BOX", HAMMING: "Image.HAMMING", LANCZOS: "Image.LANCZOS/Image.ANTIALIAS", }[resample] + f" ({resample}) cannot be used." else: message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) image.load() self.load() if image.mode in ("1", "P"): resample = 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:`PIL.Image.FLIP_LEFT_RIGHT`, :py:data:`PIL.Image.FLIP_TOP_BOTTOM`, :py:data:`PIL.Image.ROTATE_90`, :py:data:`PIL.Image.ROTATE_180`, :py:data:`PIL.Image.ROTATE_270`, :py:data:`PIL.Image.TRANSPOSE` or :py:data:`PIL.Image.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: raise ImportError("Qt bindings are not installed") return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") 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: raise NotImplementedError("ImageGrab.grabclipboard() is macOS and Windows only")
null
167,682
import io from . import FontFile, Image from ._binary import i8 from ._binary import i16be as b16 from ._binary import i16le as l16 from ._binary import i32be as b32 from ._binary import i32le as l32 def sz(s, o): return s[o : s.index(b"\0", o)]
null
167,683
import os import re from . import Image, ImageFile, ImagePalette def number(s): try: return int(s) except ValueError: return float(s)
null
167,684
import os import re from . import Image, ImageFile, ImagePalette 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 isPath(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: raise SyntaxError("not identified by this driver") 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 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: raise OSError("cannot load this image") 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) 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: decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: seek(offset) decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) status, err_code = decoder.decode(b"") 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: raise OSError("image file is truncated") from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: raise OSError( "image file is truncated " f"({len(b)} bytes not processed)" ) 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 ) ): raise EOFError("attempt to seek outside sequence") return self.tell() != frame def _save(im, fp, filename): try: image_type, rawmode = SAVE[im.mode] except KeyError as e: raise ValueError(f"Cannot save {im.mode} images as IM") 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"]: fp.write(im.im.getpalette("RGB", "RGB;L")) # 768 bytes ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))])
null
167,685
import os from . import Image, _binary The provided code snippet includes necessary dependencies for implementing the `puti16` function. Write a Python function `def puti16(fp, values)` to solve the following problem: Write network order (big-endian) 16-bit sequence Here is the function: def puti16(fp, values): """Write network order (big-endian) 16-bit sequence""" for v in values: if v < 0: v += 65536 fp.write(_binary.o16be(v))
Write network order (big-endian) 16-bit sequence
167,686
from math import log, pi, sin, sqrt from ._binary import o8 EPSILON = 1e-10 def curved(middle, pos): return pos ** (log(0.5) / log(max(middle, EPSILON)))
null
167,687
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 sine(middle, pos): return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0
null
167,688
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 sphere_increasing(middle, pos): return sqrt(1.0 - (linear(middle, pos) - 1.0) ** 2)
null
167,689
from math import log, pi, sin, sqrt from ._binary import o8 def linear(middle, pos): def sphere_decreasing(middle, pos): return 1.0 - sqrt(1.0 - linear(middle, pos) ** 2)
null
167,690
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
167,691
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
167,692
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: raise OSError(f"cannot write mode {im.mode} as BMP") 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] # bitmap header if bitmap_header: offset = 14 + header + colors * 4 file_size = offset + image if file_size > 2 ** 32 - 1: raise ValueError("File size is too large for the BMP format") 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 im.mode == "1": for i in (0, 255): fp.write(o8(i) * 4) elif im.mode == "L": for i in range(256): fp.write(o8(i) * 4) elif im.mode == "P": fp.write(im.im.getpalette("RGB", "BGRX")) 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
167,693
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]
null
167,694
import struct 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 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 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_png_(self): def __init__(self, new): def __array__(self, dtype=None): 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=WEB, colors=256): def convert_transparency(m, v): def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1): 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 getim(self): def getpalette(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=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=BICUBIC, reducing_gap=2.0): def round_aspect(number, key): def transform( self, size, method, data=None, resample=NEAREST, fill=1, fillcolor=None ): def __transformer(self, box, image, method, data, resample=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 verify(self): def load(self): def load_prepare(self): def load_end(self): def _seek_check(self, frame): def _save(im, fp, filename): fp.write(_MAGIC) # (2+2) sizes = im.encoderinfo.get( "sizes", [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)], ) width, height = im.size sizes = filter( lambda x: False if (x[0] > width or x[1] > height or x[0] > 256 or x[1] > 256) else True, sizes, ) sizes = list(sizes) fp.write(struct.pack("<H", len(sizes))) # idCount(2) offset = fp.tell() + len(sizes) * 16 bmp = im.encoderinfo.get("bitmap_format") == "bmp" provided_images = {im.size: im for im in im.encoderinfo.get("append_images", [])} for size in sizes: width, height = size # 0 means 256 fp.write(struct.pack("B", width if width < 256 else 0)) # bWidth(1) fp.write(struct.pack("B", height if height < 256 else 0)) # bHeight(1) fp.write(b"\0") # bColorCount(1) fp.write(b"\0") # bReserved(1) fp.write(b"\0\0") # wPlanes(2) tmp = provided_images.get(size) if not tmp: # TODO: invent a more convenient method for proportional scalings tmp = im.copy() tmp.thumbnail(size, Image.LANCZOS, reducing_gap=None) bits = BmpImagePlugin.SAVE[tmp.mode][1] if bmp else 32 fp.write(struct.pack("<H", bits)) # wBitCount(2) image_io = BytesIO() if bmp: tmp.save(image_io, "dib") if bits != 32: and_mask = Image.new("1", tmp.size) ImageFile._save( and_mask, image_io, [("raw", (0, 0) + tmp.size, 0, ("1", 0, -1))] ) else: tmp.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(struct.pack("<I", bytes_len)) # dwBytesInRes(4) fp.write(struct.pack("<I", offset)) # dwImageOffset(4) current = fp.tell() fp.seek(offset) fp.write(image_bytes) offset = offset + bytes_len fp.seek(current)
null
167,695
import struct 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 o32le as o32 _MAGIC = b"\0\0\1\0" def _accept(prefix): return prefix[:4] == _MAGIC
null
167,696
import array import warnings from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile 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. :param size: An optional palette size. If given, an error is raised if ``palette`` is not of equal length. """ 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: warnings.warn( "The size parameter is deprecated and will be removed in Pillow 10 " "(2023-07-01).", DeprecationWarning, ) if size != len(self.palette): raise ValueError("wrong palette size") def palette(self): return self._palette def palette(self, palette): self._palette = palette 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 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: raise ValueError("palette contains raw palette data") 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: raise ValueError("palette contains raw palette data") if isinstance(color, tuple): if self.mode == "RGB": if len(color) == 4 and color[3] == 255: 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: raise ValueError("cannot allocate more than 256 colors") 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: raise ValueError(f"unknown color specifier: {repr(color)}") def save(self, fp): """Save palette to text file. .. warning:: This method is experimental. """ if self.rawmode: raise ValueError("palette contains raw palette data") 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
167,697
import array import warnings from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile 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
167,698
import array import warnings from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile 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. :param size: An optional palette size. If given, an error is raised if ``palette`` is not of equal length. """ 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: warnings.warn( "The size parameter is deprecated and will be removed in Pillow 10 " "(2023-07-01).", DeprecationWarning, ) if size != len(self.palette): raise ValueError("wrong palette size") def palette(self): return self._palette def palette(self, palette): self._palette = palette 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 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: raise ValueError("palette contains raw palette data") 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: raise ValueError("palette contains raw palette data") if isinstance(color, tuple): if self.mode == "RGB": if len(color) == 4 and color[3] == 255: 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: raise ValueError("cannot allocate more than 256 colors") 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: raise ValueError(f"unknown color specifier: {repr(color)}") def save(self, fp): """Save palette to text file. .. warning:: This method is experimental. """ if self.rawmode: raise ValueError("palette contains raw palette data") 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
167,699
import array import warnings from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile 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. :param size: An optional palette size. If given, an error is raised if ``palette`` is not of equal length. """ 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: warnings.warn( "The size parameter is deprecated and will be removed in Pillow 10 " "(2023-07-01).", DeprecationWarning, ) if size != len(self.palette): raise ValueError("wrong palette size") def palette(self): return self._palette def palette(self, palette): self._palette = palette 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 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: raise ValueError("palette contains raw palette data") 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: raise ValueError("palette contains raw palette data") if isinstance(color, tuple): if self.mode == "RGB": if len(color) == 4 and color[3] == 255: 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: raise ValueError("cannot allocate more than 256 colors") 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: raise ValueError(f"unknown color specifier: {repr(color)}") def save(self, fp): """Save palette to text file. .. warning:: This method is experimental. """ if self.rawmode: raise ValueError("palette contains raw palette data") 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 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
167,700
import array import warnings from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile 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. :param size: An optional palette size. If given, an error is raised if ``palette`` is not of equal length. """ 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: warnings.warn( "The size parameter is deprecated and will be removed in Pillow 10 " "(2023-07-01).", DeprecationWarning, ) if size != len(self.palette): raise ValueError("wrong palette size") def palette(self): return self._palette def palette(self, palette): self._palette = palette 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 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: raise ValueError("palette contains raw palette data") 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: raise ValueError("palette contains raw palette data") if isinstance(color, tuple): if self.mode == "RGB": if len(color) == 4 and color[3] == 255: 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: raise ValueError("cannot allocate more than 256 colors") 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: raise ValueError(f"unknown color specifier: {repr(color)}") def save(self, fp): """Save palette to text file. .. warning:: This method is experimental. """ if self.rawmode: raise ValueError("palette contains raw palette data") 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
167,701
from . import Image, ImageFile _handler = None 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
Install application-specific FITS image handler. :param handler: Handler object.
167,702
from . import Image, ImageFile def _accept(prefix): return prefix[:6] == b"SIMPLE"
null
167,703
from . import Image, ImageFile _handler = None def _save(im, fp, filename): if _handler is None or not hasattr("_handler", "save"): raise OSError("FITS save handler not installed") _handler.save(im, fp, filename)
null
167,704
from . import BmpImagePlugin, Image from ._binary import i16le as i16 from ._binary import i32le as i32 def _accept(prefix): return prefix[:4] == b"\0\0\2\0"
null
167,705
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_RGB = 0x40 DDS_RGBA = DDPF_RGB | DDPF_ALPHAPIXELS Image.register_open(DdsImageFile.format, DdsImageFile, _accept) Image.register_save(DdsImageFile.format, _save) Image.register_extension(DdsImageFile.format, ".dds") 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": warnings.warn( "Image categories are deprecated and will be removed in Pillow 10 " "(2023-07-01). Use is_animated instead.", DeprecationWarning, stacklevel=2, ) 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 hasattr(self, "_close__fp"): self._close__fp() 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 hasattr(self, "_close__fp"): self._close__fp() 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 = deferred_error(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.readonly == other.readonly 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_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: raise ValueError("Could not save to PNG for display") from e return b.getvalue() class _ArrayData: def __init__(self, new): self.__array_interface__ = new def __array__(self, dtype=None): # numpy array interface support import numpy as np new = {} shape, typestr = _conv_type_shape(self) new["shape"] = shape new["typestr"] = typestr new["version"] = 3 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() return np.array(self._ArrayData(new), dtype) def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) self.tile = [] 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. :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() # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c data = [] while True: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError(f"encoder error {s} in tobytes") return b"".join(data) 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": raise ValueError("not a bitmap") 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: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data") 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 and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() if mode == "RGBA": mode = "RGB" self.info["transparency"] = arr[3::4] arr = bytes( value for (index, value) in enumerate(arr) if index % 4 != 3 ) palette_length = 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: self.palette.mode = "RGB" self.palette.palette = self.im.getpalette()[: palette_length * 3] if self.im: 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=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 :data:`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. :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:`NONE` or :data:`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:`WEB` or :data:`ADAPTIVE`. :param colors: Number of colors to use for the :data:`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"): raise ValueError("illegal conversion") 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", "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: raise ValueError("Transparency for P mode should be bytes or int") if mode == "P" and 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 # colorspace conversion if dither is None: dither = FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError as e: raise ValueError("illegal conversion") from e new_im = self._new(im) if mode == "P" and 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=1): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`MEDIANCUT` (median cut), :data:`MAXCOVERAGE` (maximum coverage), :data:`FASTOCTREE` (fast octree), :data:`LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`MEDIANCUT` will be used. The exception to this is RGBA images. :data:`MEDIANCUT` and :data:`MAXCOVERAGE` do not support RGBA images, so :data:`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:`NONE` or :data:`FLOYDSTEINBERG` (default). Default: 1 (legacy setting) :returns: A new image """ self.load() if method is None: # defaults: method = MEDIANCUT if self.mode == "RGBA": method = FASTOCTREE if self.mode == "RGBA" and method not in (FASTOCTREE, LIBIMAGEQUANT): # Caller specified an invalid mode. raise ValueError( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) 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() 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. """ 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"): raise TypeError( "filter argument should be ImageFilter.Filter instance or class" ) 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 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): if self._exif is None: self._exif = Exif() 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.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[1]) return self._exif 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): """ Returns the image palette as a list. :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: return list(self.im.getpalette()) except ValueError: return None # no palette 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. 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" or "RGBA" images (in the latter case, 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? raise ValueError("cannot determine region size; use 4-item box") 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 ("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)): raise ValueError("Source must be a tuple") if not isinstance(dest, (list, tuple)): raise ValueError("Destination must be a tuple") if not len(source) in (2, 4): raise ValueError("Source must be a 2 or 4-tuple") if not len(dest) == 2: raise ValueError("Destination must be a 2-tuple") if min(source) < 0: raise ValueError("Source must be non-negative") 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 raise ValueError("point operation not supported for this mode") 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: raise ValueError("illegal image mode") 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"): raise ValueError("illegal image mode") 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" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): raise ValueError("illegal image mode") 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 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 == "P" and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P image value = self.palette.getcolor(value, self) 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"): raise ValueError("illegal image mode") if source_palette is None: if self.mode == "P": self.load() source_palette = self.im.getpalette("RGB")[:768] 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 * 3 : oldPosition * 3 + 3] 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("RGB", palette=mapping_palette * 3) # 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("RGB;L", m_im.palette.tobytes()) m_im = m_im.convert("L") # Internally, we require 768 bytes for a palette. new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b"\x00" m_im.putpalette(new_palette_bytes) m_im.palette = ImagePalette.ImagePalette("RGB", palette=palette_bytes) 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:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`PIL.Image.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`PIL.Image.NEAREST`. Otherwise, the default filter is :py:data:`PIL.Image.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 = NEAREST if type_special else BICUBIC elif resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING): message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (LANCZOS, "Image.LANCZOS"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), (BOX, "Image.BOX"), (HAMMING, "Image.HAMMING"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) if reducing_gap is not None and reducing_gap < 1.0: raise ValueError("reducing_gap must be 1.0 or greater") size = tuple(size) 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 = NEAREST if self.mode in ["LA", "RGBA"] and resample != 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 != 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=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:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.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:`PIL.Image.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(ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose(ROTATE_90 if angle == 90 else 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), 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 isPath(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 isPath(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: raise ValueError(f"unknown file extension: {ext}") from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] if open_fp: 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) finally: # do what we can to clean up 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: raise ValueError(f'The image has no channel "{channel}"') 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=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: Requested size. :param resample: Optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If omitted, it defaults to :py:data:`PIL.Image.BICUBIC`. (was :py:data:`PIL.Image.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 """ x, y = map(math.floor, size) if x >= self.width and y >= self.height: return def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) # preserve aspect ratio 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) ) size = (x, y) box = None if reducing_gap is not None: res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] 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=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. :param method: The transformation method. This is one of :py:data:`PIL.Image.EXTENT` (cut out a rectangular subregion), :py:data:`PIL.Image.AFFINE` (affine transform), :py:data:`PIL.Image.PERSPECTIVE` (perspective transform), :py:data:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or :py:data:`PIL.Image.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.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:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.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:`PIL.Image.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 != 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: raise ValueError("missing method data") 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 == MESH: # list of quads for box, quad in data: im.__transformer(box, self, 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=NEAREST, fill=1): w = box[2] - box[0] h = box[3] - box[1] if method == AFFINE: data = data[0:6] elif method == EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == PERSPECTIVE: data = data[0:8] elif method == QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[0: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: raise ValueError("unknown transformation method") if resample not in (NEAREST, BILINEAR, BICUBIC): if resample in (BOX, HAMMING, LANCZOS): message = { BOX: "Image.BOX", HAMMING: "Image.HAMMING", LANCZOS: "Image.LANCZOS/Image.ANTIALIAS", }[resample] + f" ({resample}) cannot be used." else: message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) image.load() self.load() if image.mode in ("1", "P"): resample = 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:`PIL.Image.FLIP_LEFT_RIGHT`, :py:data:`PIL.Image.FLIP_TOP_BOTTOM`, :py:data:`PIL.Image.ROTATE_90`, :py:data:`PIL.Image.ROTATE_180`, :py:data:`PIL.Image.ROTATE_270`, :py:data:`PIL.Image.TRANSPOSE` or :py:data:`PIL.Image.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: raise ImportError("Qt bindings are not installed") return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") 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 isPath(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: raise SyntaxError("not identified by this driver") 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 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: raise OSError("cannot load this image") 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) 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: decoder = Image._getdecoder( self.mode, decoder_name, args, self.decoderconfig ) try: seek(offset) decoder.setimage(self.im, extents) if decoder.pulls_fd: decoder.setfd(self.fp) status, err_code = decoder.decode(b"") 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: raise OSError("image file is truncated") from e if not s: # truncated jpeg if LOAD_TRUNCATED_IMAGES: break else: raise OSError( "image file is truncated " f"({len(b)} bytes not processed)" ) 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 ) ): raise EOFError("attempt to seek outside sequence") return self.tell() != frame def _save(im, fp, filename): if im.mode not in ("RGB", "RGBA"): raise OSError(f"cannot write mode {im.mode} as DDS") 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 * (32 if im.mode == "RGBA" else 24) + 7) // 8) # pitch + o32(0) # depth + o32(0) # mipmaps + o32(0) * 11 # reserved + o32(32) # pfsize + o32(DDS_RGBA if im.mode == "RGBA" else DDPF_RGB) # pfflags + o32(0) # fourcc + o32(32 if im.mode == "RGBA" else 24) # bitcount + o32(0xFF0000) # rbitmask + o32(0xFF00) # gbitmask + o32(0xFF) # bbitmask + o32(0xFF000000 if im.mode == "RGBA" else 0) # abitmask + 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, (im.mode[::-1], 0, 1))])
null
167,706
import struct from io import BytesIO from . import Image, ImageFile from ._binary import o32le as o32 def _accept(prefix): return prefix[:4] == b"DDS "
null
167,707
import os import shutil import subprocess import sys from shlex import quote from PIL import Image _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, file, **options): """Display given file""" os.system(self.get_command(file, **options)) return 1 def _remove_file_after_delay(self, file): subprocess.Popen( [ sys.executable, "-c", "import os, sys, time; time.sleep(20); os.remove(sys.argv[1])", file, ] ) 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. :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. :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. :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.
167,708
from . import Image, ImageFile, JpegImagePlugin from ._binary import i16be as i16 def _save(im, fp, filename): # Note that we can only save the current frame at present return JpegImagePlugin._save(im, fp, filename)
null
167,709
import io import os import struct from . import Image, ImageFile 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 = struct.unpack(">H", hdr)[0] 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.
167,710
import io import os import struct from . import Image, ImageFile 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): raise SyntaxError("Not enough data in header") data = self.fp.read(num_bytes) if len(data) < num_bytes: raise OSError( f"Expected to read {num_bytes} bytes but only got {len(data)}." ) 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): raise SyntaxError("Invalid header length") 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: raise SyntaxError("Malformed JP2 header") 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.
167,711
import io import os import struct from . import Image, ImageFile def _accept(prefix): return ( prefix[:4] == b"\xff\x4f\xff\x51" or prefix[:12] == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a" )
null
167,712
import io import os import struct from . import Image, ImageFile class ImageFile(Image.Image): def __init__(self, fp=None, filename=None): def get_format_mimetype(self): 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 filename.endswith(".j2k"): kind = "j2k" else: kind = "jp2" # Get the keyword arguments info = im.encoderinfo 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 ] ) ): raise ValueError("quality_layers must be a sequence of numbers") 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") 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, fd, ) ImageFile._save(im, fp, [("jpeg2k", (0, 0) + im.size, 0, kind)])
null
167,713
import io from . import Image, ImageFile, ImagePalette from ._binary import i8 from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import si16be as si16 def _accept(prefix): return prefix[:4] == b"8BPS"
null
167,714
import io from . import Image, ImageFile, ImagePalette from ._binary import i8 from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import si16be as si16 def _maketile(file, mode, bbox, channels): class ImageFile(Image.Image): def __init__(self, fp=None, filename=None): def get_format_mimetype(self): def verify(self): def load(self): def load_prepare(self): def load_end(self): def _seek_check(self, frame): def i8(c): def _layerinfo(fp, ct_bytes): # read layerinfo block layers = [] def read(size): return ImageFile._safe_read(fp, size) ct = si16(read(2)) # sanity check if ct_bytes < (abs(ct) * 20): raise SyntaxError("Layer block too short for number of layers requested") for i in range(abs(ct)): # bounding box y0 = i32(read(4)) x0 = i32(read(4)) y1 = i32(read(4)) x1 = i32(read(4)) # image info info = [] mode = [] ct_types = i16(read(2)) types = list(range(ct_types)) if len(types) > 4: continue for i in types: type = i16(read(2)) if type == 65535: m = "A" else: m = "RGBA"[type] mode.append(m) size = i32(read(4)) info.append((m, size)) # figure out the image mode mode.sort() if mode == ["R"]: mode = "L" elif mode == ["B", "G", "R"]: mode = "RGB" elif mode == ["A", "B", "G", "R"]: mode = "RGBA" else: mode = None # unknown # skip over blend flags and extra information read(12) # filler name = "" size = i32(read(4)) # length of the extra data field combined = 0 if size: data_end = fp.tell() + size length = i32(read(4)) if length: fp.seek(length - 16, io.SEEK_CUR) combined += length + 4 length = i32(read(4)) if length: fp.seek(length, io.SEEK_CUR) combined += length + 4 length = i8(read(1)) if length: # Don't know the proper encoding, # Latin-1 should be a good guess name = read(length).decode("latin-1", "replace") combined += length + 1 fp.seek(data_end) layers.append((name, mode, (x0, y0, x1, y1))) # get tiles i = 0 for name, mode, bbox in layers: tile = [] for m in mode: t = _maketile(fp, m, bbox, 1) if t: tile.extend(t) layers[i] = name, mode, bbox, tile i += 1 return layers
null
167,715
import base64 import os import sys from io import BytesIO from . import Image from ._util import isDirectory, isPath class FreeTypeFont: "FreeType font wrapper (requires _imagingft service)" def __init__(self, font=None, size=10, index=0, encoding="", layout_engine=None): # FIXME: use service provider instead self.path = font self.size = size self.index = index self.encoding = encoding if layout_engine not in (LAYOUT_BASIC, LAYOUT_RAQM): layout_engine = LAYOUT_BASIC if core.HAVE_RAQM: layout_engine = LAYOUT_RAQM elif layout_engine == LAYOUT_RAQM and not core.HAVE_RAQM: layout_engine = LAYOUT_BASIC self.layout_engine = layout_engine def load_from_bytes(f): self.font_bytes = f.read() self.font = core.getfont( "", size, index, encoding, self.font_bytes, layout_engine ) if isPath(font): if sys.platform == "win32": font_bytes_path = font if isinstance(font, bytes) else font.encode() try: font_bytes_path.decode("ascii") except UnicodeDecodeError: # FreeType cannot load fonts with non-ASCII characters on Windows # So load it into memory first with open(font, "rb") as f: load_from_bytes(f) return self.font = core.getfont( font, size, index, encoding, layout_engine=layout_engine ) else: load_from_bytes(font) def __getstate__(self): return [self.path, self.size, self.index, self.encoding, self.layout_engine] def __setstate__(self, state): path, size, index, encoding, layout_engine = state self.__init__(path, size, index, encoding, layout_engine) def _multiline_split(self, text): split_character = "\n" if isinstance(text, str) else b"\n" return text.split(split_character) def getname(self): """ :return: A tuple of the font family (e.g. Helvetica) and the font style (e.g. Bold) """ return self.font.family, self.font.style def getmetrics(self): """ :return: A tuple of the font ascent (the distance from the baseline to the highest outline point) and descent (the distance from the baseline to the lowest outline point, a negative value) """ return self.font.ascent, self.font.descent def getlength(self, text, mode="", direction=None, features=None, language=None): """ Returns length (in pixels with 1/64 precision) of given text when rendered in font with provided direction, features, and language. This is the amount by which following text should be offset. Text bounding box may extend past the length in some fonts, e.g. when using italics or accents. The result is returned as a float; it is a whole number if using basic layout. Note that the sum of two lengths may not equal the length of a concatenated string due to kerning. If you need to adjust for kerning, include the following character and subtract its length. For example, instead of .. code-block:: python hello = font.getlength("Hello") world = font.getlength("World") hello_world = hello + world # not adjusted for kerning assert hello_world == font.getlength("HelloWorld") # may fail use .. code-block:: python hello = font.getlength("HelloW") - font.getlength("W") # adjusted for kerning world = font.getlength("World") hello_world = hello + world # adjusted for kerning assert hello_world == font.getlength("HelloWorld") # True or disable kerning with (requires libraqm) .. code-block:: python hello = draw.textlength("Hello", font, features=["-kern"]) world = draw.textlength("World", font, features=["-kern"]) hello_world = hello + world # kerning is disabled, no need to adjust assert hello_world == draw.textlength("HelloWorld", font, features=["-kern"]) .. versionadded:: 8.0.0 :param text: Text to measure. :param mode: Used by some graphics drivers to indicate what mode the driver prefers; if empty, the renderer may return either mode. Note that the mode is always a string, to simplify C-level implementations. :param direction: Direction of the text. It can be 'rtl' (right to left), 'ltr' (left to right) or 'ttb' (top to bottom). Requires libraqm. :param features: A list of OpenType font features to be used during text layout. This is usually used to turn on optional font features that are not enabled by default, for example 'dlig' or 'ss01', but can be also used to turn off default font features for example '-liga' to disable ligatures or '-kern' to disable kerning. To get all supported features, see https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm. :param language: Language of the text. Different languages may use different glyph shapes or ligatures. This parameter tells the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a `BCP 47 language code <https://www.w3.org/International/articles/language-tags/>`_ Requires libraqm. :return: Width for horizontal, height for vertical text. """ return self.font.getlength(text, mode, direction, features, language) / 64 def getbbox( self, text, mode="", direction=None, features=None, language=None, stroke_width=0, anchor=None, ): """ Returns bounding box (in pixels) of given text relative to given anchor when rendered in font with provided direction, features, and language. Use :py:meth:`getlength()` to get the offset of following text with 1/64 pixel precision. The bounding box includes extra margins for some fonts, e.g. italics or accents. .. versionadded:: 8.0.0 :param text: Text to render. :param mode: Used by some graphics drivers to indicate what mode the driver prefers; if empty, the renderer may return either mode. Note that the mode is always a string, to simplify C-level implementations. :param direction: Direction of the text. It can be 'rtl' (right to left), 'ltr' (left to right) or 'ttb' (top to bottom). Requires libraqm. :param features: A list of OpenType font features to be used during text layout. This is usually used to turn on optional font features that are not enabled by default, for example 'dlig' or 'ss01', but can be also used to turn off default font features for example '-liga' to disable ligatures or '-kern' to disable kerning. To get all supported features, see https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm. :param language: Language of the text. Different languages may use different glyph shapes or ligatures. This parameter tells the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a `BCP 47 language code <https://www.w3.org/International/articles/language-tags/>`_ Requires libraqm. :param stroke_width: The width of the text stroke. :param anchor: The text anchor alignment. Determines the relative location of the anchor to the text. The default alignment is top left. See :ref:`text-anchors` for valid values. :return: ``(left, top, right, bottom)`` bounding box """ size, offset = self.font.getsize( text, mode, direction, features, language, anchor ) left, top = offset[0] - stroke_width, offset[1] - stroke_width width, height = size[0] + 2 * stroke_width, size[1] + 2 * stroke_width return left, top, left + width, top + height def getsize( self, text, direction=None, features=None, language=None, stroke_width=0 ): """ Returns width and height (in pixels) of given text if rendered in font with provided direction, features, and language. Use :py:meth:`getlength()` to measure the offset of following text with 1/64 pixel precision. Use :py:meth:`getbbox()` to get the exact bounding box based on an anchor. .. note:: For historical reasons this function measures text height from the ascender line instead of the top, see :ref:`text-anchors`. If you wish to measure text height from the top, it is recommended to use the bottom value of :meth:`getbbox` with ``anchor='lt'`` instead. :param text: Text to measure. :param direction: Direction of the text. It can be 'rtl' (right to left), 'ltr' (left to right) or 'ttb' (top to bottom). Requires libraqm. .. versionadded:: 4.2.0 :param features: A list of OpenType font features to be used during text layout. This is usually used to turn on optional font features that are not enabled by default, for example 'dlig' or 'ss01', but can be also used to turn off default font features for example '-liga' to disable ligatures or '-kern' to disable kerning. To get all supported features, see https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm. .. versionadded:: 4.2.0 :param language: Language of the text. Different languages may use different glyph shapes or ligatures. This parameter tells the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a `BCP 47 language code <https://www.w3.org/International/articles/language-tags/>`_ Requires libraqm. .. versionadded:: 6.0.0 :param stroke_width: The width of the text stroke. .. versionadded:: 6.2.0 :return: (width, height) """ # vertical offset is added for historical reasons # see https://github.com/python-pillow/Pillow/pull/4910#discussion_r486682929 size, offset = self.font.getsize(text, "L", direction, features, language) return ( size[0] + stroke_width * 2, size[1] + stroke_width * 2 + offset[1], ) def getsize_multiline( self, text, direction=None, spacing=4, features=None, language=None, stroke_width=0, ): """ Returns width and height (in pixels) of given text if rendered in font with provided direction, features, and language, while respecting newline characters. :param text: Text to measure. :param direction: Direction of the text. It can be 'rtl' (right to left), 'ltr' (left to right) or 'ttb' (top to bottom). Requires libraqm. :param spacing: The vertical gap between lines, defaulting to 4 pixels. :param features: A list of OpenType font features to be used during text layout. This is usually used to turn on optional font features that are not enabled by default, for example 'dlig' or 'ss01', but can be also used to turn off default font features for example '-liga' to disable ligatures or '-kern' to disable kerning. To get all supported features, see https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm. :param language: Language of the text. Different languages may use different glyph shapes or ligatures. This parameter tells the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a `BCP 47 language code <https://www.w3.org/International/articles/language-tags/>`_ Requires libraqm. .. versionadded:: 6.0.0 :param stroke_width: The width of the text stroke. .. versionadded:: 6.2.0 :return: (width, height) """ max_width = 0 lines = self._multiline_split(text) line_spacing = self.getsize("A", stroke_width=stroke_width)[1] + spacing for line in lines: line_width, line_height = self.getsize( line, direction, features, language, stroke_width ) max_width = max(max_width, line_width) return max_width, len(lines) * line_spacing - spacing def getoffset(self, text): """ Returns the offset of given text. This is the gap between the starting coordinate and the first marking. Note that this gap is included in the result of :py:func:`~PIL.ImageFont.FreeTypeFont.getsize`. :param text: Text to measure. :return: A tuple of the x and y offset """ return self.font.getsize(text)[1] def getmask( self, text, mode="", direction=None, features=None, language=None, stroke_width=0, anchor=None, ink=0, ): """ Create a bitmap for the text. If the font uses antialiasing, the bitmap should have mode ``L`` and use a maximum value of 255. If the font has embedded color data, the bitmap should have mode ``RGBA``. Otherwise, it should have mode ``1``. :param text: Text to render. :param mode: Used by some graphics drivers to indicate what mode the driver prefers; if empty, the renderer may return either mode. Note that the mode is always a string, to simplify C-level implementations. .. versionadded:: 1.1.5 :param direction: Direction of the text. It can be 'rtl' (right to left), 'ltr' (left to right) or 'ttb' (top to bottom). Requires libraqm. .. versionadded:: 4.2.0 :param features: A list of OpenType font features to be used during text layout. This is usually used to turn on optional font features that are not enabled by default, for example 'dlig' or 'ss01', but can be also used to turn off default font features for example '-liga' to disable ligatures or '-kern' to disable kerning. To get all supported features, see https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm. .. versionadded:: 4.2.0 :param language: Language of the text. Different languages may use different glyph shapes or ligatures. This parameter tells the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a `BCP 47 language code <https://www.w3.org/International/articles/language-tags/>`_ Requires libraqm. .. versionadded:: 6.0.0 :param stroke_width: The width of the text stroke. .. versionadded:: 6.2.0 :param anchor: The text anchor alignment. Determines the relative location of the anchor to the text. The default alignment is top left. See :ref:`text-anchors` for valid values. .. versionadded:: 8.0.0 :param ink: Foreground ink for rendering in RGBA mode. .. versionadded:: 8.0.0 :return: An internal PIL storage memory instance as defined by the :py:mod:`PIL.Image.core` interface module. """ return self.getmask2( text, mode, direction=direction, features=features, language=language, stroke_width=stroke_width, anchor=anchor, ink=ink, )[0] def getmask2( self, text, mode="", fill=Image.core.fill, direction=None, features=None, language=None, stroke_width=0, anchor=None, ink=0, *args, **kwargs, ): """ Create a bitmap for the text. If the font uses antialiasing, the bitmap should have mode ``L`` and use a maximum value of 255. If the font has embedded color data, the bitmap should have mode ``RGBA``. Otherwise, it should have mode ``1``. :param text: Text to render. :param mode: Used by some graphics drivers to indicate what mode the driver prefers; if empty, the renderer may return either mode. Note that the mode is always a string, to simplify C-level implementations. .. versionadded:: 1.1.5 :param direction: Direction of the text. It can be 'rtl' (right to left), 'ltr' (left to right) or 'ttb' (top to bottom). Requires libraqm. .. versionadded:: 4.2.0 :param features: A list of OpenType font features to be used during text layout. This is usually used to turn on optional font features that are not enabled by default, for example 'dlig' or 'ss01', but can be also used to turn off default font features for example '-liga' to disable ligatures or '-kern' to disable kerning. To get all supported features, see https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm. .. versionadded:: 4.2.0 :param language: Language of the text. Different languages may use different glyph shapes or ligatures. This parameter tells the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a `BCP 47 language code <https://www.w3.org/International/articles/language-tags/>`_ Requires libraqm. .. versionadded:: 6.0.0 :param stroke_width: The width of the text stroke. .. versionadded:: 6.2.0 :param anchor: The text anchor alignment. Determines the relative location of the anchor to the text. The default alignment is top left. See :ref:`text-anchors` for valid values. .. versionadded:: 8.0.0 :param ink: Foreground ink for rendering in RGBA mode. .. versionadded:: 8.0.0 :return: A tuple of an internal PIL storage memory instance as defined by the :py:mod:`PIL.Image.core` interface module, and the text offset, the gap between the starting coordinate and the first marking """ size, offset = self.font.getsize( text, mode, direction, features, language, anchor ) size = size[0] + stroke_width * 2, size[1] + stroke_width * 2 offset = offset[0] - stroke_width, offset[1] - stroke_width Image._decompression_bomb_check(size) im = fill("RGBA" if mode == "RGBA" else "L", size, 0) self.font.render( text, im.id, mode, direction, features, language, stroke_width, ink ) return im, offset def font_variant( self, font=None, size=None, index=None, encoding=None, layout_engine=None ): """ Create a copy of this FreeTypeFont object, using any specified arguments to override the settings. Parameters are identical to the parameters used to initialize this object. :return: A FreeTypeFont object. """ return FreeTypeFont( font=self.path if font is None else font, size=self.size if size is None else size, index=self.index if index is None else index, encoding=self.encoding if encoding is None else encoding, layout_engine=layout_engine or self.layout_engine, ) def get_variation_names(self): """ :returns: A list of the named styles in a variation font. :exception OSError: If the font is not a variation font. """ try: names = self.font.getvarnames() except AttributeError as e: raise NotImplementedError("FreeType 2.9.1 or greater is required") from e return [name.replace(b"\x00", b"") for name in names] def set_variation_by_name(self, name): """ :param name: The name of the style. :exception OSError: If the font is not a variation font. """ names = self.get_variation_names() if not isinstance(name, bytes): name = name.encode() index = names.index(name) if index == getattr(self, "_last_variation_index", None): # When the same name is set twice in a row, # there is an 'unknown freetype error' # https://savannah.nongnu.org/bugs/?56186 return self._last_variation_index = index self.font.setvarname(index) def get_variation_axes(self): """ :returns: A list of the axes in a variation font. :exception OSError: If the font is not a variation font. """ try: axes = self.font.getvaraxes() except AttributeError as e: raise NotImplementedError("FreeType 2.9.1 or greater is required") from e for axis in axes: axis["name"] = axis["name"].replace(b"\x00", b"") return axes def set_variation_by_axes(self, axes): """ :param axes: A list of values for each axis. :exception OSError: If the font is not a variation font. """ try: self.font.setvaraxes(axes) except AttributeError as e: raise NotImplementedError("FreeType 2.9.1 or greater is required") from e def isPath(f): return isinstance(f, (bytes, str, Path)) The provided code snippet includes necessary dependencies for implementing the `truetype` function. Write a Python function `def truetype(font=None, size=10, index=0, encoding="", layout_engine=None)` to solve the following problem: Load a TrueType or OpenType font from a file or file-like object, and create a font object. This function loads a font object from the given file or file-like object, and creates a font object for a font of the given size. Pillow uses FreeType to open font files. If you are opening many fonts simultaneously on Windows, be aware that Windows limits the number of files that can be open in C at once to 512. If you approach that limit, an ``OSError`` may be thrown, reporting that FreeType "cannot open resource". This function requires the _imagingft service. :param font: A filename or file-like object containing a TrueType font. If the file is not found in this filename, the loader may also search in other directories, such as the :file:`fonts/` directory on Windows or :file:`/Library/Fonts/`, :file:`/System/Library/Fonts/` and :file:`~/Library/Fonts/` on macOS. :param size: The requested size, in points. :param index: Which font face to load (default is first available face). :param encoding: Which font encoding to use (default is Unicode). Possible encodings include (see the FreeType documentation for more information): * "unic" (Unicode) * "symb" (Microsoft Symbol) * "ADOB" (Adobe Standard) * "ADBE" (Adobe Expert) * "ADBC" (Adobe Custom) * "armn" (Apple Roman) * "sjis" (Shift JIS) * "gb " (PRC) * "big5" * "wans" (Extended Wansung) * "joha" (Johab) * "lat1" (Latin-1) This specifies the character set to use. It does not alter the encoding of any text provided in subsequent operations. :param layout_engine: Which layout engine to use, if available: :data:`.ImageFont.LAYOUT_BASIC` or :data:`.ImageFont.LAYOUT_RAQM`. You can check support for Raqm layout using :py:func:`PIL.features.check_feature` with ``feature="raqm"``. .. versionadded:: 4.2.0 :return: A font object. :exception OSError: If the file could not be read. Here is the function: def truetype(font=None, size=10, index=0, encoding="", layout_engine=None): """ Load a TrueType or OpenType font from a file or file-like object, and create a font object. This function loads a font object from the given file or file-like object, and creates a font object for a font of the given size. Pillow uses FreeType to open font files. If you are opening many fonts simultaneously on Windows, be aware that Windows limits the number of files that can be open in C at once to 512. If you approach that limit, an ``OSError`` may be thrown, reporting that FreeType "cannot open resource". This function requires the _imagingft service. :param font: A filename or file-like object containing a TrueType font. If the file is not found in this filename, the loader may also search in other directories, such as the :file:`fonts/` directory on Windows or :file:`/Library/Fonts/`, :file:`/System/Library/Fonts/` and :file:`~/Library/Fonts/` on macOS. :param size: The requested size, in points. :param index: Which font face to load (default is first available face). :param encoding: Which font encoding to use (default is Unicode). Possible encodings include (see the FreeType documentation for more information): * "unic" (Unicode) * "symb" (Microsoft Symbol) * "ADOB" (Adobe Standard) * "ADBE" (Adobe Expert) * "ADBC" (Adobe Custom) * "armn" (Apple Roman) * "sjis" (Shift JIS) * "gb " (PRC) * "big5" * "wans" (Extended Wansung) * "joha" (Johab) * "lat1" (Latin-1) This specifies the character set to use. It does not alter the encoding of any text provided in subsequent operations. :param layout_engine: Which layout engine to use, if available: :data:`.ImageFont.LAYOUT_BASIC` or :data:`.ImageFont.LAYOUT_RAQM`. You can check support for Raqm layout using :py:func:`PIL.features.check_feature` with ``feature="raqm"``. .. versionadded:: 4.2.0 :return: A font object. :exception OSError: If the file could not be read. """ def freetype(font): return FreeTypeFont(font, size, index, encoding, layout_engine) try: return freetype(font) except OSError: if not isPath(font): raise ttf_filename = os.path.basename(font) dirs = [] if sys.platform == "win32": # check the windows font repository # NOTE: must use uppercase WINDIR, to work around bugs in # 1.5.2's os.environ.get() windir = os.environ.get("WINDIR") if windir: dirs.append(os.path.join(windir, "fonts")) elif sys.platform in ("linux", "linux2"): lindirs = os.environ.get("XDG_DATA_DIRS", "") if not lindirs: # According to the freedesktop spec, XDG_DATA_DIRS should # default to /usr/share lindirs = "/usr/share" dirs += [os.path.join(lindir, "fonts") for lindir in lindirs.split(":")] elif sys.platform == "darwin": dirs += [ "/Library/Fonts", "/System/Library/Fonts", os.path.expanduser("~/Library/Fonts"), ] ext = os.path.splitext(ttf_filename)[1] first_font_with_a_different_extension = None for directory in dirs: for walkroot, walkdir, walkfilenames in os.walk(directory): for walkfilename in walkfilenames: if ext and walkfilename == ttf_filename: return freetype(os.path.join(walkroot, walkfilename)) elif not ext and os.path.splitext(walkfilename)[0] == ttf_filename: fontpath = os.path.join(walkroot, walkfilename) if os.path.splitext(fontpath)[1] == ".ttf": return freetype(fontpath) if not ext and first_font_with_a_different_extension is None: first_font_with_a_different_extension = fontpath if first_font_with_a_different_extension: return freetype(first_font_with_a_different_extension) raise
Load a TrueType or OpenType font from a file or file-like object, and create a font object. This function loads a font object from the given file or file-like object, and creates a font object for a font of the given size. Pillow uses FreeType to open font files. If you are opening many fonts simultaneously on Windows, be aware that Windows limits the number of files that can be open in C at once to 512. If you approach that limit, an ``OSError`` may be thrown, reporting that FreeType "cannot open resource". This function requires the _imagingft service. :param font: A filename or file-like object containing a TrueType font. If the file is not found in this filename, the loader may also search in other directories, such as the :file:`fonts/` directory on Windows or :file:`/Library/Fonts/`, :file:`/System/Library/Fonts/` and :file:`~/Library/Fonts/` on macOS. :param size: The requested size, in points. :param index: Which font face to load (default is first available face). :param encoding: Which font encoding to use (default is Unicode). Possible encodings include (see the FreeType documentation for more information): * "unic" (Unicode) * "symb" (Microsoft Symbol) * "ADOB" (Adobe Standard) * "ADBE" (Adobe Expert) * "ADBC" (Adobe Custom) * "armn" (Apple Roman) * "sjis" (Shift JIS) * "gb " (PRC) * "big5" * "wans" (Extended Wansung) * "joha" (Johab) * "lat1" (Latin-1) This specifies the character set to use. It does not alter the encoding of any text provided in subsequent operations. :param layout_engine: Which layout engine to use, if available: :data:`.ImageFont.LAYOUT_BASIC` or :data:`.ImageFont.LAYOUT_RAQM`. You can check support for Raqm layout using :py:func:`PIL.features.check_feature` with ``feature="raqm"``. .. versionadded:: 4.2.0 :return: A font object. :exception OSError: If the file could not be read.
167,716
import base64 import os import sys from io import BytesIO from . import Image from ._util import isDirectory, isPath def load(filename): """ Load a font file. This function loads a font object from the given bitmap font file, and returns the corresponding font object. :param filename: Name of font file. :return: A font object. :exception OSError: If the file could not be read. """ f = ImageFont() f._load_pilfont(filename) return f def isDirectory(f): return isPath(f) and os.path.isdir(f) The provided code snippet includes necessary dependencies for implementing the `load_path` function. Write a Python function `def load_path(filename)` to solve the following problem: Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a bitmap font along the Python path. :param filename: Name of font file. :return: A font object. :exception OSError: If the file could not be read. Here is the function: def load_path(filename): """ Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a bitmap font along the Python path. :param filename: Name of font file. :return: A font object. :exception OSError: If the file could not be read. """ for directory in sys.path: if isDirectory(directory): if not isinstance(filename, str): filename = filename.decode("utf-8") try: return load(os.path.join(directory, filename)) except OSError: pass raise OSError("cannot find font file")
Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a bitmap font along the Python path. :param filename: Name of font file. :return: A font object. :exception OSError: If the file could not be read.
167,717
import base64 import os import sys from io import BytesIO from . import Image from ._util import isDirectory, isPath class ImageFont: "PIL font wrapper" def _load_pilfont(self, filename): with open(filename, "rb") as fp: image = None for ext in (".png", ".gif", ".pbm"): if image: image.close() try: fullname = os.path.splitext(filename)[0] + ext image = Image.open(fullname) except Exception: pass else: if image and image.mode in ("1", "L"): break else: if image: image.close() raise OSError("cannot find glyph data file") self.file = fullname self._load_pilfont_data(fp, image) image.close() def _load_pilfont_data(self, file, image): # read PILfont header if file.readline() != b"PILfont\n": raise SyntaxError("Not a PILfont file") file.readline().split(b";") self.info = [] # FIXME: should be a dictionary while True: s = file.readline() if not s or s == b"DATA\n": break self.info.append(s) # read PILfont metrics data = file.read(256 * 20) # check image if image.mode not in ("1", "L"): raise TypeError("invalid font image mode") image.load() self.font = Image.core.font(image.im, data) def getsize(self, text, *args, **kwargs): """ Returns width and height (in pixels) of given text. :param text: Text to measure. :return: (width, height) """ return self.font.getsize(text) def getmask(self, text, mode="", *args, **kwargs): """ Create a bitmap for the text. If the font uses antialiasing, the bitmap should have mode ``L`` and use a maximum value of 255. Otherwise, it should have mode ``1``. :param text: Text to render. :param mode: Used by some graphics drivers to indicate what mode the driver prefers; if empty, the renderer may return either mode. Note that the mode is always a string, to simplify C-level implementations. .. versionadded:: 1.1.5 :return: An internal PIL storage memory instance as defined by the :py:mod:`PIL.Image.core` interface module. """ return self.font.getmask(text, mode) 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": warnings.warn( "Image categories are deprecated and will be removed in Pillow 10 " "(2023-07-01). Use is_animated instead.", DeprecationWarning, stacklevel=2, ) 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 hasattr(self, "_close__fp"): self._close__fp() 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 hasattr(self, "_close__fp"): self._close__fp() 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 = deferred_error(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.readonly == other.readonly 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_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: raise ValueError("Could not save to PNG for display") from e return b.getvalue() class _ArrayData: def __init__(self, new): self.__array_interface__ = new def __array__(self, dtype=None): # numpy array interface support import numpy as np new = {} shape, typestr = _conv_type_shape(self) new["shape"] = shape new["typestr"] = typestr new["version"] = 3 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() return np.array(self._ArrayData(new), dtype) def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) self.tile = [] 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. :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() # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c data = [] while True: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError(f"encoder error {s} in tobytes") return b"".join(data) 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": raise ValueError("not a bitmap") 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: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data") 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 and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() if mode == "RGBA": mode = "RGB" self.info["transparency"] = arr[3::4] arr = bytes( value for (index, value) in enumerate(arr) if index % 4 != 3 ) palette_length = 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: self.palette.mode = "RGB" self.palette.palette = self.im.getpalette()[: palette_length * 3] if self.im: 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=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 :data:`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. :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:`NONE` or :data:`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:`WEB` or :data:`ADAPTIVE`. :param colors: Number of colors to use for the :data:`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"): raise ValueError("illegal conversion") 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", "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: raise ValueError("Transparency for P mode should be bytes or int") if mode == "P" and 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 # colorspace conversion if dither is None: dither = FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError as e: raise ValueError("illegal conversion") from e new_im = self._new(im) if mode == "P" and 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=1): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`MEDIANCUT` (median cut), :data:`MAXCOVERAGE` (maximum coverage), :data:`FASTOCTREE` (fast octree), :data:`LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`MEDIANCUT` will be used. The exception to this is RGBA images. :data:`MEDIANCUT` and :data:`MAXCOVERAGE` do not support RGBA images, so :data:`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:`NONE` or :data:`FLOYDSTEINBERG` (default). Default: 1 (legacy setting) :returns: A new image """ self.load() if method is None: # defaults: method = MEDIANCUT if self.mode == "RGBA": method = FASTOCTREE if self.mode == "RGBA" and method not in (FASTOCTREE, LIBIMAGEQUANT): # Caller specified an invalid mode. raise ValueError( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) 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() 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. """ 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"): raise TypeError( "filter argument should be ImageFilter.Filter instance or class" ) 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 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): if self._exif is None: self._exif = Exif() 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.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[1]) return self._exif 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): """ Returns the image palette as a list. :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: return list(self.im.getpalette()) except ValueError: return None # no palette 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. 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" or "RGBA" images (in the latter case, 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? raise ValueError("cannot determine region size; use 4-item box") 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 ("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)): raise ValueError("Source must be a tuple") if not isinstance(dest, (list, tuple)): raise ValueError("Destination must be a tuple") if not len(source) in (2, 4): raise ValueError("Source must be a 2 or 4-tuple") if not len(dest) == 2: raise ValueError("Destination must be a 2-tuple") if min(source) < 0: raise ValueError("Source must be non-negative") 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 raise ValueError("point operation not supported for this mode") 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: raise ValueError("illegal image mode") 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"): raise ValueError("illegal image mode") 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" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): raise ValueError("illegal image mode") 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 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 == "P" and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P image value = self.palette.getcolor(value, self) 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"): raise ValueError("illegal image mode") if source_palette is None: if self.mode == "P": self.load() source_palette = self.im.getpalette("RGB")[:768] 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 * 3 : oldPosition * 3 + 3] 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("RGB", palette=mapping_palette * 3) # 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("RGB;L", m_im.palette.tobytes()) m_im = m_im.convert("L") # Internally, we require 768 bytes for a palette. new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b"\x00" m_im.putpalette(new_palette_bytes) m_im.palette = ImagePalette.ImagePalette("RGB", palette=palette_bytes) 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:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`PIL.Image.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`PIL.Image.NEAREST`. Otherwise, the default filter is :py:data:`PIL.Image.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 = NEAREST if type_special else BICUBIC elif resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING): message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (LANCZOS, "Image.LANCZOS"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), (BOX, "Image.BOX"), (HAMMING, "Image.HAMMING"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) if reducing_gap is not None and reducing_gap < 1.0: raise ValueError("reducing_gap must be 1.0 or greater") size = tuple(size) 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 = NEAREST if self.mode in ["LA", "RGBA"] and resample != 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 != 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=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:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.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:`PIL.Image.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(ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose(ROTATE_90 if angle == 90 else 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), 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 isPath(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 isPath(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: raise ValueError(f"unknown file extension: {ext}") from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] if open_fp: 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) finally: # do what we can to clean up 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: raise ValueError(f'The image has no channel "{channel}"') 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=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: Requested size. :param resample: Optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If omitted, it defaults to :py:data:`PIL.Image.BICUBIC`. (was :py:data:`PIL.Image.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 """ x, y = map(math.floor, size) if x >= self.width and y >= self.height: return def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) # preserve aspect ratio 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) ) size = (x, y) box = None if reducing_gap is not None: res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] 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=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. :param method: The transformation method. This is one of :py:data:`PIL.Image.EXTENT` (cut out a rectangular subregion), :py:data:`PIL.Image.AFFINE` (affine transform), :py:data:`PIL.Image.PERSPECTIVE` (perspective transform), :py:data:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or :py:data:`PIL.Image.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.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:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.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:`PIL.Image.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 != 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: raise ValueError("missing method data") 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 == MESH: # list of quads for box, quad in data: im.__transformer(box, self, 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=NEAREST, fill=1): w = box[2] - box[0] h = box[3] - box[1] if method == AFFINE: data = data[0:6] elif method == EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == PERSPECTIVE: data = data[0:8] elif method == QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[0: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: raise ValueError("unknown transformation method") if resample not in (NEAREST, BILINEAR, BICUBIC): if resample in (BOX, HAMMING, LANCZOS): message = { BOX: "Image.BOX", HAMMING: "Image.HAMMING", LANCZOS: "Image.LANCZOS/Image.ANTIALIAS", }[resample] + f" ({resample}) cannot be used." else: message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) image.load() self.load() if image.mode in ("1", "P"): resample = 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:`PIL.Image.FLIP_LEFT_RIGHT`, :py:data:`PIL.Image.FLIP_TOP_BOTTOM`, :py:data:`PIL.Image.ROTATE_90`, :py:data:`PIL.Image.ROTATE_180`, :py:data:`PIL.Image.ROTATE_270`, :py:data:`PIL.Image.TRANSPOSE` or :py:data:`PIL.Image.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: raise ImportError("Qt bindings are not installed") return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `load_default` function. Write a Python function `def load_default()` to solve the following problem: Load a "better than nothing" default font. .. versionadded:: 1.1.4 :return: A font object. Here is the function: def load_default(): """Load a "better than nothing" default font. .. versionadded:: 1.1.4 :return: A font object. """ f = ImageFont() f._load_pilfont_data( # courB08 BytesIO( base64.b64decode( b""" UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAA//8AAQAAAAAAAAABAAEA BgAAAAH/+gADAAAAAQAAAAMABgAGAAAAAf/6AAT//QADAAAABgADAAYAAAAA//kABQABAAYAAAAL AAgABgAAAAD/+AAFAAEACwAAABAACQAGAAAAAP/5AAUAAAAQAAAAFQAHAAYAAP////oABQAAABUA AAAbAAYABgAAAAH/+QAE//wAGwAAAB4AAwAGAAAAAf/5AAQAAQAeAAAAIQAIAAYAAAAB//kABAAB ACEAAAAkAAgABgAAAAD/+QAE//0AJAAAACgABAAGAAAAAP/6AAX//wAoAAAALQAFAAYAAAAB//8A BAACAC0AAAAwAAMABgAAAAD//AAF//0AMAAAADUAAQAGAAAAAf//AAMAAAA1AAAANwABAAYAAAAB //kABQABADcAAAA7AAgABgAAAAD/+QAFAAAAOwAAAEAABwAGAAAAAP/5AAYAAABAAAAARgAHAAYA AAAA//kABQAAAEYAAABLAAcABgAAAAD/+QAFAAAASwAAAFAABwAGAAAAAP/5AAYAAABQAAAAVgAH AAYAAAAA//kABQAAAFYAAABbAAcABgAAAAD/+QAFAAAAWwAAAGAABwAGAAAAAP/5AAUAAABgAAAA ZQAHAAYAAAAA//kABQAAAGUAAABqAAcABgAAAAD/+QAFAAAAagAAAG8ABwAGAAAAAf/8AAMAAABv AAAAcQAEAAYAAAAA//wAAwACAHEAAAB0AAYABgAAAAD/+gAE//8AdAAAAHgABQAGAAAAAP/7AAT/ /gB4AAAAfAADAAYAAAAB//oABf//AHwAAACAAAUABgAAAAD/+gAFAAAAgAAAAIUABgAGAAAAAP/5 AAYAAQCFAAAAiwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAA AP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAG AAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsA BgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAA AMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA 2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAF AAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA//// +gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA ////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYA BgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEv AAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcA AAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAA AUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sA BQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP// //kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYA AP////kABgAAAXcAAAF+AAcABgAAAAD/+QAGAAABfgAAAYQABwAGAAD////7AAUAAAGEAAABigAF AAYAAP////sABQAAAYoAAAGQAAUABgAAAAD/+wAFAAABkAAAAZUABQAGAAD////7AAUAAgGVAAAB mwAHAAYAAAAA//sABgACAZsAAAGhAAcABgAAAAD/+wAGAAABoQAAAacABQAGAAAAAP/7AAYAAAGn AAABrQAFAAYAAAAA//kABgAAAa0AAAGzAAcABgAA////+wAGAAABswAAAboABQAGAAD////7AAUA AAG6AAABwAAFAAYAAP////sABgAAAcAAAAHHAAUABgAAAAD/+wAGAAABxwAAAc0ABQAGAAD////7 AAYAAgHNAAAB1AAHAAYAAAAA//sABQAAAdQAAAHZAAUABgAAAAH/+QAFAAEB2QAAAd0ACAAGAAAA Av/6AAMAAQHdAAAB3gAHAAYAAAAA//kABAABAd4AAAHiAAgABgAAAAD/+wAF//0B4gAAAecAAgAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAB //sAAwACAecAAAHpAAcABgAAAAD/+QAFAAEB6QAAAe4ACAAGAAAAAP/5AAYAAAHuAAAB9AAHAAYA AAAA//oABf//AfQAAAH5AAUABgAAAAD/+QAGAAAB+QAAAf8ABwAGAAAAAv/5AAMAAgH/AAACAAAJ AAYAAAAA//kABQABAgAAAAIFAAgABgAAAAH/+gAE//sCBQAAAggAAQAGAAAAAP/5AAYAAAIIAAAC DgAHAAYAAAAB//kABf/+Ag4AAAISAAUABgAA////+wAGAAACEgAAAhkABQAGAAAAAP/7AAX//gIZ AAACHgADAAYAAAAA//wABf/9Ah4AAAIjAAEABgAAAAD/+QAHAAACIwAAAioABwAGAAAAAP/6AAT/ +wIqAAACLgABAAYAAAAA//kABP/8Ai4AAAIyAAMABgAAAAD/+gAFAAACMgAAAjcABgAGAAAAAf/5 AAT//QI3AAACOgAEAAYAAAAB//kABP/9AjoAAAI9AAQABgAAAAL/+QAE//sCPQAAAj8AAgAGAAD/ ///7AAYAAgI/AAACRgAHAAYAAAAA//kABgABAkYAAAJMAAgABgAAAAH//AAD//0CTAAAAk4AAQAG AAAAAf//AAQAAgJOAAACUQADAAYAAAAB//kABP/9AlEAAAJUAAQABgAAAAH/+QAF//4CVAAAAlgA BQAGAAD////7AAYAAAJYAAACXwAFAAYAAP////kABgAAAl8AAAJmAAcABgAA////+QAGAAACZgAA Am0ABwAGAAD////5AAYAAAJtAAACdAAHAAYAAAAA//sABQACAnQAAAJ5AAcABgAA////9wAGAAAC eQAAAoAACQAGAAD////3AAYAAAKAAAAChwAJAAYAAP////cABgAAAocAAAKOAAkABgAA////9wAG AAACjgAAApUACQAGAAD////4AAYAAAKVAAACnAAIAAYAAP////cABgAAApwAAAKjAAkABgAA//// +gAGAAACowAAAqoABgAGAAAAAP/6AAUAAgKqAAACrwAIAAYAAP////cABQAAAq8AAAK1AAkABgAA ////9wAFAAACtQAAArsACQAGAAD////3AAUAAAK7AAACwQAJAAYAAP////gABQAAAsEAAALHAAgA BgAAAAD/9wAEAAACxwAAAssACQAGAAAAAP/3AAQAAALLAAACzwAJAAYAAAAA//cABAAAAs8AAALT AAkABgAAAAD/+AAEAAAC0wAAAtcACAAGAAD////6AAUAAALXAAAC3QAGAAYAAP////cABgAAAt0A AALkAAkABgAAAAD/9wAFAAAC5AAAAukACQAGAAAAAP/3AAUAAALpAAAC7gAJAAYAAAAA//cABQAA Au4AAALzAAkABgAAAAD/9wAFAAAC8wAAAvgACQAGAAAAAP/4AAUAAAL4AAAC/QAIAAYAAAAA//oA Bf//Av0AAAMCAAUABgAA////+gAGAAADAgAAAwkABgAGAAD////3AAYAAAMJAAADEAAJAAYAAP// //cABgAAAxAAAAMXAAkABgAA////9wAGAAADFwAAAx4ACQAGAAD////4AAYAAAAAAAoABwASAAYA AP////cABgAAAAcACgAOABMABgAA////+gAFAAAADgAKABQAEAAGAAD////6AAYAAAAUAAoAGwAQ AAYAAAAA//gABgAAABsACgAhABIABgAAAAD/+AAGAAAAIQAKACcAEgAGAAAAAP/4AAYAAAAnAAoA LQASAAYAAAAA//gABgAAAC0ACgAzABIABgAAAAD/+QAGAAAAMwAKADkAEQAGAAAAAP/3AAYAAAA5 AAoAPwATAAYAAP////sABQAAAD8ACgBFAA8ABgAAAAD/+wAFAAIARQAKAEoAEQAGAAAAAP/4AAUA AABKAAoATwASAAYAAAAA//gABQAAAE8ACgBUABIABgAAAAD/+AAFAAAAVAAKAFkAEgAGAAAAAP/5 AAUAAABZAAoAXgARAAYAAAAA//gABgAAAF4ACgBkABIABgAAAAD/+AAGAAAAZAAKAGoAEgAGAAAA AP/4AAYAAABqAAoAcAASAAYAAAAA//kABgAAAHAACgB2ABEABgAAAAD/+AAFAAAAdgAKAHsAEgAG AAD////4AAYAAAB7AAoAggASAAYAAAAA//gABQAAAIIACgCHABIABgAAAAD/+AAFAAAAhwAKAIwA EgAGAAAAAP/4AAUAAACMAAoAkQASAAYAAAAA//gABQAAAJEACgCWABIABgAAAAD/+QAFAAAAlgAK AJsAEQAGAAAAAP/6AAX//wCbAAoAoAAPAAYAAAAA//oABQABAKAACgClABEABgAA////+AAGAAAA pQAKAKwAEgAGAAD////4AAYAAACsAAoAswASAAYAAP////gABgAAALMACgC6ABIABgAA////+QAG AAAAugAKAMEAEQAGAAD////4AAYAAgDBAAoAyAAUAAYAAP////kABQACAMgACgDOABMABgAA//// +QAGAAIAzgAKANUAEw== """ ) ), Image.open( BytesIO( base64.b64decode( b""" iVBORw0KGgoAAAANSUhEUgAAAx4AAAAUAQAAAAArMtZoAAAEwElEQVR4nABlAJr/AHVE4czCI/4u Mc4b7vuds/xzjz5/3/7u/n9vMe7vnfH/9++vPn/xyf5zhxzjt8GHw8+2d83u8x27199/nxuQ6Od9 M43/5z2I+9n9ZtmDBwMQECDRQw/eQIQohJXxpBCNVE6QCCAAAAD//wBlAJr/AgALyj1t/wINwq0g LeNZUworuN1cjTPIzrTX6ofHWeo3v336qPzfEwRmBnHTtf95/fglZK5N0PDgfRTslpGBvz7LFc4F IUXBWQGjQ5MGCx34EDFPwXiY4YbYxavpnhHFrk14CDAAAAD//wBlAJr/AgKqRooH2gAgPeggvUAA Bu2WfgPoAwzRAABAAAAAAACQgLz/3Uv4Gv+gX7BJgDeeGP6AAAD1NMDzKHD7ANWr3loYbxsAD791 NAADfcoIDyP44K/jv4Y63/Z+t98Ovt+ub4T48LAAAAD//wBlAJr/AuplMlADJAAAAGuAphWpqhMx in0A/fRvAYBABPgBwBUgABBQ/sYAyv9g0bCHgOLoGAAAAAAAREAAwI7nr0ArYpow7aX8//9LaP/9 SjdavWA8ePHeBIKB//81/83ndznOaXx379wAAAD//wBlAJr/AqDxW+D3AABAAbUh/QMnbQag/gAY AYDAAACgtgD/gOqAAAB5IA/8AAAk+n9w0AAA8AAAmFRJuPo27ciC0cD5oeW4E7KA/wD3ECMAn2tt y8PgwH8AfAxFzC0JzeAMtratAsC/ffwAAAD//wBlAJr/BGKAyCAA4AAAAvgeYTAwHd1kmQF5chkG ABoMIHcL5xVpTfQbUqzlAAAErwAQBgAAEOClA5D9il08AEh/tUzdCBsXkbgACED+woQg8Si9VeqY lODCn7lmF6NhnAEYgAAA/NMIAAAAAAD//2JgjLZgVGBg5Pv/Tvpc8hwGBjYGJADjHDrAwPzAjv/H /Wf3PzCwtzcwHmBgYGcwbZz8wHaCAQMDOwMDQ8MCBgYOC3W7mp+f0w+wHOYxO3OG+e376hsMZjk3 AAAAAP//YmCMY2A4wMAIN5e5gQETPD6AZisDAwMDgzSDAAPjByiHcQMDAwMDg1nOze1lByRu5/47 c4859311AYNZzg0AAAAA//9iYGDBYihOIIMuwIjGL39/fwffA8b//xv/P2BPtzzHwCBjUQAAAAD/ /yLFBrIBAAAA//9i1HhcwdhizX7u8NZNzyLbvT97bfrMf/QHI8evOwcSqGUJAAAA//9iYBB81iSw pEE170Qrg5MIYydHqwdDQRMrAwcVrQAAAAD//2J4x7j9AAMDn8Q/BgYLBoaiAwwMjPdvMDBYM1Tv oJodAAAAAP//Yqo/83+dxePWlxl3npsel9lvLfPcqlE9725C+acfVLMEAAAA//9i+s9gwCoaaGMR evta/58PTEWzr21hufPjA8N+qlnBwAAAAAD//2JiWLci5v1+HmFXDqcnULE/MxgYGBj+f6CaJQAA AAD//2Ji2FrkY3iYpYC5qDeGgeEMAwPDvwQBBoYvcTwOVLMEAAAA//9isDBgkP///0EOg9z35v// Gc/eeW7BwPj5+QGZhANUswMAAAD//2JgqGBgYGBgqEMXlvhMPUsAAAAA//8iYDd1AAAAAP//AwDR w7IkEbzhVQAAAABJRU5ErkJggg== """ ) ) ), ) return f
Load a "better than nothing" default font. .. versionadded:: 1.1.4 :return: A font object.
167,718
from . import ImageFile, ImagePalette, UnidentifiedImageError from ._binary import i16be as i16 from ._binary import i32be as i32 class GdImageFile(ImageFile.ImageFile): """ Image plugin for the GD uncompressed format. Note that this format is not supported by the standard :py:func:`PIL.Image.open()` function. To use this plugin, you have to import the :py:mod:`PIL.GdImageFile` module and use the :py:func:`PIL.GdImageFile.open()` function. """ format = "GD" format_description = "GD uncompressed images" def _open(self): # Header s = self.fp.read(1037) if not i16(s) in [65534, 65535]: raise SyntaxError("Not a valid GD 2.x .gd file") self.mode = "L" # FIXME: "P" self._size = i16(s, 2), i16(s, 4) trueColor = s[6] trueColorOffset = 2 if trueColor else 0 # transparency index tindex = i32(s, 7 + trueColorOffset) if tindex < 256: self.info["transparency"] = tindex self.palette = ImagePalette.raw( "XBGR", s[7 + trueColorOffset + 4 : 7 + trueColorOffset + 4 + 256 * 4] ) self.tile = [ ("raw", (0, 0) + self.size, 7 + trueColorOffset + 4 + 256 * 4, ("L", 0, 1)) ] The provided code snippet includes necessary dependencies for implementing the `open` function. Write a Python function `def open(fp, mode="r")` to solve the following problem: Load texture from a GD image file. :param filename: GD file name, or an opened file handle. :param mode: Optional mode. In this version, if the mode argument is given, it must be "r". :returns: An image instance. :raises OSError: If the image could not be read. Here is the function: def open(fp, mode="r"): """ Load texture from a GD image file. :param filename: GD file name, or an opened file handle. :param mode: Optional mode. In this version, if the mode argument is given, it must be "r". :returns: An image instance. :raises OSError: If the image could not be read. """ if mode != "r": raise ValueError("bad mode") try: return GdImageFile(fp) except SyntaxError as e: raise UnidentifiedImageError("cannot identify this image file") from e
Load texture from a GD image file. :param filename: GD file name, or an opened file handle. :param mode: Optional mode. In this version, if the mode argument is given, it must be "r". :returns: An image instance. :raises OSError: If the image could not be read.
167,719
import itertools import logging import re import struct import warnings import zlib from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from ._binary import o16be as o16 from ._binary import o32be as o32 MAX_TEXT_CHUNK = ImageFile.SAFEBLOCK def _safe_zlib_decompress(s): dobj = zlib.decompressobj() plaintext = dobj.decompress(s, MAX_TEXT_CHUNK) if dobj.unconsumed_tail: raise ValueError("Decompressed Data Too Large") return plaintext
null
167,720
import itertools import logging import re import struct import warnings import zlib from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from ._binary import o16be as o16 from ._binary import o32be as o32 _MAGIC = b"\211PNG\r\n\032\n" def _accept(prefix): return prefix[:8] == _MAGIC
null
167,721
import itertools import logging import re import struct import warnings import zlib from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from ._binary import o16be as o16 from ._binary import o32be as o32 def _save(im, fp, filename, chunk=putchunk, save_all=False): # save an image to disk (called by the save method) mode = im.mode if mode == "P": # # attempt to minimize storage requirements for palette images if "bits" in im.encoderinfo: # number of bits specified by user colors = min(1 << im.encoderinfo["bits"], 256) else: # check palette contents if im.palette: colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 1) else: colors = 256 if colors <= 16: if colors <= 2: bits = 1 elif colors <= 4: bits = 2 else: bits = 4 mode = f"{mode};{bits}" # encoder options im.encoderconfig = ( im.encoderinfo.get("optimize", False), im.encoderinfo.get("compress_level", -1), im.encoderinfo.get("compress_type", -1), im.encoderinfo.get("dictionary", b""), ) # get the corresponding PNG mode try: rawmode, mode = _OUTMODES[mode] except KeyError as e: raise OSError(f"cannot write mode {mode} as PNG") from e # # write minimal PNG file fp.write(_MAGIC) chunk( fp, b"IHDR", o32(im.size[0]), # 0: size o32(im.size[1]), mode, # 8: depth/type b"\0", # 10: compression b"\0", # 11: filter category b"\0", # 12: interlace flag ) chunks = [b"cHRM", b"gAMA", b"sBIT", b"sRGB", b"tIME"] icc = im.encoderinfo.get("icc_profile", im.info.get("icc_profile")) if icc: # ICC profile # according to PNG spec, the iCCP chunk contains: # Profile name 1-79 bytes (character string) # Null separator 1 byte (null character) # Compression method 1 byte (0) # Compressed profile n bytes (zlib with deflate compression) name = b"ICC Profile" data = name + b"\0\0" + zlib.compress(icc) chunk(fp, b"iCCP", data) # You must either have sRGB or iCCP. # Disallow sRGB chunks when an iCCP-chunk has been emitted. chunks.remove(b"sRGB") info = im.encoderinfo.get("pnginfo") if info: chunks_multiple_allowed = [b"sPLT", b"iTXt", b"tEXt", b"zTXt"] for info_chunk in info.chunks: cid, data = info_chunk[:2] if cid in chunks: chunks.remove(cid) chunk(fp, cid, data) elif cid in chunks_multiple_allowed: chunk(fp, cid, data) elif cid[1:2].islower(): # Private chunk after_idat = info_chunk[2:3] if not after_idat: chunk(fp, cid, data) if im.mode == "P": palette_byte_number = colors * 3 palette_bytes = im.im.getpalette("RGB")[:palette_byte_number] while len(palette_bytes) < palette_byte_number: palette_bytes += b"\0" chunk(fp, b"PLTE", palette_bytes) transparency = im.encoderinfo.get("transparency", im.info.get("transparency", None)) if transparency or transparency == 0: if im.mode == "P": # limit to actual palette size alpha_bytes = colors if isinstance(transparency, bytes): chunk(fp, b"tRNS", transparency[:alpha_bytes]) else: transparency = max(0, min(255, transparency)) alpha = b"\xFF" * transparency + b"\0" chunk(fp, b"tRNS", alpha[:alpha_bytes]) elif im.mode in ("1", "L", "I"): transparency = max(0, min(65535, transparency)) chunk(fp, b"tRNS", o16(transparency)) elif im.mode == "RGB": red, green, blue = transparency chunk(fp, b"tRNS", o16(red) + o16(green) + o16(blue)) else: if "transparency" in im.encoderinfo: # don't bother with transparency if it's an RGBA # and it's in the info dict. It's probably just stale. raise OSError("cannot use transparency for this mode") else: if im.mode == "P" and im.im.getpalettemode() == "RGBA": alpha = im.im.getpalette("RGBA", "A") alpha_bytes = colors chunk(fp, b"tRNS", alpha[:alpha_bytes]) dpi = im.encoderinfo.get("dpi") if dpi: chunk( fp, b"pHYs", o32(int(dpi[0] / 0.0254 + 0.5)), o32(int(dpi[1] / 0.0254 + 0.5)), b"\x01", ) if info: chunks = [b"bKGD", b"hIST"] for info_chunk in info.chunks: cid, data = info_chunk[:2] if cid in chunks: chunks.remove(cid) chunk(fp, cid, data) exif = im.encoderinfo.get("exif", im.info.get("exif")) if exif: if isinstance(exif, Image.Exif): exif = exif.tobytes(8) if exif.startswith(b"Exif\x00\x00"): exif = exif[6:] chunk(fp, b"eXIf", exif) if save_all: _write_multiple_frames(im, fp, chunk, rawmode) else: ImageFile._save(im, _idat(fp, chunk), [("zip", (0, 0) + im.size, 0, rawmode)]) if info: for info_chunk in info.chunks: cid, data = info_chunk[:2] if cid[1:2].islower(): # Private chunk after_idat = info_chunk[2:3] if after_idat: chunk(fp, cid, data) chunk(fp, b"IEND", b"") if hasattr(fp, "flush"): fp.flush() def _save_all(im, fp, filename): _save(im, fp, filename, save_all=True)
null
167,722
import itertools import logging import re import struct import warnings import zlib from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 from ._binary import o16be as o16 from ._binary import o32be as o32 def _crc32(data, seed=0): return zlib.crc32(data, seed) & 0xFFFFFFFF def _save(im, fp, filename, chunk=putchunk, save_all=False): # save an image to disk (called by the save method) mode = im.mode if mode == "P": # # attempt to minimize storage requirements for palette images if "bits" in im.encoderinfo: # number of bits specified by user colors = min(1 << im.encoderinfo["bits"], 256) else: # check palette contents if im.palette: colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 1) else: colors = 256 if colors <= 16: if colors <= 2: bits = 1 elif colors <= 4: bits = 2 else: bits = 4 mode = f"{mode};{bits}" # encoder options im.encoderconfig = ( im.encoderinfo.get("optimize", False), im.encoderinfo.get("compress_level", -1), im.encoderinfo.get("compress_type", -1), im.encoderinfo.get("dictionary", b""), ) # get the corresponding PNG mode try: rawmode, mode = _OUTMODES[mode] except KeyError as e: raise OSError(f"cannot write mode {mode} as PNG") from e # # write minimal PNG file fp.write(_MAGIC) chunk( fp, b"IHDR", o32(im.size[0]), # 0: size o32(im.size[1]), mode, # 8: depth/type b"\0", # 10: compression b"\0", # 11: filter category b"\0", # 12: interlace flag ) chunks = [b"cHRM", b"gAMA", b"sBIT", b"sRGB", b"tIME"] icc = im.encoderinfo.get("icc_profile", im.info.get("icc_profile")) if icc: # ICC profile # according to PNG spec, the iCCP chunk contains: # Profile name 1-79 bytes (character string) # Null separator 1 byte (null character) # Compression method 1 byte (0) # Compressed profile n bytes (zlib with deflate compression) name = b"ICC Profile" data = name + b"\0\0" + zlib.compress(icc) chunk(fp, b"iCCP", data) # You must either have sRGB or iCCP. # Disallow sRGB chunks when an iCCP-chunk has been emitted. chunks.remove(b"sRGB") info = im.encoderinfo.get("pnginfo") if info: chunks_multiple_allowed = [b"sPLT", b"iTXt", b"tEXt", b"zTXt"] for info_chunk in info.chunks: cid, data = info_chunk[:2] if cid in chunks: chunks.remove(cid) chunk(fp, cid, data) elif cid in chunks_multiple_allowed: chunk(fp, cid, data) elif cid[1:2].islower(): # Private chunk after_idat = info_chunk[2:3] if not after_idat: chunk(fp, cid, data) if im.mode == "P": palette_byte_number = colors * 3 palette_bytes = im.im.getpalette("RGB")[:palette_byte_number] while len(palette_bytes) < palette_byte_number: palette_bytes += b"\0" chunk(fp, b"PLTE", palette_bytes) transparency = im.encoderinfo.get("transparency", im.info.get("transparency", None)) if transparency or transparency == 0: if im.mode == "P": # limit to actual palette size alpha_bytes = colors if isinstance(transparency, bytes): chunk(fp, b"tRNS", transparency[:alpha_bytes]) else: transparency = max(0, min(255, transparency)) alpha = b"\xFF" * transparency + b"\0" chunk(fp, b"tRNS", alpha[:alpha_bytes]) elif im.mode in ("1", "L", "I"): transparency = max(0, min(65535, transparency)) chunk(fp, b"tRNS", o16(transparency)) elif im.mode == "RGB": red, green, blue = transparency chunk(fp, b"tRNS", o16(red) + o16(green) + o16(blue)) else: if "transparency" in im.encoderinfo: # don't bother with transparency if it's an RGBA # and it's in the info dict. It's probably just stale. raise OSError("cannot use transparency for this mode") else: if im.mode == "P" and im.im.getpalettemode() == "RGBA": alpha = im.im.getpalette("RGBA", "A") alpha_bytes = colors chunk(fp, b"tRNS", alpha[:alpha_bytes]) dpi = im.encoderinfo.get("dpi") if dpi: chunk( fp, b"pHYs", o32(int(dpi[0] / 0.0254 + 0.5)), o32(int(dpi[1] / 0.0254 + 0.5)), b"\x01", ) if info: chunks = [b"bKGD", b"hIST"] for info_chunk in info.chunks: cid, data = info_chunk[:2] if cid in chunks: chunks.remove(cid) chunk(fp, cid, data) exif = im.encoderinfo.get("exif", im.info.get("exif")) if exif: if isinstance(exif, Image.Exif): exif = exif.tobytes(8) if exif.startswith(b"Exif\x00\x00"): exif = exif[6:] chunk(fp, b"eXIf", exif) if save_all: _write_multiple_frames(im, fp, chunk, rawmode) else: ImageFile._save(im, _idat(fp, chunk), [("zip", (0, 0) + im.size, 0, rawmode)]) if info: for info_chunk in info.chunks: cid, data = info_chunk[:2] if cid[1:2].islower(): # Private chunk after_idat = info_chunk[2:3] if after_idat: chunk(fp, cid, data) chunk(fp, b"IEND", b"") if hasattr(fp, "flush"): fp.flush() The provided code snippet includes necessary dependencies for implementing the `getchunks` function. Write a Python function `def getchunks(im, **params)` to solve the following problem: Return a list of PNG chunks representing this image. Here is the function: def getchunks(im, **params): """Return a list of PNG chunks representing this image.""" class collector: data = [] def write(self, data): pass def append(self, chunk): self.data.append(chunk) def append(fp, cid, *data): data = b"".join(data) crc = o32(_crc32(data, _crc32(cid))) fp.append((cid, data, crc)) fp = collector() try: im.encoderinfo = params _save(im, fp, None, append) finally: del im.encoderinfo return fp.data
Return a list of PNG chunks representing this image.
167,723
import os import struct from . import Image, ImageFile from ._binary import i16be as i16 from ._binary import o8 def _accept(prefix): return len(prefix) >= 2 and i16(prefix) == 474
null
167,724
import os import struct from . import Image, ImageFile from ._binary import i16be as i16 from ._binary import o8 def o8(i): return bytes((i & 255,)) def _save(im, fp, filename): if im.mode != "RGB" and im.mode != "RGBA" and im.mode != "L": raise ValueError("Unsupported SGI image mode") # Get the keyword arguments info = im.encoderinfo # Byte-per-pixel precision, 1 = 8bits per pixel bpc = info.get("bpc", 1) if bpc not in (1, 2): raise ValueError("Unsupported number of bytes per pixel") # Flip the image, since the origin of SGI file is the bottom-left corner orientation = -1 # Define the file as SGI File Format magicNumber = 474 # Run-Length Encoding Compression - Unsupported at this time rle = 0 # Number of dimensions (x,y,z) dim = 3 # X Dimension = width / Y Dimension = height x, y = im.size if im.mode == "L" and y == 1: dim = 1 elif im.mode == "L": dim = 2 # Z Dimension: Number of channels z = len(im.mode) if dim == 1 or dim == 2: z = 1 # assert we've got the right number of bands. if len(im.getbands()) != z: raise ValueError( f"incorrect number of bands in SGI write: {z} vs {len(im.getbands())}" ) # Minimum Byte value pinmin = 0 # Maximum Byte value (255 = 8bits per pixel) pinmax = 255 # Image name (79 characters max, truncated below in write) imgName = os.path.splitext(os.path.basename(filename))[0] imgName = imgName.encode("ascii", "ignore") # Standard representation of pixel in the file colormap = 0 fp.write(struct.pack(">h", magicNumber)) fp.write(o8(rle)) fp.write(o8(bpc)) fp.write(struct.pack(">H", dim)) fp.write(struct.pack(">H", x)) fp.write(struct.pack(">H", y)) fp.write(struct.pack(">H", z)) fp.write(struct.pack(">l", pinmin)) fp.write(struct.pack(">l", pinmax)) fp.write(struct.pack("4s", b"")) # dummy fp.write(struct.pack("79s", imgName)) # truncates to 79 chars fp.write(struct.pack("s", b"")) # force null byte after imgname fp.write(struct.pack(">l", colormap)) fp.write(struct.pack("404s", b"")) # dummy rawmode = "L" if bpc == 2: rawmode = "L;16B" for channel in im.split(): fp.write(channel.tobytes("raw", rawmode, 0, orientation)) if hasattr(fp, "flush"): fp.flush()
null
167,725
from . import Image, ImageFile _handler = None 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 BUFR image handler. :param handler: Handler object. Here is the function: def register_handler(handler): """ Install application-specific BUFR image handler. :param handler: Handler object. """ global _handler _handler = handler
Install application-specific BUFR image handler. :param handler: Handler object.
167,726
from . import Image, ImageFile def _accept(prefix): return prefix[:4] == b"BUFR" or prefix[:4] == b"ZCZC"
null
167,727
from . import Image, ImageFile _handler = None def _save(im, fp, filename): if _handler is None or not hasattr("_handler", "save"): raise OSError("BUFR save handler not installed") _handler.save(im, fp, filename)
null
167,728
from . import Image, ImageFile, ImagePalette from ._binary import o8 _MAGIC = b"P7 332" def _accept(prefix): return prefix[:6] == _MAGIC
null
167,729
import struct from io import BytesIO from . import Image, ImageFile def unpack_565(i): return (((i >> 11) & 0x1F) << 3, ((i >> 5) & 0x3F) << 2, (i & 0x1F) << 3) The provided code snippet includes necessary dependencies for implementing the `decode_dxt1` function. Write a Python function `def decode_dxt1(data, alpha=False)` to solve the following problem: input: one "row" of data (i.e. will produce 4*width pixels) Here is the function: def decode_dxt1(data, alpha=False): """ input: one "row" of data (i.e. will produce 4*width pixels) """ blocks = len(data) // 8 # number of blocks in row ret = (bytearray(), bytearray(), bytearray(), bytearray()) for block in range(blocks): # Decode next 8-byte block. idx = block * 8 color0, color1, bits = struct.unpack_from("<HHI", data, idx) r0, g0, b0 = unpack_565(color0) r1, g1, b1 = unpack_565(color1) # Decode this block into 4x4 pixels # Accumulate the results onto our 4 row accumulators for j in range(4): for i in range(4): # get next control op and generate a pixel control = bits & 3 bits = bits >> 2 a = 0xFF if control == 0: r, g, b = r0, g0, b0 elif control == 1: r, g, b = r1, g1, b1 elif control == 2: if color0 > color1: r = (2 * r0 + r1) // 3 g = (2 * g0 + g1) // 3 b = (2 * b0 + b1) // 3 else: r = (r0 + r1) // 2 g = (g0 + g1) // 2 b = (b0 + b1) // 2 elif control == 3: if color0 > color1: r = (2 * r1 + r0) // 3 g = (2 * g1 + g0) // 3 b = (2 * b1 + b0) // 3 else: r, g, b, a = 0, 0, 0, 0 if alpha: ret[j].extend([r, g, b, a]) else: ret[j].extend([r, g, b]) return ret
input: one "row" of data (i.e. will produce 4*width pixels)
167,730
import struct from io import BytesIO from . import Image, ImageFile def unpack_565(i): return (((i >> 11) & 0x1F) << 3, ((i >> 5) & 0x3F) << 2, (i & 0x1F) << 3) The provided code snippet includes necessary dependencies for implementing the `decode_dxt3` function. Write a Python function `def decode_dxt3(data)` to solve the following problem: input: one "row" of data (i.e. will produce 4*width pixels) Here is the function: def decode_dxt3(data): """ input: one "row" of data (i.e. will produce 4*width pixels) """ blocks = len(data) // 16 # number of blocks in row ret = (bytearray(), bytearray(), bytearray(), bytearray()) for block in range(blocks): idx = block * 16 block = data[idx : idx + 16] # Decode next 16-byte block. bits = struct.unpack_from("<8B", block) color0, color1 = struct.unpack_from("<HH", block, 8) (code,) = struct.unpack_from("<I", block, 12) r0, g0, b0 = unpack_565(color0) r1, g1, b1 = unpack_565(color1) for j in range(4): high = False # Do we want the higher bits? for i in range(4): alphacode_index = (4 * j + i) // 2 a = bits[alphacode_index] if high: high = False a >>= 4 else: high = True a &= 0xF a *= 17 # We get a value between 0 and 15 color_code = (code >> 2 * (4 * j + i)) & 0x03 if color_code == 0: r, g, b = r0, g0, b0 elif color_code == 1: r, g, b = r1, g1, b1 elif color_code == 2: r = (2 * r0 + r1) // 3 g = (2 * g0 + g1) // 3 b = (2 * b0 + b1) // 3 elif color_code == 3: r = (2 * r1 + r0) // 3 g = (2 * g1 + g0) // 3 b = (2 * b1 + b0) // 3 ret[j].extend([r, g, b, a]) return ret
input: one "row" of data (i.e. will produce 4*width pixels)
167,731
import struct from io import BytesIO from . import Image, ImageFile def unpack_565(i): return (((i >> 11) & 0x1F) << 3, ((i >> 5) & 0x3F) << 2, (i & 0x1F) << 3) The provided code snippet includes necessary dependencies for implementing the `decode_dxt5` function. Write a Python function `def decode_dxt5(data)` to solve the following problem: input: one "row" of data (i.e. will produce 4 * width pixels) Here is the function: def decode_dxt5(data): """ input: one "row" of data (i.e. will produce 4 * width pixels) """ blocks = len(data) // 16 # number of blocks in row ret = (bytearray(), bytearray(), bytearray(), bytearray()) for block in range(blocks): idx = block * 16 block = data[idx : idx + 16] # Decode next 16-byte block. a0, a1 = struct.unpack_from("<BB", block) bits = struct.unpack_from("<6B", block, 2) alphacode1 = bits[2] | (bits[3] << 8) | (bits[4] << 16) | (bits[5] << 24) alphacode2 = bits[0] | (bits[1] << 8) color0, color1 = struct.unpack_from("<HH", block, 8) (code,) = struct.unpack_from("<I", block, 12) r0, g0, b0 = unpack_565(color0) r1, g1, b1 = unpack_565(color1) for j in range(4): for i in range(4): # get next control op and generate a pixel alphacode_index = 3 * (4 * j + i) if alphacode_index <= 12: alphacode = (alphacode2 >> alphacode_index) & 0x07 elif alphacode_index == 15: alphacode = (alphacode2 >> 15) | ((alphacode1 << 1) & 0x06) else: # alphacode_index >= 18 and alphacode_index <= 45 alphacode = (alphacode1 >> (alphacode_index - 16)) & 0x07 if alphacode == 0: a = a0 elif alphacode == 1: a = a1 elif a0 > a1: a = ((8 - alphacode) * a0 + (alphacode - 1) * a1) // 7 elif alphacode == 6: a = 0 elif alphacode == 7: a = 255 else: a = ((6 - alphacode) * a0 + (alphacode - 1) * a1) // 5 color_code = (code >> 2 * (4 * j + i)) & 0x03 if color_code == 0: r, g, b = r0, g0, b0 elif color_code == 1: r, g, b = r1, g1, b1 elif color_code == 2: r = (2 * r0 + r1) // 3 g = (2 * g0 + g1) // 3 b = (2 * b0 + b1) // 3 elif color_code == 3: r = (2 * r1 + r0) // 3 g = (2 * g1 + g0) // 3 b = (2 * b1 + b0) // 3 ret[j].extend([r, g, b, a]) return ret
input: one "row" of data (i.e. will produce 4 * width pixels)
167,732
import struct from io import BytesIO from . import Image, ImageFile def _accept(prefix): return prefix[:4] in (b"BLP1", b"BLP2")
null
167,733
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": warnings.warn( "Image categories are deprecated and will be removed in Pillow 10 " "(2023-07-01). Use is_animated instead.", DeprecationWarning, stacklevel=2, ) 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 hasattr(self, "_close__fp"): self._close__fp() 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 hasattr(self, "_close__fp"): self._close__fp() 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 = deferred_error(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.readonly == other.readonly 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_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: raise ValueError("Could not save to PNG for display") from e return b.getvalue() class _ArrayData: def __init__(self, new): self.__array_interface__ = new def __array__(self, dtype=None): # numpy array interface support import numpy as np new = {} shape, typestr = _conv_type_shape(self) new["shape"] = shape new["typestr"] = typestr new["version"] = 3 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() return np.array(self._ArrayData(new), dtype) def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) self.tile = [] 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. :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() # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c data = [] while True: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError(f"encoder error {s} in tobytes") return b"".join(data) 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": raise ValueError("not a bitmap") 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: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data") 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 and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() if mode == "RGBA": mode = "RGB" self.info["transparency"] = arr[3::4] arr = bytes( value for (index, value) in enumerate(arr) if index % 4 != 3 ) palette_length = 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: self.palette.mode = "RGB" self.palette.palette = self.im.getpalette()[: palette_length * 3] if self.im: 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=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 :data:`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. :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:`NONE` or :data:`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:`WEB` or :data:`ADAPTIVE`. :param colors: Number of colors to use for the :data:`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"): raise ValueError("illegal conversion") 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", "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: raise ValueError("Transparency for P mode should be bytes or int") if mode == "P" and 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 # colorspace conversion if dither is None: dither = FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError as e: raise ValueError("illegal conversion") from e new_im = self._new(im) if mode == "P" and 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=1): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`MEDIANCUT` (median cut), :data:`MAXCOVERAGE` (maximum coverage), :data:`FASTOCTREE` (fast octree), :data:`LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`MEDIANCUT` will be used. The exception to this is RGBA images. :data:`MEDIANCUT` and :data:`MAXCOVERAGE` do not support RGBA images, so :data:`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:`NONE` or :data:`FLOYDSTEINBERG` (default). Default: 1 (legacy setting) :returns: A new image """ self.load() if method is None: # defaults: method = MEDIANCUT if self.mode == "RGBA": method = FASTOCTREE if self.mode == "RGBA" and method not in (FASTOCTREE, LIBIMAGEQUANT): # Caller specified an invalid mode. raise ValueError( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) 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() 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. """ 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"): raise TypeError( "filter argument should be ImageFilter.Filter instance or class" ) 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 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): if self._exif is None: self._exif = Exif() 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.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[1]) return self._exif 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): """ Returns the image palette as a list. :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: return list(self.im.getpalette()) except ValueError: return None # no palette 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. 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" or "RGBA" images (in the latter case, 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? raise ValueError("cannot determine region size; use 4-item box") 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 ("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)): raise ValueError("Source must be a tuple") if not isinstance(dest, (list, tuple)): raise ValueError("Destination must be a tuple") if not len(source) in (2, 4): raise ValueError("Source must be a 2 or 4-tuple") if not len(dest) == 2: raise ValueError("Destination must be a 2-tuple") if min(source) < 0: raise ValueError("Source must be non-negative") 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 raise ValueError("point operation not supported for this mode") 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: raise ValueError("illegal image mode") 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"): raise ValueError("illegal image mode") 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" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): raise ValueError("illegal image mode") 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 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 == "P" and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P image value = self.palette.getcolor(value, self) 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"): raise ValueError("illegal image mode") if source_palette is None: if self.mode == "P": self.load() source_palette = self.im.getpalette("RGB")[:768] 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 * 3 : oldPosition * 3 + 3] 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("RGB", palette=mapping_palette * 3) # 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("RGB;L", m_im.palette.tobytes()) m_im = m_im.convert("L") # Internally, we require 768 bytes for a palette. new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b"\x00" m_im.putpalette(new_palette_bytes) m_im.palette = ImagePalette.ImagePalette("RGB", palette=palette_bytes) 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:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`PIL.Image.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`PIL.Image.NEAREST`. Otherwise, the default filter is :py:data:`PIL.Image.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 = NEAREST if type_special else BICUBIC elif resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING): message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (LANCZOS, "Image.LANCZOS"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), (BOX, "Image.BOX"), (HAMMING, "Image.HAMMING"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) if reducing_gap is not None and reducing_gap < 1.0: raise ValueError("reducing_gap must be 1.0 or greater") size = tuple(size) 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 = NEAREST if self.mode in ["LA", "RGBA"] and resample != 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 != 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=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:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.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:`PIL.Image.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(ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose(ROTATE_90 if angle == 90 else 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), 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 isPath(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 isPath(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: raise ValueError(f"unknown file extension: {ext}") from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] if open_fp: 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) finally: # do what we can to clean up 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: raise ValueError(f'The image has no channel "{channel}"') 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=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: Requested size. :param resample: Optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If omitted, it defaults to :py:data:`PIL.Image.BICUBIC`. (was :py:data:`PIL.Image.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 """ x, y = map(math.floor, size) if x >= self.width and y >= self.height: return def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) # preserve aspect ratio 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) ) size = (x, y) box = None if reducing_gap is not None: res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] 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=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. :param method: The transformation method. This is one of :py:data:`PIL.Image.EXTENT` (cut out a rectangular subregion), :py:data:`PIL.Image.AFFINE` (affine transform), :py:data:`PIL.Image.PERSPECTIVE` (perspective transform), :py:data:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or :py:data:`PIL.Image.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.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:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.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:`PIL.Image.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 != 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: raise ValueError("missing method data") 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 == MESH: # list of quads for box, quad in data: im.__transformer(box, self, 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=NEAREST, fill=1): w = box[2] - box[0] h = box[3] - box[1] if method == AFFINE: data = data[0:6] elif method == EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == PERSPECTIVE: data = data[0:8] elif method == QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[0: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: raise ValueError("unknown transformation method") if resample not in (NEAREST, BILINEAR, BICUBIC): if resample in (BOX, HAMMING, LANCZOS): message = { BOX: "Image.BOX", HAMMING: "Image.HAMMING", LANCZOS: "Image.LANCZOS/Image.ANTIALIAS", }[resample] + f" ({resample}) cannot be used." else: message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) image.load() self.load() if image.mode in ("1", "P"): resample = 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:`PIL.Image.FLIP_LEFT_RIGHT`, :py:data:`PIL.Image.FLIP_TOP_BOTTOM`, :py:data:`PIL.Image.ROTATE_90`, :py:data:`PIL.Image.ROTATE_180`, :py:data:`PIL.Image.ROTATE_270`, :py:data:`PIL.Image.TRANSPOSE` or :py:data:`PIL.Image.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: raise ImportError("Qt bindings are not installed") return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `constant` function. Write a Python function `def constant(image, value)` to solve the following problem: Fill a channel with a given grey level. :rtype: :py:class:`~PIL.Image.Image` Here is the function: def constant(image, value): """Fill a channel with a given grey level. :rtype: :py:class:`~PIL.Image.Image` """ return Image.new("L", image.size, value)
Fill a channel with a given grey level. :rtype: :py:class:`~PIL.Image.Image`
167,734
from . import Image The provided code snippet includes necessary dependencies for implementing the `duplicate` function. Write a Python function `def duplicate(image)` to solve the following problem: Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`. :rtype: :py:class:`~PIL.Image.Image` Here is the function: def duplicate(image): """Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`. :rtype: :py:class:`~PIL.Image.Image` """ return image.copy()
Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`. :rtype: :py:class:`~PIL.Image.Image`
167,735
from . import Image The provided code snippet includes necessary dependencies for implementing the `invert` function. Write a Python function `def invert(image)` to solve the following problem: Invert an image (channel). .. code-block:: python out = MAX - image :rtype: :py:class:`~PIL.Image.Image` Here is the function: def invert(image): """ Invert an image (channel). .. code-block:: python out = MAX - image :rtype: :py:class:`~PIL.Image.Image` """ image.load() return image._new(image.im.chop_invert())
Invert an image (channel). .. code-block:: python out = MAX - image :rtype: :py:class:`~PIL.Image.Image`
167,736
from . import Image The provided code snippet includes necessary dependencies for implementing the `lighter` function. Write a Python function `def lighter(image1, image2)` to solve the following problem: Compares the two images, pixel by pixel, and returns a new image containing the lighter values. .. code-block:: python out = max(image1, image2) :rtype: :py:class:`~PIL.Image.Image` Here is the function: def lighter(image1, image2): """ Compares the two images, pixel by pixel, and returns a new image containing the lighter values. .. code-block:: python out = max(image1, image2) :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1.im.chop_lighter(image2.im))
Compares the two images, pixel by pixel, and returns a new image containing the lighter values. .. code-block:: python out = max(image1, image2) :rtype: :py:class:`~PIL.Image.Image`
167,737
from . import Image The provided code snippet includes necessary dependencies for implementing the `darker` function. Write a Python function `def darker(image1, image2)` to solve the following problem: Compares the two images, pixel by pixel, and returns a new image containing the darker values. .. code-block:: python out = min(image1, image2) :rtype: :py:class:`~PIL.Image.Image` Here is the function: def darker(image1, image2): """ Compares the two images, pixel by pixel, and returns a new image containing the darker values. .. code-block:: python out = min(image1, image2) :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1.im.chop_darker(image2.im))
Compares the two images, pixel by pixel, and returns a new image containing the darker values. .. code-block:: python out = min(image1, image2) :rtype: :py:class:`~PIL.Image.Image`
167,738
from . import Image The provided code snippet includes necessary dependencies for implementing the `difference` function. Write a Python function `def difference(image1, image2)` to solve the following problem: Returns the absolute value of the pixel-by-pixel difference between the two images. .. code-block:: python out = abs(image1 - image2) :rtype: :py:class:`~PIL.Image.Image` Here is the function: def difference(image1, image2): """ Returns the absolute value of the pixel-by-pixel difference between the two images. .. code-block:: python out = abs(image1 - image2) :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1.im.chop_difference(image2.im))
Returns the absolute value of the pixel-by-pixel difference between the two images. .. code-block:: python out = abs(image1 - image2) :rtype: :py:class:`~PIL.Image.Image`
167,739
from . import Image The provided code snippet includes necessary dependencies for implementing the `multiply` function. Write a Python function `def multiply(image1, image2)` to solve the following problem: Superimposes two images on top of each other. If you multiply an image with a solid black image, the result is black. If you multiply with a solid white image, the image is unaffected. .. code-block:: python out = image1 * image2 / MAX :rtype: :py:class:`~PIL.Image.Image` Here is the function: def multiply(image1, image2): """ Superimposes two images on top of each other. If you multiply an image with a solid black image, the result is black. If you multiply with a solid white image, the image is unaffected. .. code-block:: python out = image1 * image2 / MAX :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1.im.chop_multiply(image2.im))
Superimposes two images on top of each other. If you multiply an image with a solid black image, the result is black. If you multiply with a solid white image, the image is unaffected. .. code-block:: python out = image1 * image2 / MAX :rtype: :py:class:`~PIL.Image.Image`
167,740
from . import Image The provided code snippet includes necessary dependencies for implementing the `screen` function. Write a Python function `def screen(image1, image2)` to solve the following problem: Superimposes two inverted images on top of each other. .. code-block:: python out = MAX - ((MAX - image1) * (MAX - image2) / MAX) :rtype: :py:class:`~PIL.Image.Image` Here is the function: def screen(image1, image2): """ Superimposes two inverted images on top of each other. .. code-block:: python out = MAX - ((MAX - image1) * (MAX - image2) / MAX) :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1.im.chop_screen(image2.im))
Superimposes two inverted images on top of each other. .. code-block:: python out = MAX - ((MAX - image1) * (MAX - image2) / MAX) :rtype: :py:class:`~PIL.Image.Image`
167,741
from . import Image The provided code snippet includes necessary dependencies for implementing the `soft_light` function. Write a Python function `def soft_light(image1, image2)` to solve the following problem: Superimposes two images on top of each other using the Soft Light algorithm :rtype: :py:class:`~PIL.Image.Image` Here is the function: def soft_light(image1, image2): """ Superimposes two images on top of each other using the Soft Light algorithm :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1.im.chop_soft_light(image2.im))
Superimposes two images on top of each other using the Soft Light algorithm :rtype: :py:class:`~PIL.Image.Image`
167,742
from . import Image The provided code snippet includes necessary dependencies for implementing the `hard_light` function. Write a Python function `def hard_light(image1, image2)` to solve the following problem: Superimposes two images on top of each other using the Hard Light algorithm :rtype: :py:class:`~PIL.Image.Image` Here is the function: def hard_light(image1, image2): """ Superimposes two images on top of each other using the Hard Light algorithm :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1.im.chop_hard_light(image2.im))
Superimposes two images on top of each other using the Hard Light algorithm :rtype: :py:class:`~PIL.Image.Image`
167,743
from . import Image The provided code snippet includes necessary dependencies for implementing the `overlay` function. Write a Python function `def overlay(image1, image2)` to solve the following problem: Superimposes two images on top of each other using the Overlay algorithm :rtype: :py:class:`~PIL.Image.Image` Here is the function: def overlay(image1, image2): """ Superimposes two images on top of each other using the Overlay algorithm :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1.im.chop_overlay(image2.im))
Superimposes two images on top of each other using the Overlay algorithm :rtype: :py:class:`~PIL.Image.Image`
167,744
from . import Image The provided code snippet includes necessary dependencies for implementing the `add` function. Write a Python function `def add(image1, image2, scale=1.0, offset=0)` to solve the following problem: Adds two images, dividing the result by scale and adding the offset. If omitted, scale defaults to 1.0, and offset to 0.0. .. code-block:: python out = ((image1 + image2) / scale + offset) :rtype: :py:class:`~PIL.Image.Image` Here is the function: def add(image1, image2, scale=1.0, offset=0): """ Adds two images, dividing the result by scale and adding the offset. If omitted, scale defaults to 1.0, and offset to 0.0. .. code-block:: python out = ((image1 + image2) / scale + offset) :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1.im.chop_add(image2.im, scale, offset))
Adds two images, dividing the result by scale and adding the offset. If omitted, scale defaults to 1.0, and offset to 0.0. .. code-block:: python out = ((image1 + image2) / scale + offset) :rtype: :py:class:`~PIL.Image.Image`
167,745
from . import Image The provided code snippet includes necessary dependencies for implementing the `subtract` function. Write a Python function `def subtract(image1, image2, scale=1.0, offset=0)` to solve the following problem: Subtracts two images, dividing the result by scale and adding the offset. If omitted, scale defaults to 1.0, and offset to 0.0. .. code-block:: python out = ((image1 - image2) / scale + offset) :rtype: :py:class:`~PIL.Image.Image` Here is the function: def subtract(image1, image2, scale=1.0, offset=0): """ Subtracts two images, dividing the result by scale and adding the offset. If omitted, scale defaults to 1.0, and offset to 0.0. .. code-block:: python out = ((image1 - image2) / scale + offset) :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1.im.chop_subtract(image2.im, scale, offset))
Subtracts two images, dividing the result by scale and adding the offset. If omitted, scale defaults to 1.0, and offset to 0.0. .. code-block:: python out = ((image1 - image2) / scale + offset) :rtype: :py:class:`~PIL.Image.Image`
167,746
from . import Image The provided code snippet includes necessary dependencies for implementing the `add_modulo` function. Write a Python function `def add_modulo(image1, image2)` to solve the following problem: Add two images, without clipping the result. .. code-block:: python out = ((image1 + image2) % MAX) :rtype: :py:class:`~PIL.Image.Image` Here is the function: def add_modulo(image1, image2): """Add two images, without clipping the result. .. code-block:: python out = ((image1 + image2) % MAX) :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1.im.chop_add_modulo(image2.im))
Add two images, without clipping the result. .. code-block:: python out = ((image1 + image2) % MAX) :rtype: :py:class:`~PIL.Image.Image`
167,747
from . import Image The provided code snippet includes necessary dependencies for implementing the `logical_and` function. Write a Python function `def logical_and(image1, image2)` to solve the following problem: Logical AND between two images. Both of the images must have mode "1". If you would like to perform a logical AND on an image with a mode other than "1", try :py:meth:`~PIL.ImageChops.multiply` instead, using a black-and-white mask as the second image. .. code-block:: python out = ((image1 and image2) % MAX) :rtype: :py:class:`~PIL.Image.Image` Here is the function: def logical_and(image1, image2): """Logical AND between two images. Both of the images must have mode "1". If you would like to perform a logical AND on an image with a mode other than "1", try :py:meth:`~PIL.ImageChops.multiply` instead, using a black-and-white mask as the second image. .. code-block:: python out = ((image1 and image2) % MAX) :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1.im.chop_and(image2.im))
Logical AND between two images. Both of the images must have mode "1". If you would like to perform a logical AND on an image with a mode other than "1", try :py:meth:`~PIL.ImageChops.multiply` instead, using a black-and-white mask as the second image. .. code-block:: python out = ((image1 and image2) % MAX) :rtype: :py:class:`~PIL.Image.Image`
167,748
from . import Image The provided code snippet includes necessary dependencies for implementing the `logical_or` function. Write a Python function `def logical_or(image1, image2)` to solve the following problem: Logical OR between two images. Both of the images must have mode "1". .. code-block:: python out = ((image1 or image2) % MAX) :rtype: :py:class:`~PIL.Image.Image` Here is the function: def logical_or(image1, image2): """Logical OR between two images. Both of the images must have mode "1". .. code-block:: python out = ((image1 or image2) % MAX) :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1.im.chop_or(image2.im))
Logical OR between two images. Both of the images must have mode "1". .. code-block:: python out = ((image1 or image2) % MAX) :rtype: :py:class:`~PIL.Image.Image`
167,749
from . import Image The provided code snippet includes necessary dependencies for implementing the `logical_xor` function. Write a Python function `def logical_xor(image1, image2)` to solve the following problem: Logical XOR between two images. Both of the images must have mode "1". .. code-block:: python out = ((bool(image1) != bool(image2)) % MAX) :rtype: :py:class:`~PIL.Image.Image` Here is the function: def logical_xor(image1, image2): """Logical XOR between two images. Both of the images must have mode "1". .. code-block:: python out = ((bool(image1) != bool(image2)) % MAX) :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1.im.chop_xor(image2.im))
Logical XOR between two images. Both of the images must have mode "1". .. code-block:: python out = ((bool(image1) != bool(image2)) % MAX) :rtype: :py:class:`~PIL.Image.Image`
167,750
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": warnings.warn( "Image categories are deprecated and will be removed in Pillow 10 " "(2023-07-01). Use is_animated instead.", DeprecationWarning, stacklevel=2, ) 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 hasattr(self, "_close__fp"): self._close__fp() 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 hasattr(self, "_close__fp"): self._close__fp() 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 = deferred_error(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.readonly == other.readonly 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_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: raise ValueError("Could not save to PNG for display") from e return b.getvalue() class _ArrayData: def __init__(self, new): self.__array_interface__ = new def __array__(self, dtype=None): # numpy array interface support import numpy as np new = {} shape, typestr = _conv_type_shape(self) new["shape"] = shape new["typestr"] = typestr new["version"] = 3 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() return np.array(self._ArrayData(new), dtype) def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) self.tile = [] 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. :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() # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c data = [] while True: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError(f"encoder error {s} in tobytes") return b"".join(data) 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": raise ValueError("not a bitmap") 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: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data") 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 and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() if mode == "RGBA": mode = "RGB" self.info["transparency"] = arr[3::4] arr = bytes( value for (index, value) in enumerate(arr) if index % 4 != 3 ) palette_length = 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: self.palette.mode = "RGB" self.palette.palette = self.im.getpalette()[: palette_length * 3] if self.im: 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=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 :data:`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. :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:`NONE` or :data:`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:`WEB` or :data:`ADAPTIVE`. :param colors: Number of colors to use for the :data:`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"): raise ValueError("illegal conversion") 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", "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: raise ValueError("Transparency for P mode should be bytes or int") if mode == "P" and 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 # colorspace conversion if dither is None: dither = FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError as e: raise ValueError("illegal conversion") from e new_im = self._new(im) if mode == "P" and 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=1): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`MEDIANCUT` (median cut), :data:`MAXCOVERAGE` (maximum coverage), :data:`FASTOCTREE` (fast octree), :data:`LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`MEDIANCUT` will be used. The exception to this is RGBA images. :data:`MEDIANCUT` and :data:`MAXCOVERAGE` do not support RGBA images, so :data:`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:`NONE` or :data:`FLOYDSTEINBERG` (default). Default: 1 (legacy setting) :returns: A new image """ self.load() if method is None: # defaults: method = MEDIANCUT if self.mode == "RGBA": method = FASTOCTREE if self.mode == "RGBA" and method not in (FASTOCTREE, LIBIMAGEQUANT): # Caller specified an invalid mode. raise ValueError( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) 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() 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. """ 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"): raise TypeError( "filter argument should be ImageFilter.Filter instance or class" ) 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 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): if self._exif is None: self._exif = Exif() 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.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[1]) return self._exif 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): """ Returns the image palette as a list. :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: return list(self.im.getpalette()) except ValueError: return None # no palette 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. 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" or "RGBA" images (in the latter case, 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? raise ValueError("cannot determine region size; use 4-item box") 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 ("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)): raise ValueError("Source must be a tuple") if not isinstance(dest, (list, tuple)): raise ValueError("Destination must be a tuple") if not len(source) in (2, 4): raise ValueError("Source must be a 2 or 4-tuple") if not len(dest) == 2: raise ValueError("Destination must be a 2-tuple") if min(source) < 0: raise ValueError("Source must be non-negative") 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 raise ValueError("point operation not supported for this mode") 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: raise ValueError("illegal image mode") 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"): raise ValueError("illegal image mode") 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" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): raise ValueError("illegal image mode") 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 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 == "P" and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P image value = self.palette.getcolor(value, self) 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"): raise ValueError("illegal image mode") if source_palette is None: if self.mode == "P": self.load() source_palette = self.im.getpalette("RGB")[:768] 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 * 3 : oldPosition * 3 + 3] 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("RGB", palette=mapping_palette * 3) # 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("RGB;L", m_im.palette.tobytes()) m_im = m_im.convert("L") # Internally, we require 768 bytes for a palette. new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b"\x00" m_im.putpalette(new_palette_bytes) m_im.palette = ImagePalette.ImagePalette("RGB", palette=palette_bytes) 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:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`PIL.Image.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`PIL.Image.NEAREST`. Otherwise, the default filter is :py:data:`PIL.Image.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 = NEAREST if type_special else BICUBIC elif resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING): message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (LANCZOS, "Image.LANCZOS"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), (BOX, "Image.BOX"), (HAMMING, "Image.HAMMING"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) if reducing_gap is not None and reducing_gap < 1.0: raise ValueError("reducing_gap must be 1.0 or greater") size = tuple(size) 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 = NEAREST if self.mode in ["LA", "RGBA"] and resample != 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 != 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=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:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.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:`PIL.Image.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(ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose(ROTATE_90 if angle == 90 else 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), 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 isPath(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 isPath(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: raise ValueError(f"unknown file extension: {ext}") from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] if open_fp: 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) finally: # do what we can to clean up 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: raise ValueError(f'The image has no channel "{channel}"') 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=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: Requested size. :param resample: Optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If omitted, it defaults to :py:data:`PIL.Image.BICUBIC`. (was :py:data:`PIL.Image.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 """ x, y = map(math.floor, size) if x >= self.width and y >= self.height: return def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) # preserve aspect ratio 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) ) size = (x, y) box = None if reducing_gap is not None: res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] 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=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. :param method: The transformation method. This is one of :py:data:`PIL.Image.EXTENT` (cut out a rectangular subregion), :py:data:`PIL.Image.AFFINE` (affine transform), :py:data:`PIL.Image.PERSPECTIVE` (perspective transform), :py:data:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or :py:data:`PIL.Image.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.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:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.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:`PIL.Image.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 != 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: raise ValueError("missing method data") 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 == MESH: # list of quads for box, quad in data: im.__transformer(box, self, 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=NEAREST, fill=1): w = box[2] - box[0] h = box[3] - box[1] if method == AFFINE: data = data[0:6] elif method == EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == PERSPECTIVE: data = data[0:8] elif method == QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[0: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: raise ValueError("unknown transformation method") if resample not in (NEAREST, BILINEAR, BICUBIC): if resample in (BOX, HAMMING, LANCZOS): message = { BOX: "Image.BOX", HAMMING: "Image.HAMMING", LANCZOS: "Image.LANCZOS/Image.ANTIALIAS", }[resample] + f" ({resample}) cannot be used." else: message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) image.load() self.load() if image.mode in ("1", "P"): resample = 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:`PIL.Image.FLIP_LEFT_RIGHT`, :py:data:`PIL.Image.FLIP_TOP_BOTTOM`, :py:data:`PIL.Image.ROTATE_90`, :py:data:`PIL.Image.ROTATE_180`, :py:data:`PIL.Image.ROTATE_270`, :py:data:`PIL.Image.TRANSPOSE` or :py:data:`PIL.Image.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: raise ImportError("Qt bindings are not installed") return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `composite` function. Write a Python function `def composite(image1, image2, mask)` to solve the following problem: Create composite using transparency mask. Alias for :py:func:`PIL.Image.composite`. :rtype: :py:class:`~PIL.Image.Image` Here is the function: def composite(image1, image2, mask): """Create composite using transparency mask. Alias for :py:func:`PIL.Image.composite`. :rtype: :py:class:`~PIL.Image.Image` """ return Image.composite(image1, image2, mask)
Create composite using transparency mask. Alias for :py:func:`PIL.Image.composite`. :rtype: :py:class:`~PIL.Image.Image`
167,751
from . import Image, ImageFile _handler = None 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 HDF5 image handler. :param handler: Handler object. Here is the function: def register_handler(handler): """ Install application-specific HDF5 image handler. :param handler: Handler object. """ global _handler _handler = handler
Install application-specific HDF5 image handler. :param handler: Handler object.
167,752
from . import Image, ImageFile def _accept(prefix): return prefix[:8] == b"\x89HDF\r\n\x1a\n"
null
167,753
from . import Image, ImageFile _handler = None def _save(im, fp, filename): if _handler is None or not hasattr("_handler", "save"): raise OSError("HDF5 save handler not installed") _handler.save(im, fp, filename)
null
167,754
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath def __getattr__(name): categories = {"NORMAL": 0, "SEQUENCE": 1, "CONTAINER": 2} if name in categories: warnings.warn( "Image categories are deprecated and will be removed in Pillow 10 " "(2023-07-01). Use is_animated instead.", DeprecationWarning, stacklevel=2, ) return categories[name] raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
null
167,755
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath if hasattr(core, "DEFAULT_STRATEGY"): DEFAULT_STRATEGY = core.DEFAULT_STRATEGY FILTERED = core.FILTERED HUFFMAN_ONLY = core.HUFFMAN_ONLY RLE = core.RLE FIXED = core.FIXED The provided code snippet includes necessary dependencies for implementing the `isImageType` function. Write a Python function `def isImageType(t)` to solve the following problem: Checks if an object is an image object. .. warning:: This function is for internal use only. :param t: object to check if it's an image :returns: True if the object is an image Here is the function: def isImageType(t): """ Checks if an object is an image object. .. warning:: This function is for internal use only. :param t: object to check if it's an image :returns: True if the object is an image """ return hasattr(t, "im")
Checks if an object is an image object. .. warning:: This function is for internal use only. :param t: object to check if it's an image :returns: True if the object is an image
167,756
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath _MODE_CONV = { # official modes "1": ("|b1", None), # Bits need to be extended to bytes "L": ("|u1", None), "LA": ("|u1", 2), "I": (_ENDIAN + "i4", None), "F": (_ENDIAN + "f4", None), "P": ("|u1", None), "RGB": ("|u1", 3), "RGBX": ("|u1", 4), "RGBA": ("|u1", 4), "CMYK": ("|u1", 4), "YCbCr": ("|u1", 3), "LAB": ("|u1", 3), # UNDONE - unsigned |u1i1i1 "HSV": ("|u1", 3), # I;16 == I;16L, and I;32 == I;32L "I;16": ("<u2", None), "I;16B": (">u2", None), "I;16L": ("<u2", None), "I;16S": ("<i2", None), "I;16BS": (">i2", None), "I;16LS": ("<i2", None), "I;32": ("<u4", None), "I;32B": (">u4", None), "I;32L": ("<u4", None), "I;32S": ("<i4", None), "I;32BS": (">i4", None), "I;32LS": ("<i4", None), } def _conv_type_shape(im): typ, extra = _MODE_CONV[im.mode] if extra is None: return (im.size[1], im.size[0]), typ else: return (im.size[1], im.size[0], extra), typ
null
167,757
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath The provided code snippet includes necessary dependencies for implementing the `getmodebandnames` function. Write a Python function `def getmodebandnames(mode)` to solve the following problem: Gets a list of individual band names. Given a mode, this function returns a tuple containing the names of individual bands (use :py:method:`~PIL.Image.getmodetype` to get the mode used to store each individual band. :param mode: Input mode. :returns: A tuple containing band names. The length of the tuple gives the number of bands in an image of the given mode. :exception KeyError: If the input mode was not a standard mode. Here is the function: def getmodebandnames(mode): """ Gets a list of individual band names. Given a mode, this function returns a tuple containing the names of individual bands (use :py:method:`~PIL.Image.getmodetype` to get the mode used to store each individual band. :param mode: Input mode. :returns: A tuple containing band names. The length of the tuple gives the number of bands in an image of the given mode. :exception KeyError: If the input mode was not a standard mode. """ return ImageMode.getmode(mode).bands
Gets a list of individual band names. Given a mode, this function returns a tuple containing the names of individual bands (use :py:method:`~PIL.Image.getmodetype` to get the mode used to store each individual band. :param mode: Input mode. :returns: A tuple containing band names. The length of the tuple gives the number of bands in an image of the given mode. :exception KeyError: If the input mode was not a standard mode.
167,758
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath DECODERS = {} def _getdecoder(mode, decoder_name, args, extra=()): # tweak arguments if args is None: args = () elif not isinstance(args, tuple): args = (args,) try: decoder = DECODERS[decoder_name] except KeyError: pass else: return decoder(mode, *args + extra) try: # get decoder decoder = getattr(core, decoder_name + "_decoder") except AttributeError as e: raise OSError(f"decoder {decoder_name} not available") from e return decoder(mode, *args + extra)
null
167,759
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath class _E: def __init__(self, data): def __add__(self, other): def __mul__(self, other): def coerce_e(value): return value if isinstance(value, _E) else _E(value)
null
167,760
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath class _E: def __init__(self, data): self.data = data def __add__(self, other): return _E((self.data, "__add__", coerce_e(other).data)) def __mul__(self, other): return _E((self.data, "__mul__", coerce_e(other).data)) def _getscaleoffset(expr): stub = ["stub"] data = expr(_E(stub)).data try: (a, b, c) = data # simplified syntax if a is stub and b == "__mul__" and isinstance(c, numbers.Number): return c, 0.0 if a is stub and b == "__add__" and isinstance(c, numbers.Number): return 1.0, c except TypeError: pass try: ((a, b, c), d, e) = data # full syntax if ( a is stub and b == "__mul__" and isinstance(c, numbers.Number) and d == "__add__" and isinstance(e, numbers.Number) ): return c, e except TypeError: pass raise ValueError("illegal expression")
null
167,761
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath 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": warnings.warn( "Image categories are deprecated and will be removed in Pillow 10 " "(2023-07-01). Use is_animated instead.", DeprecationWarning, stacklevel=2, ) 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 hasattr(self, "_close__fp"): self._close__fp() 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 hasattr(self, "_close__fp"): self._close__fp() 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 = deferred_error(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.readonly == other.readonly 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_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: raise ValueError("Could not save to PNG for display") from e return b.getvalue() class _ArrayData: def __init__(self, new): self.__array_interface__ = new def __array__(self, dtype=None): # numpy array interface support import numpy as np new = {} shape, typestr = _conv_type_shape(self) new["shape"] = shape new["typestr"] = typestr new["version"] = 3 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() return np.array(self._ArrayData(new), dtype) def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) self.tile = [] 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. :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() # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c data = [] while True: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError(f"encoder error {s} in tobytes") return b"".join(data) 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": raise ValueError("not a bitmap") 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: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data") 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 and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() if mode == "RGBA": mode = "RGB" self.info["transparency"] = arr[3::4] arr = bytes( value for (index, value) in enumerate(arr) if index % 4 != 3 ) palette_length = 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: self.palette.mode = "RGB" self.palette.palette = self.im.getpalette()[: palette_length * 3] if self.im: 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=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 :data:`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. :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:`NONE` or :data:`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:`WEB` or :data:`ADAPTIVE`. :param colors: Number of colors to use for the :data:`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"): raise ValueError("illegal conversion") 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", "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: raise ValueError("Transparency for P mode should be bytes or int") if mode == "P" and 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 # colorspace conversion if dither is None: dither = FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError as e: raise ValueError("illegal conversion") from e new_im = self._new(im) if mode == "P" and 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=1): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`MEDIANCUT` (median cut), :data:`MAXCOVERAGE` (maximum coverage), :data:`FASTOCTREE` (fast octree), :data:`LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`MEDIANCUT` will be used. The exception to this is RGBA images. :data:`MEDIANCUT` and :data:`MAXCOVERAGE` do not support RGBA images, so :data:`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:`NONE` or :data:`FLOYDSTEINBERG` (default). Default: 1 (legacy setting) :returns: A new image """ self.load() if method is None: # defaults: method = MEDIANCUT if self.mode == "RGBA": method = FASTOCTREE if self.mode == "RGBA" and method not in (FASTOCTREE, LIBIMAGEQUANT): # Caller specified an invalid mode. raise ValueError( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) 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() 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. """ 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"): raise TypeError( "filter argument should be ImageFilter.Filter instance or class" ) 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 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): if self._exif is None: self._exif = Exif() 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.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[1]) return self._exif 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): """ Returns the image palette as a list. :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: return list(self.im.getpalette()) except ValueError: return None # no palette 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. 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" or "RGBA" images (in the latter case, 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? raise ValueError("cannot determine region size; use 4-item box") 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 ("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)): raise ValueError("Source must be a tuple") if not isinstance(dest, (list, tuple)): raise ValueError("Destination must be a tuple") if not len(source) in (2, 4): raise ValueError("Source must be a 2 or 4-tuple") if not len(dest) == 2: raise ValueError("Destination must be a 2-tuple") if min(source) < 0: raise ValueError("Source must be non-negative") 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 raise ValueError("point operation not supported for this mode") 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: raise ValueError("illegal image mode") 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"): raise ValueError("illegal image mode") 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" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): raise ValueError("illegal image mode") 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 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 == "P" and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P image value = self.palette.getcolor(value, self) 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"): raise ValueError("illegal image mode") if source_palette is None: if self.mode == "P": self.load() source_palette = self.im.getpalette("RGB")[:768] 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 * 3 : oldPosition * 3 + 3] 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("RGB", palette=mapping_palette * 3) # 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("RGB;L", m_im.palette.tobytes()) m_im = m_im.convert("L") # Internally, we require 768 bytes for a palette. new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b"\x00" m_im.putpalette(new_palette_bytes) m_im.palette = ImagePalette.ImagePalette("RGB", palette=palette_bytes) 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:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`PIL.Image.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`PIL.Image.NEAREST`. Otherwise, the default filter is :py:data:`PIL.Image.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 = NEAREST if type_special else BICUBIC elif resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING): message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (LANCZOS, "Image.LANCZOS"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), (BOX, "Image.BOX"), (HAMMING, "Image.HAMMING"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) if reducing_gap is not None and reducing_gap < 1.0: raise ValueError("reducing_gap must be 1.0 or greater") size = tuple(size) 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 = NEAREST if self.mode in ["LA", "RGBA"] and resample != 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 != 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=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:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.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:`PIL.Image.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(ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose(ROTATE_90 if angle == 90 else 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), 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 isPath(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 isPath(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: raise ValueError(f"unknown file extension: {ext}") from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] if open_fp: 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) finally: # do what we can to clean up 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: raise ValueError(f'The image has no channel "{channel}"') 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=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: Requested size. :param resample: Optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If omitted, it defaults to :py:data:`PIL.Image.BICUBIC`. (was :py:data:`PIL.Image.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 """ x, y = map(math.floor, size) if x >= self.width and y >= self.height: return def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) # preserve aspect ratio 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) ) size = (x, y) box = None if reducing_gap is not None: res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] 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=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. :param method: The transformation method. This is one of :py:data:`PIL.Image.EXTENT` (cut out a rectangular subregion), :py:data:`PIL.Image.AFFINE` (affine transform), :py:data:`PIL.Image.PERSPECTIVE` (perspective transform), :py:data:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or :py:data:`PIL.Image.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.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:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.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:`PIL.Image.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 != 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: raise ValueError("missing method data") 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 == MESH: # list of quads for box, quad in data: im.__transformer(box, self, 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=NEAREST, fill=1): w = box[2] - box[0] h = box[3] - box[1] if method == AFFINE: data = data[0:6] elif method == EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == PERSPECTIVE: data = data[0:8] elif method == QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[0: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: raise ValueError("unknown transformation method") if resample not in (NEAREST, BILINEAR, BICUBIC): if resample in (BOX, HAMMING, LANCZOS): message = { BOX: "Image.BOX", HAMMING: "Image.HAMMING", LANCZOS: "Image.LANCZOS/Image.ANTIALIAS", }[resample] + f" ({resample}) cannot be used." else: message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) image.load() self.load() if image.mode in ("1", "P"): resample = 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:`PIL.Image.FLIP_LEFT_RIGHT`, :py:data:`PIL.Image.FLIP_TOP_BOTTOM`, :py:data:`PIL.Image.ROTATE_90`, :py:data:`PIL.Image.ROTATE_180`, :py:data:`PIL.Image.ROTATE_270`, :py:data:`PIL.Image.TRANSPOSE` or :py:data:`PIL.Image.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: raise ImportError("Qt bindings are not installed") return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `_wedge` function. Write a Python function `def _wedge()` to solve the following problem: Create greyscale wedge (for debugging only) Here is the function: def _wedge(): """Create greyscale wedge (for debugging only)""" return Image()._new(core.wedge("L"))
Create greyscale wedge (for debugging only)
167,762
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath if hasattr(core, "DEFAULT_STRATEGY"): DEFAULT_STRATEGY = core.DEFAULT_STRATEGY FILTERED = core.FILTERED HUFFMAN_ONLY = core.HUFFMAN_ONLY RLE = core.RLE FIXED = core.FIXED def frombuffer(mode, size, data, decoder_name="raw", *args): """ Creates an image memory referencing pixel data in a byte buffer. This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data in the byte buffer, where possible. This means that changes to the original buffer object are reflected in this image). Not all modes can share memory; supported modes include "L", "RGBX", "RGBA", and "CMYK". Note that this function decodes pixel data only, not entire images. If you have an entire image file in a string, wrap it in a :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load it. In the current version, the default parameters used for the "raw" decoder differs from that used for :py:func:`~PIL.Image.frombytes`. This is a bug, and will probably be fixed in a future release. The current release issues a warning if you do this; to disable the warning, you should provide the full set of parameters. See below for details. :param mode: The image mode. See: :ref:`concept-modes`. :param size: The image size. :param data: A bytes or other buffer object containing raw data for the given mode. :param decoder_name: What decoder to use. :param args: Additional parameters for the given decoder. For the default encoder ("raw"), it's recommended that you provide the full set of parameters:: frombuffer(mode, size, data, "raw", mode, 0, 1) :returns: An :py:class:`~PIL.Image.Image` object. .. versionadded:: 1.1.4 """ _check_size(size) # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if decoder_name == "raw": if args == (): args = mode, 0, 1 if args[0] in _MAPMODES: im = new(mode, (1, 1)) im = im._new(core.map_buffer(data, size, decoder_name, 0, args)) im.readonly = 1 return im return frombytes(mode, size, data, decoder_name, args) _fromarray_typemap = { # (shape, typestr) => mode, rawmode # first two members of shape are set to one ((1, 1), "|b1"): ("1", "1;8"), ((1, 1), "|u1"): ("L", "L"), ((1, 1), "|i1"): ("I", "I;8"), ((1, 1), "<u2"): ("I", "I;16"), ((1, 1), ">u2"): ("I", "I;16B"), ((1, 1), "<i2"): ("I", "I;16S"), ((1, 1), ">i2"): ("I", "I;16BS"), ((1, 1), "<u4"): ("I", "I;32"), ((1, 1), ">u4"): ("I", "I;32B"), ((1, 1), "<i4"): ("I", "I;32S"), ((1, 1), ">i4"): ("I", "I;32BS"), ((1, 1), "<f4"): ("F", "F;32F"), ((1, 1), ">f4"): ("F", "F;32BF"), ((1, 1), "<f8"): ("F", "F;64F"), ((1, 1), ">f8"): ("F", "F;64BF"), ((1, 1, 2), "|u1"): ("LA", "LA"), ((1, 1, 3), "|u1"): ("RGB", "RGB"), ((1, 1, 4), "|u1"): ("RGBA", "RGBA"), } _fromarray_typemap[((1, 1), _ENDIAN + "i4")] = ("I", "I") _fromarray_typemap[((1, 1), _ENDIAN + "f4")] = ("F", "F") The provided code snippet includes necessary dependencies for implementing the `fromarray` function. Write a Python function `def fromarray(obj, mode=None)` to solve the following problem: Creates an image memory from an object exporting the array interface (using the buffer protocol). If ``obj`` is not contiguous, then the ``tobytes`` method is called and :py:func:`~PIL.Image.frombuffer` is used. If you have an image in NumPy:: from PIL import Image import numpy as np im = Image.open("hopper.jpg") a = np.asarray(im) Then this can be used to convert it to a Pillow image:: im = Image.fromarray(a) :param obj: Object with array interface :param mode: Optional mode to use when reading ``obj``. Will be determined from type if ``None``. This will not be used to convert the data after reading, but will be used to change how the data is read:: from PIL import Image import numpy as np a = np.full((1, 1), 300) im = Image.fromarray(a, mode="L") im.getpixel((0, 0)) # 44 im = Image.fromarray(a, mode="RGB") im.getpixel((0, 0)) # (44, 1, 0) See: :ref:`concept-modes` for general information about modes. :returns: An image object. .. versionadded:: 1.1.6 Here is the function: def fromarray(obj, mode=None): """ Creates an image memory from an object exporting the array interface (using the buffer protocol). If ``obj`` is not contiguous, then the ``tobytes`` method is called and :py:func:`~PIL.Image.frombuffer` is used. If you have an image in NumPy:: from PIL import Image import numpy as np im = Image.open("hopper.jpg") a = np.asarray(im) Then this can be used to convert it to a Pillow image:: im = Image.fromarray(a) :param obj: Object with array interface :param mode: Optional mode to use when reading ``obj``. Will be determined from type if ``None``. This will not be used to convert the data after reading, but will be used to change how the data is read:: from PIL import Image import numpy as np a = np.full((1, 1), 300) im = Image.fromarray(a, mode="L") im.getpixel((0, 0)) # 44 im = Image.fromarray(a, mode="RGB") im.getpixel((0, 0)) # (44, 1, 0) See: :ref:`concept-modes` for general information about modes. :returns: An image object. .. versionadded:: 1.1.6 """ arr = obj.__array_interface__ shape = arr["shape"] ndim = len(shape) strides = arr.get("strides", None) if mode is None: try: typekey = (1, 1) + shape[2:], arr["typestr"] except KeyError as e: raise TypeError("Cannot handle this data type") from e try: mode, rawmode = _fromarray_typemap[typekey] except KeyError as e: raise TypeError("Cannot handle this data type: %s, %s" % typekey) from e else: rawmode = mode if mode in ["1", "L", "I", "P", "F"]: ndmax = 2 elif mode == "RGB": ndmax = 3 else: ndmax = 4 if ndim > ndmax: raise ValueError(f"Too many dimensions: {ndim} > {ndmax}.") size = 1 if ndim == 1 else shape[1], shape[0] if strides is not None: if hasattr(obj, "tobytes"): obj = obj.tobytes() else: obj = obj.tostring() return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)
Creates an image memory from an object exporting the array interface (using the buffer protocol). If ``obj`` is not contiguous, then the ``tobytes`` method is called and :py:func:`~PIL.Image.frombuffer` is used. If you have an image in NumPy:: from PIL import Image import numpy as np im = Image.open("hopper.jpg") a = np.asarray(im) Then this can be used to convert it to a Pillow image:: im = Image.fromarray(a) :param obj: Object with array interface :param mode: Optional mode to use when reading ``obj``. Will be determined from type if ``None``. This will not be used to convert the data after reading, but will be used to change how the data is read:: from PIL import Image import numpy as np a = np.full((1, 1), 300) im = Image.fromarray(a, mode="L") im.getpixel((0, 0)) # 44 im = Image.fromarray(a, mode="RGB") im.getpixel((0, 0)) # (44, 1, 0) See: :ref:`concept-modes` for general information about modes. :returns: An image object. .. versionadded:: 1.1.6
167,763
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath The provided code snippet includes necessary dependencies for implementing the `fromqpixmap` function. Write a Python function `def fromqpixmap(im)` to solve the following problem: Creates an image instance from a QPixmap image Here is the function: def fromqpixmap(im): """Creates an image instance from a QPixmap image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.fromqpixmap(im)
Creates an image instance from a QPixmap image
167,764
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath The provided code snippet includes necessary dependencies for implementing the `alpha_composite` function. Write a Python function `def alpha_composite(im1, im2)` to solve the following problem: Alpha composite im2 over im1. :param im1: The first image. Must have mode RGBA. :param im2: The second image. Must have mode RGBA, and the same size as the first image. :returns: An :py:class:`~PIL.Image.Image` object. Here is the function: def alpha_composite(im1, im2): """ Alpha composite im2 over im1. :param im1: The first image. Must have mode RGBA. :param im2: The second image. Must have mode RGBA, and the same size as the first image. :returns: An :py:class:`~PIL.Image.Image` object. """ im1.load() im2.load() return im1._new(core.alpha_composite(im1.im, im2.im))
Alpha composite im2 over im1. :param im1: The first image. Must have mode RGBA. :param im2: The second image. Must have mode RGBA, and the same size as the first image. :returns: An :py:class:`~PIL.Image.Image` object.