2010-07-31 06:52:47 +04:00
|
|
|
#
|
|
|
|
# The Python Imaging Library.
|
|
|
|
# $Id$
|
|
|
|
#
|
|
|
|
# the Image class wrapper
|
|
|
|
#
|
|
|
|
# partial release history:
|
|
|
|
# 1995-09-09 fl Created
|
|
|
|
# 1996-03-11 fl PIL release 0.0 (proof of concept)
|
|
|
|
# 1996-04-30 fl PIL release 0.1b1
|
|
|
|
# 1999-07-28 fl PIL release 1.0 final
|
|
|
|
# 2000-06-07 fl PIL release 1.1
|
|
|
|
# 2000-10-20 fl PIL release 1.1.1
|
|
|
|
# 2001-05-07 fl PIL release 1.1.2
|
|
|
|
# 2002-03-15 fl PIL release 1.1.3
|
|
|
|
# 2003-05-10 fl PIL release 1.1.4
|
|
|
|
# 2005-03-28 fl PIL release 1.1.5
|
|
|
|
# 2006-12-02 fl PIL release 1.1.6
|
|
|
|
# 2009-11-15 fl PIL release 1.1.7
|
|
|
|
#
|
|
|
|
# Copyright (c) 1997-2009 by Secret Labs AB. All rights reserved.
|
|
|
|
# Copyright (c) 1995-2009 by Fredrik Lundh.
|
|
|
|
#
|
|
|
|
# See the README file for information on usage and redistribution.
|
|
|
|
#
|
|
|
|
|
2019-07-06 23:40:53 +03:00
|
|
|
import atexit
|
2019-09-26 15:12:28 +03:00
|
|
|
import builtins
|
2019-07-06 23:40:53 +03:00
|
|
|
import io
|
|
|
|
import logging
|
|
|
|
import math
|
|
|
|
import os
|
2021-06-30 04:20:55 +03:00
|
|
|
import re
|
2019-07-06 23:40:53 +03:00
|
|
|
import struct
|
|
|
|
import sys
|
2019-10-07 16:28:36 +03:00
|
|
|
import tempfile
|
2019-07-06 23:40:53 +03:00
|
|
|
import warnings
|
2019-09-26 15:12:28 +03:00
|
|
|
from collections.abc import Callable, MutableMapping
|
2022-01-15 01:02:31 +03:00
|
|
|
from enum import IntEnum
|
2019-09-26 15:12:28 +03:00
|
|
|
from pathlib import Path
|
2019-07-06 23:40:53 +03:00
|
|
|
|
2021-06-30 04:28:00 +03:00
|
|
|
try:
|
|
|
|
import defusedxml.ElementTree as ElementTree
|
|
|
|
except ImportError:
|
|
|
|
ElementTree = None
|
|
|
|
|
2019-01-29 20:10:52 +03:00
|
|
|
# VERSION was removed in Pillow 6.0.0.
|
2021-10-18 03:05:53 +03:00
|
|
|
# PILLOW_VERSION was removed in Pillow 9.0.0.
|
2018-04-22 22:00:39 +03:00
|
|
|
# Use __version__ instead.
|
2022-11-28 00:39:56 +03:00
|
|
|
from . import (
|
|
|
|
ExifTags,
|
|
|
|
ImageMode,
|
|
|
|
TiffTags,
|
|
|
|
UnidentifiedImageError,
|
|
|
|
__version__,
|
|
|
|
_plugins,
|
|
|
|
)
|
2022-03-01 01:23:12 +03:00
|
|
|
from ._binary import i32le, o32be, o32le
|
2022-04-05 16:33:20 +03:00
|
|
|
from ._deprecate import deprecate
|
2022-04-10 21:21:50 +03:00
|
|
|
from ._util import DeferredError, is_path
|
2018-10-18 19:46:20 +03:00
|
|
|
|
2020-03-31 09:41:47 +03:00
|
|
|
|
2021-10-15 13:07:53 +03:00
|
|
|
def __getattr__(name):
|
|
|
|
categories = {"NORMAL": 0, "SEQUENCE": 1, "CONTAINER": 2}
|
|
|
|
if name in categories:
|
2022-04-05 16:33:20 +03:00
|
|
|
deprecate("Image categories", 10, "is_animated", plural=True)
|
2021-10-15 13:07:53 +03:00
|
|
|
return categories[name]
|
2022-01-15 02:07:07 +03:00
|
|
|
old_resampling = {
|
|
|
|
"LINEAR": "BILINEAR",
|
|
|
|
"CUBIC": "BICUBIC",
|
|
|
|
"ANTIALIAS": "LANCZOS",
|
|
|
|
}
|
|
|
|
if name in old_resampling:
|
2022-12-28 01:44:53 +03:00
|
|
|
deprecate(
|
|
|
|
name, 10, f"{old_resampling[name]} or Resampling.{old_resampling[name]}"
|
|
|
|
)
|
2022-01-15 02:07:07 +03:00
|
|
|
return Resampling[old_resampling[name]]
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = f"module '{__name__}' has no attribute '{name}'"
|
|
|
|
raise AttributeError(msg)
|
2021-03-28 07:51:28 +03:00
|
|
|
|
2020-03-29 18:36:37 +03:00
|
|
|
|
2015-02-06 21:58:07 +03:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2014-06-23 11:53:08 +04:00
|
|
|
class DecompressionBombWarning(RuntimeWarning):
|
|
|
|
pass
|
|
|
|
|
2018-03-03 12:54:00 +03:00
|
|
|
|
2017-06-21 12:52:18 +03:00
|
|
|
class DecompressionBombError(Exception):
|
|
|
|
pass
|
2014-08-28 15:44:19 +04:00
|
|
|
|
2018-03-03 12:54:00 +03:00
|
|
|
|
2020-07-21 13:46:50 +03:00
|
|
|
# Limit to around a quarter gigabyte for a 24-bit (3 bpp) image
|
2016-10-17 18:45:54 +03:00
|
|
|
MAX_IMAGE_PIXELS = int(1024 * 1024 * 1024 // 4 // 3)
|
2014-05-14 19:04:18 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
try:
|
2014-11-19 22:41:46 +03:00
|
|
|
# If the _imaging C module is not present, Pillow will not load.
|
|
|
|
# Note that other modules should not refer to _imaging directly;
|
|
|
|
# import Image and use the Image.core variable instead.
|
|
|
|
# Also note that Image.core is not a publicly documented interface,
|
2014-11-28 04:21:03 +03:00
|
|
|
# and should be considered private and subject to change.
|
2017-01-17 16:22:18 +03:00
|
|
|
from . import _imaging as core
|
2019-03-21 16:28:20 +03:00
|
|
|
|
|
|
|
if __version__ != getattr(core, "PILLOW_VERSION", None):
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = (
|
2019-03-21 16:28:20 +03:00
|
|
|
"The _imaging extension was built for another version of Pillow or PIL:\n"
|
2020-07-16 12:43:29 +03:00
|
|
|
f"Core version: {getattr(core, 'PILLOW_VERSION', None)}\n"
|
|
|
|
f"Pillow version: {__version__}"
|
2019-03-21 16:28:20 +03:00
|
|
|
)
|
2022-12-22 00:51:35 +03:00
|
|
|
raise ImportError(msg)
|
2013-06-30 23:21:37 +04:00
|
|
|
|
2012-10-11 07:52:53 +04:00
|
|
|
except ImportError as v:
|
2022-04-10 21:21:50 +03:00
|
|
|
core = DeferredError(ImportError("The _imaging C module is not installed."))
|
2013-10-12 09:18:40 +04:00
|
|
|
# Explanations for ways that we know we might have an import error
|
2013-07-23 21:17:15 +04:00
|
|
|
if str(v).startswith("Module use of python"):
|
2010-07-31 06:52:47 +04:00
|
|
|
# The _imaging C module is present, but not compiled for
|
|
|
|
# the right version (windows only). Print a warning, if
|
|
|
|
# possible.
|
|
|
|
warnings.warn(
|
2019-03-21 16:28:20 +03:00
|
|
|
"The _imaging extension was built for another version of Python.",
|
|
|
|
RuntimeWarning,
|
|
|
|
)
|
2013-07-23 12:44:27 +04:00
|
|
|
elif str(v).startswith("The _imaging extension"):
|
2013-04-09 08:43:15 +04:00
|
|
|
warnings.warn(str(v), RuntimeWarning)
|
2013-10-12 09:18:40 +04:00
|
|
|
# Fail here anyway. Don't let people run with a mostly broken Pillow.
|
2016-02-19 12:11:00 +03:00
|
|
|
# see docs/porting.rst
|
2013-10-12 09:18:40 +04:00
|
|
|
raise
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
|
2014-01-07 10:08:14 +04:00
|
|
|
# works everywhere, win for pypy, not cpython
|
2019-03-21 16:28:20 +03:00
|
|
|
USE_CFFI_ACCESS = hasattr(sys, "pypy_version_info")
|
2014-01-05 22:41:25 +04:00
|
|
|
try:
|
|
|
|
import cffi
|
2015-05-27 02:15:45 +03:00
|
|
|
except ImportError:
|
2018-10-18 19:46:20 +03:00
|
|
|
cffi = None
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2014-01-05 22:41:25 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def isImageType(t):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
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
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
return hasattr(t, "im")
|
|
|
|
|
2017-01-29 19:38:06 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
#
|
2018-12-05 10:19:00 +03:00
|
|
|
# Constants
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2023-02-06 22:27:15 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# transpose
|
2022-01-15 01:02:31 +03:00
|
|
|
class Transpose(IntEnum):
|
|
|
|
FLIP_LEFT_RIGHT = 0
|
|
|
|
FLIP_TOP_BOTTOM = 1
|
|
|
|
ROTATE_90 = 2
|
|
|
|
ROTATE_180 = 3
|
|
|
|
ROTATE_270 = 4
|
|
|
|
TRANSPOSE = 5
|
|
|
|
TRANSVERSE = 6
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2018-12-05 10:19:00 +03:00
|
|
|
# transforms (also defined in Imaging.h)
|
2022-01-15 01:02:31 +03:00
|
|
|
class Transform(IntEnum):
|
|
|
|
AFFINE = 0
|
|
|
|
EXTENT = 1
|
|
|
|
PERSPECTIVE = 2
|
|
|
|
QUAD = 3
|
|
|
|
MESH = 4
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
# resampling filters (also defined in Imaging.h)
|
|
|
|
class Resampling(IntEnum):
|
|
|
|
NEAREST = 0
|
|
|
|
BOX = 4
|
|
|
|
BILINEAR = 2
|
|
|
|
HAMMING = 5
|
|
|
|
BICUBIC = 3
|
|
|
|
LANCZOS = 1
|
|
|
|
|
|
|
|
|
|
|
|
_filters_support = {
|
|
|
|
Resampling.BOX: 0.5,
|
|
|
|
Resampling.BILINEAR: 1.0,
|
|
|
|
Resampling.HAMMING: 1.0,
|
|
|
|
Resampling.BICUBIC: 2.0,
|
|
|
|
Resampling.LANCZOS: 3.0,
|
|
|
|
}
|
2019-12-20 14:54:06 +03:00
|
|
|
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# dithers
|
2022-01-15 01:02:31 +03:00
|
|
|
class Dither(IntEnum):
|
|
|
|
NONE = 0
|
|
|
|
ORDERED = 1 # Not yet implemented
|
|
|
|
RASTERIZE = 2 # Not yet implemented
|
|
|
|
FLOYDSTEINBERG = 3 # default
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
# palettes/quantizers
|
2022-01-15 01:02:31 +03:00
|
|
|
class Palette(IntEnum):
|
|
|
|
WEB = 0
|
|
|
|
ADAPTIVE = 1
|
|
|
|
|
|
|
|
|
|
|
|
class Quantize(IntEnum):
|
|
|
|
MEDIANCUT = 0
|
|
|
|
MAXCOVERAGE = 1
|
|
|
|
FASTOCTREE = 2
|
|
|
|
LIBIMAGEQUANT = 3
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2013-03-11 23:33:04 +04:00
|
|
|
|
2022-12-28 01:44:53 +03:00
|
|
|
module = sys.modules[__name__]
|
|
|
|
for enum in (Transpose, Transform, Resampling, Dither, Palette, Quantize):
|
|
|
|
for item in enum:
|
|
|
|
setattr(module, item.name, item.value)
|
|
|
|
|
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
if hasattr(core, "DEFAULT_STRATEGY"):
|
2013-03-11 23:33:04 +04:00
|
|
|
DEFAULT_STRATEGY = core.DEFAULT_STRATEGY
|
|
|
|
FILTERED = core.FILTERED
|
|
|
|
HUFFMAN_ONLY = core.HUFFMAN_ONLY
|
|
|
|
RLE = core.RLE
|
|
|
|
FIXED = core.FIXED
|
|
|
|
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Registries
|
|
|
|
|
|
|
|
ID = []
|
|
|
|
OPEN = {}
|
|
|
|
MIME = {}
|
|
|
|
SAVE = {}
|
2015-06-30 11:02:48 +03:00
|
|
|
SAVE_ALL = {}
|
2010-07-31 06:52:47 +04:00
|
|
|
EXTENSION = {}
|
2016-05-31 11:10:01 +03:00
|
|
|
DECODERS = {}
|
|
|
|
ENCODERS = {}
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
# --------------------------------------------------------------------
|
2021-03-07 06:21:27 +03:00
|
|
|
# Modes
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2022-02-15 13:45:35 +03:00
|
|
|
_ENDIAN = "<" if sys.byteorder == "little" else ">"
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def _conv_type_shape(im):
|
2022-02-15 10:01:02 +03:00
|
|
|
m = ImageMode.getmode(im.mode)
|
2022-02-15 13:47:12 +03:00
|
|
|
shape = (im.height, im.width)
|
2022-02-15 10:01:02 +03:00
|
|
|
extra = len(m.bands)
|
|
|
|
if extra != 1:
|
|
|
|
shape += (extra,)
|
|
|
|
return shape, m.typestr
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
|
2021-03-07 06:21:27 +03:00
|
|
|
MODES = ["1", "CMYK", "F", "HSV", "I", "L", "LAB", "P", "RGB", "RGBA", "RGBX", "YCbCr"]
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
# raw modes that may be memory mapped. NOTE: if you change this, you
|
|
|
|
# may have to modify the stride calculation in map.c too!
|
|
|
|
_MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16L", "I;16B")
|
|
|
|
|
|
|
|
|
|
|
|
def getmodebase(mode):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Gets the "base" mode for given mode. This function returns "L" for
|
|
|
|
images that contain grayscale data, and "RGB" for images that
|
|
|
|
contain color data.
|
|
|
|
|
|
|
|
:param mode: Input mode.
|
|
|
|
:returns: "L" or "RGB".
|
|
|
|
:exception KeyError: If the input mode was not a standard mode.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
return ImageMode.getmode(mode).basemode
|
|
|
|
|
|
|
|
|
|
|
|
def getmodetype(mode):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Gets the storage type mode. Given a mode, this function returns a
|
|
|
|
single-layer mode suitable for storing individual bands.
|
|
|
|
|
|
|
|
:param mode: Input mode.
|
|
|
|
:returns: "L", "I", or "F".
|
|
|
|
:exception KeyError: If the input mode was not a standard mode.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
return ImageMode.getmode(mode).basetype
|
|
|
|
|
|
|
|
|
|
|
|
def getmodebandnames(mode):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
2013-10-12 09:18:40 +04:00
|
|
|
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.
|
2013-07-09 23:12:28 +04:00
|
|
|
|
|
|
|
: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.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
return ImageMode.getmode(mode).bands
|
|
|
|
|
|
|
|
|
|
|
|
def getmodebands(mode):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Gets the number of individual bands for this mode.
|
|
|
|
|
|
|
|
:param mode: Input mode.
|
|
|
|
:returns: The number of bands in this mode.
|
|
|
|
:exception KeyError: If the input mode was not a standard mode.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
return len(ImageMode.getmode(mode).bands)
|
|
|
|
|
2017-01-29 19:38:06 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Helpers
|
|
|
|
|
|
|
|
_initialized = 0
|
|
|
|
|
|
|
|
|
|
|
|
def preinit():
|
2018-04-09 16:13:19 +03:00
|
|
|
"""Explicitly load standard file format drivers."""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
global _initialized
|
|
|
|
if _initialized >= 1:
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
2017-01-17 16:22:18 +03:00
|
|
|
from . import BmpImagePlugin
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2018-10-18 19:46:20 +03:00
|
|
|
assert BmpImagePlugin
|
2010-07-31 06:52:47 +04:00
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
try:
|
2017-01-17 16:22:18 +03:00
|
|
|
from . import GifImagePlugin
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2018-10-18 19:46:20 +03:00
|
|
|
assert GifImagePlugin
|
2010-07-31 06:52:47 +04:00
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
try:
|
2017-01-17 16:22:18 +03:00
|
|
|
from . import JpegImagePlugin
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2018-10-18 19:46:20 +03:00
|
|
|
assert JpegImagePlugin
|
2010-07-31 06:52:47 +04:00
|
|
|
except ImportError:
|
|
|
|
pass
|
2014-07-17 20:30:45 +04:00
|
|
|
try:
|
2017-01-17 16:22:18 +03:00
|
|
|
from . import PpmImagePlugin
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2018-10-18 19:46:20 +03:00
|
|
|
assert PpmImagePlugin
|
2010-07-31 06:52:47 +04:00
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
try:
|
2017-01-17 16:22:18 +03:00
|
|
|
from . import PngImagePlugin
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2018-10-18 19:46:20 +03:00
|
|
|
assert PngImagePlugin
|
2010-07-31 06:52:47 +04:00
|
|
|
except ImportError:
|
|
|
|
pass
|
2019-03-21 16:28:20 +03:00
|
|
|
# try:
|
|
|
|
# import TiffImagePlugin
|
|
|
|
# assert TiffImagePlugin
|
|
|
|
# except ImportError:
|
|
|
|
# pass
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
_initialized = 1
|
|
|
|
|
|
|
|
|
|
|
|
def init():
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Explicitly initializes the Python Imaging Library. This function
|
|
|
|
loads all available file format drivers.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
global _initialized
|
|
|
|
if _initialized >= 2:
|
|
|
|
return 0
|
|
|
|
|
2013-04-15 21:57:37 +04:00
|
|
|
for plugin in _plugins:
|
|
|
|
try:
|
2015-02-06 21:58:07 +03:00
|
|
|
logger.debug("Importing %s", plugin)
|
2020-07-16 12:43:29 +03:00
|
|
|
__import__(f"PIL.{plugin}", globals(), locals(), [])
|
2015-02-06 21:58:07 +03:00
|
|
|
except ImportError as e:
|
|
|
|
logger.debug("Image: failed to import %s: %s", plugin, e)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
if OPEN or SAVE:
|
|
|
|
_initialized = 2
|
|
|
|
return 1
|
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# --------------------------------------------------------------------
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
# Codec factories (used by tobytes/frombytes and ImageFile.load)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def _getdecoder(mode, decoder_name, args, extra=()):
|
|
|
|
# tweak arguments
|
|
|
|
if args is None:
|
|
|
|
args = ()
|
2012-10-16 07:14:10 +04:00
|
|
|
elif not isinstance(args, tuple):
|
2010-07-31 06:52:47 +04:00
|
|
|
args = (args,)
|
|
|
|
|
2016-05-31 11:10:01 +03:00
|
|
|
try:
|
|
|
|
decoder = DECODERS[decoder_name]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
2020-01-26 18:08:58 +03:00
|
|
|
else:
|
|
|
|
return decoder(mode, *args + extra)
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
try:
|
|
|
|
# get decoder
|
|
|
|
decoder = getattr(core, decoder_name + "_decoder")
|
2020-06-21 13:13:35 +03:00
|
|
|
except AttributeError as e:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = f"decoder {decoder_name} not available"
|
|
|
|
raise OSError(msg) from e
|
2020-01-26 18:08:58 +03:00
|
|
|
return decoder(mode, *args + extra)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def _getencoder(mode, encoder_name, args, extra=()):
|
|
|
|
# tweak arguments
|
|
|
|
if args is None:
|
|
|
|
args = ()
|
2012-10-16 07:14:10 +04:00
|
|
|
elif not isinstance(args, tuple):
|
2010-07-31 06:52:47 +04:00
|
|
|
args = (args,)
|
|
|
|
|
2016-05-31 11:10:01 +03:00
|
|
|
try:
|
|
|
|
encoder = ENCODERS[encoder_name]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
2020-01-26 18:08:58 +03:00
|
|
|
else:
|
|
|
|
return encoder(mode, *args + extra)
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
try:
|
|
|
|
# get encoder
|
|
|
|
encoder = getattr(core, encoder_name + "_encoder")
|
2020-06-21 13:13:35 +03:00
|
|
|
except AttributeError as e:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = f"encoder {encoder_name} not available"
|
|
|
|
raise OSError(msg) from e
|
2020-01-26 18:08:58 +03:00
|
|
|
return encoder(mode, *args + extra)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
|
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Simple expression analyzer
|
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2012-10-19 16:54:55 +04:00
|
|
|
def coerce_e(value):
|
2022-05-03 02:01:23 +03:00
|
|
|
deprecate("coerce_e", 10)
|
|
|
|
return value if isinstance(value, _E) else _E(1, value)
|
2012-10-19 16:54:55 +04:00
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2022-05-03 23:42:04 +03:00
|
|
|
# _E(scale, offset) represents the affine transformation scale * x + offset.
|
|
|
|
# The "data" field is named for compatibility with the old implementation,
|
|
|
|
# and should be renamed once coerce_e is removed.
|
2019-09-30 17:56:31 +03:00
|
|
|
class _E:
|
2022-05-03 02:01:23 +03:00
|
|
|
def __init__(self, scale, data):
|
|
|
|
self.scale = scale
|
2012-10-19 16:54:55 +04:00
|
|
|
self.data = data
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2022-05-01 08:58:44 +03:00
|
|
|
def __neg__(self):
|
2022-05-03 02:01:23 +03:00
|
|
|
return _E(-self.scale, -self.data)
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2012-10-19 16:54:55 +04:00
|
|
|
def __add__(self, other):
|
2022-05-03 02:01:23 +03:00
|
|
|
if isinstance(other, _E):
|
|
|
|
return _E(self.scale + other.scale, self.data + other.data)
|
|
|
|
return _E(self.scale, self.data + other)
|
2022-05-01 08:58:44 +03:00
|
|
|
|
|
|
|
__radd__ = __add__
|
|
|
|
|
|
|
|
def __sub__(self, other):
|
|
|
|
return self + -other
|
|
|
|
|
|
|
|
def __rsub__(self, other):
|
|
|
|
return other + -self
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2012-10-19 16:54:55 +04:00
|
|
|
def __mul__(self, other):
|
2022-05-03 02:01:23 +03:00
|
|
|
if isinstance(other, _E):
|
2022-05-01 08:58:44 +03:00
|
|
|
return NotImplemented
|
2022-05-03 02:01:23 +03:00
|
|
|
return _E(self.scale * other, self.data * other)
|
2022-05-01 08:58:44 +03:00
|
|
|
|
|
|
|
__rmul__ = __mul__
|
|
|
|
|
|
|
|
def __truediv__(self, other):
|
2022-05-03 02:01:23 +03:00
|
|
|
if isinstance(other, _E):
|
2022-05-01 08:58:44 +03:00
|
|
|
return NotImplemented
|
2022-05-03 02:01:23 +03:00
|
|
|
return _E(self.scale / other, self.data / other)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def _getscaleoffset(expr):
|
2022-05-03 02:01:23 +03:00
|
|
|
a = expr(_E(1, 0))
|
|
|
|
return (a.scale, a.data) if isinstance(a, _E) else (0, a)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
|
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Implementation wrapper
|
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2019-09-30 17:56:31 +03:00
|
|
|
class Image:
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2013-10-12 09:18:40 +04:00
|
|
|
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`
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
format = None
|
|
|
|
format_description = None
|
2017-03-15 02:16:38 +03:00
|
|
|
_close_exclusive_fp_after_loading = True
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
# FIXME: take "new" parameters / other image?
|
|
|
|
# FIXME: turn mode and size into delegating properties?
|
|
|
|
self.im = None
|
|
|
|
self.mode = ""
|
2018-09-30 05:58:02 +03:00
|
|
|
self._size = (0, 0)
|
2010-07-31 06:52:47 +04:00
|
|
|
self.palette = None
|
|
|
|
self.info = {}
|
2021-03-28 07:51:28 +03:00
|
|
|
self._category = 0
|
2010-07-31 06:52:47 +04:00
|
|
|
self.readonly = 0
|
2014-01-05 22:41:25 +04:00
|
|
|
self.pyaccess = None
|
2019-08-22 23:13:20 +03:00
|
|
|
self._exif = None
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2021-03-28 07:51:28 +03:00
|
|
|
def __getattr__(self, name):
|
|
|
|
if name == "category":
|
2022-04-05 16:33:20 +03:00
|
|
|
deprecate("Image categories", 10, "is_animated", plural=True)
|
2021-03-28 07:51:28 +03:00
|
|
|
return self._category
|
|
|
|
raise AttributeError(name)
|
|
|
|
|
2015-06-24 03:35:37 +03:00
|
|
|
@property
|
|
|
|
def width(self):
|
|
|
|
return self.size[0]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def height(self):
|
|
|
|
return self.size[1]
|
|
|
|
|
2018-09-30 05:58:02 +03:00
|
|
|
@property
|
|
|
|
def size(self):
|
|
|
|
return self._size
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def _new(self, im):
|
|
|
|
new = Image()
|
|
|
|
new.im = im
|
|
|
|
new.mode = im.mode
|
2018-09-30 05:58:02 +03:00
|
|
|
new._size = im.size
|
2019-03-21 16:28:20 +03:00
|
|
|
if im.mode in ("P", "PA"):
|
2017-08-31 16:18:59 +03:00
|
|
|
if self.palette:
|
|
|
|
new.palette = self.palette.copy()
|
|
|
|
else:
|
|
|
|
from . import ImagePalette
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2017-08-31 16:18:59 +03:00
|
|
|
new.palette = ImagePalette.ImagePalette()
|
2016-05-07 11:33:02 +03:00
|
|
|
new.info = self.info.copy()
|
2010-07-31 06:52:47 +04:00
|
|
|
return new
|
|
|
|
|
2018-11-11 07:50:34 +03:00
|
|
|
# Context manager support
|
2014-03-01 03:57:53 +04:00
|
|
|
def __enter__(self):
|
|
|
|
return self
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2014-03-01 03:57:53 +04:00
|
|
|
def __exit__(self, *args):
|
2019-03-21 16:28:20 +03:00
|
|
|
if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False):
|
2022-04-15 13:31:23 +03:00
|
|
|
if getattr(self, "_fp", False):
|
|
|
|
if self._fp != self.fp:
|
|
|
|
self._fp.close()
|
2022-04-17 05:14:53 +03:00
|
|
|
self._fp = DeferredError(ValueError("Operation on closed image"))
|
2019-03-12 00:54:43 +03:00
|
|
|
if self.fp:
|
|
|
|
self.fp.close()
|
2019-03-06 13:55:32 +03:00
|
|
|
self.fp = None
|
2014-05-14 19:04:18 +04:00
|
|
|
|
2014-03-01 03:57:53 +04:00
|
|
|
def close(self):
|
2014-04-18 08:53:49 +04:00
|
|
|
"""
|
|
|
|
Closes the file pointer, if possible.
|
|
|
|
|
2014-09-18 08:36:59 +04:00
|
|
|
This operation will destroy the image core and release its memory.
|
2014-04-18 08:53:49 +04:00
|
|
|
The image data will be unusable afterward.
|
|
|
|
|
2021-01-31 05:14:14 +03:00
|
|
|
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.
|
2014-04-18 08:53:49 +04:00
|
|
|
"""
|
2014-03-01 03:57:53 +04:00
|
|
|
try:
|
2022-04-15 13:31:23 +03:00
|
|
|
if getattr(self, "_fp", False):
|
|
|
|
if self._fp != self.fp:
|
|
|
|
self._fp.close()
|
2022-04-17 05:14:53 +03:00
|
|
|
self._fp = DeferredError(ValueError("Operation on closed image"))
|
2020-09-01 20:16:46 +03:00
|
|
|
if self.fp:
|
|
|
|
self.fp.close()
|
2019-01-04 04:29:23 +03:00
|
|
|
self.fp = None
|
2014-03-01 03:57:53 +04:00
|
|
|
except Exception as msg:
|
2015-12-02 08:32:44 +03:00
|
|
|
logger.debug("Error closing: %s", msg)
|
2014-03-01 03:57:53 +04:00
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
if getattr(self, "map", None):
|
2017-04-03 18:05:56 +03:00
|
|
|
self.map = None
|
2017-04-20 14:14:23 +03:00
|
|
|
|
2014-04-09 10:43:13 +04:00
|
|
|
# Instead of simply setting to None, we're setting up a
|
|
|
|
# deferred error that will better explain that the core image
|
|
|
|
# object is gone.
|
2022-04-10 21:21:50 +03:00
|
|
|
self.im = DeferredError(ValueError("Operation on closed image"))
|
2014-05-14 19:04:18 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def _copy(self):
|
|
|
|
self.load()
|
|
|
|
self.im = self.im.copy()
|
2014-01-06 10:18:42 +04:00
|
|
|
self.pyaccess = None
|
2010-07-31 06:52:47 +04:00
|
|
|
self.readonly = 0
|
|
|
|
|
2017-09-29 11:39:56 +03:00
|
|
|
def _ensure_mutable(self):
|
2017-09-06 07:22:22 +03:00
|
|
|
if self.readonly:
|
|
|
|
self._copy()
|
|
|
|
else:
|
|
|
|
self.load()
|
|
|
|
|
2017-05-10 23:07:31 +03:00
|
|
|
def _dump(self, file=None, format=None, **options):
|
2019-03-21 16:28:20 +03:00
|
|
|
suffix = ""
|
2014-04-08 03:01:49 +04:00
|
|
|
if format:
|
2019-03-21 16:28:20 +03:00
|
|
|
suffix = "." + format
|
2017-08-20 08:18:55 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
if not file:
|
2017-08-20 08:18:55 +03:00
|
|
|
f, filename = tempfile.mkstemp(suffix)
|
2014-03-15 02:56:41 +04:00
|
|
|
os.close(f)
|
2017-08-20 08:18:55 +03:00
|
|
|
else:
|
|
|
|
filename = file
|
|
|
|
if not filename.endswith(suffix):
|
|
|
|
filename = filename + suffix
|
2014-05-14 19:04:18 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
self.load()
|
2017-08-20 08:18:55 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
if not format or format == "PPM":
|
2017-08-20 08:18:55 +03:00
|
|
|
self.im.save_ppm(filename)
|
2010-07-31 06:52:47 +04:00
|
|
|
else:
|
2017-08-20 08:18:55 +03:00
|
|
|
self.save(filename, format, **options)
|
|
|
|
|
|
|
|
return filename
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-04-26 20:43:53 +04:00
|
|
|
def __eq__(self, other):
|
2019-03-21 16:28:20 +03:00
|
|
|
return (
|
|
|
|
self.__class__ is other.__class__
|
|
|
|
and self.mode == other.mode
|
|
|
|
and self.size == other.size
|
|
|
|
and self.info == other.info
|
2021-03-28 07:51:28 +03:00
|
|
|
and self._category == other._category
|
2019-03-21 16:28:20 +03:00
|
|
|
and self.getpalette() == other.getpalette()
|
|
|
|
and self.tobytes() == other.tobytes()
|
|
|
|
)
|
2014-04-26 20:43:53 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def __repr__(self):
|
|
|
|
return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % (
|
2019-03-21 16:28:20 +03:00
|
|
|
self.__class__.__module__,
|
|
|
|
self.__class__.__name__,
|
|
|
|
self.mode,
|
|
|
|
self.size[0],
|
|
|
|
self.size[1],
|
|
|
|
id(self),
|
|
|
|
)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2021-12-15 23:35:32 +03:00
|
|
|
def _repr_pretty_(self, p, cycle):
|
|
|
|
"""IPython plain text display support"""
|
|
|
|
|
2022-07-16 12:04:42 +03:00
|
|
|
# Same as __repr__ but without unpredictable id(self),
|
2021-12-15 23:35:32 +03:00
|
|
|
# to keep Jupyter notebook `text/plain` output stable.
|
2021-12-15 23:39:38 +03:00
|
|
|
p.text(
|
|
|
|
"<%s.%s image mode=%s size=%dx%d>"
|
|
|
|
% (
|
|
|
|
self.__class__.__module__,
|
|
|
|
self.__class__.__name__,
|
|
|
|
self.mode,
|
|
|
|
self.size[0],
|
|
|
|
self.size[1],
|
|
|
|
)
|
|
|
|
)
|
2021-12-15 23:35:32 +03:00
|
|
|
|
2015-01-28 21:02:04 +03:00
|
|
|
def _repr_png_(self):
|
2020-09-01 20:16:46 +03:00
|
|
|
"""iPython display hook support
|
2015-04-02 08:29:18 +03:00
|
|
|
|
2015-01-28 20:35:31 +03:00
|
|
|
:returns: png version of the image as bytes
|
|
|
|
"""
|
2019-03-02 23:19:57 +03:00
|
|
|
b = io.BytesIO()
|
2020-12-27 07:36:16 +03:00
|
|
|
try:
|
|
|
|
self.save(b, "PNG")
|
|
|
|
except Exception as e:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Could not save to PNG for display"
|
|
|
|
raise ValueError(msg) from e
|
2015-01-28 20:35:31 +03:00
|
|
|
return b.getvalue()
|
|
|
|
|
2022-04-09 01:53:27 +03:00
|
|
|
@property
|
|
|
|
def __array_interface__(self):
|
2016-08-08 01:25:43 +03:00
|
|
|
# numpy array interface support
|
|
|
|
new = {}
|
|
|
|
shape, typestr = _conv_type_shape(self)
|
2019-03-21 16:28:20 +03:00
|
|
|
new["shape"] = shape
|
|
|
|
new["typestr"] = typestr
|
|
|
|
new["version"] = 3
|
2022-09-17 13:11:55 +03:00
|
|
|
try:
|
|
|
|
if self.mode == "1":
|
|
|
|
# Binary images need to be extended from bits to bytes
|
|
|
|
# See: https://github.com/python-pillow/Pillow/issues/350
|
|
|
|
new["data"] = self.tobytes("raw", "L")
|
|
|
|
else:
|
|
|
|
new["data"] = self.tobytes()
|
|
|
|
except Exception as e:
|
|
|
|
if not isinstance(e, (MemoryError, RecursionError)):
|
|
|
|
try:
|
|
|
|
import numpy
|
|
|
|
from packaging.version import parse as parse_version
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
if parse_version(numpy.__version__) < parse_version("1.23"):
|
|
|
|
warnings.warn(e)
|
|
|
|
raise
|
2022-04-09 01:53:27 +03:00
|
|
|
return new
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-04-22 09:54:16 +04:00
|
|
|
def __getstate__(self):
|
2019-03-21 16:28:20 +03:00
|
|
|
return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()]
|
2014-04-22 09:54:16 +04:00
|
|
|
|
|
|
|
def __setstate__(self, state):
|
2014-04-26 18:18:29 +04:00
|
|
|
Image.__init__(self)
|
2014-04-26 20:43:53 +04:00
|
|
|
info, mode, size, palette, data = state
|
|
|
|
self.info = info
|
2014-04-22 09:54:16 +04:00
|
|
|
self.mode = mode
|
2018-09-30 05:58:02 +03:00
|
|
|
self._size = size
|
2014-04-25 10:01:16 +04:00
|
|
|
self.im = core.new(mode, size)
|
2019-05-11 07:01:23 +03:00
|
|
|
if mode in ("L", "LA", "P", "PA") and palette:
|
2014-04-26 20:43:53 +04:00
|
|
|
self.putpalette(palette)
|
2014-04-22 09:54:16 +04:00
|
|
|
self.frombytes(data)
|
|
|
|
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
def tobytes(self, encoder_name="raw", *args):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2015-10-05 13:27:25 +03:00
|
|
|
Return image as a bytes object.
|
2015-12-10 01:35:35 +03:00
|
|
|
|
2015-10-05 13:27:25 +03:00
|
|
|
.. warning::
|
2015-12-10 01:35:35 +03:00
|
|
|
|
2015-10-12 17:26:58 +03:00
|
|
|
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.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
|
|
|
:param encoder_name: What encoder to use. The default is to
|
|
|
|
use the standard "raw" encoder.
|
2022-07-04 12:33:21 +03:00
|
|
|
|
|
|
|
A list of C encoders can be seen under
|
|
|
|
codecs section of the function array in
|
|
|
|
:file:`_imaging.c`. Python encoders are
|
|
|
|
registered within the relevant plugins.
|
2013-07-09 23:12:28 +04:00
|
|
|
:param args: Extra arguments to the encoder.
|
2020-07-09 20:48:04 +03:00
|
|
|
:returns: A :py:class:`bytes` object.
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
# may pass tuple instead of argument list
|
2012-10-16 07:14:10 +04:00
|
|
|
if len(args) == 1 and isinstance(args[0], tuple):
|
2010-07-31 06:52:47 +04:00
|
|
|
args = args[0]
|
|
|
|
|
|
|
|
if encoder_name == "raw" and args == ():
|
|
|
|
args = self.mode
|
|
|
|
|
|
|
|
self.load()
|
|
|
|
|
2022-01-07 08:29:38 +03:00
|
|
|
if self.width == 0 or self.height == 0:
|
|
|
|
return b""
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# unpack data
|
|
|
|
e = _getencoder(self.mode, encoder_name, args)
|
|
|
|
e.setimage(self.im)
|
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
bufsize = max(65536, self.size[0] * 4) # see RawEncode.c
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
data = []
|
2012-10-17 07:39:56 +04:00
|
|
|
while True:
|
2010-07-31 06:52:47 +04:00
|
|
|
l, s, d = e.encode(bufsize)
|
|
|
|
data.append(d)
|
|
|
|
if s:
|
|
|
|
break
|
|
|
|
if s < 0:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = f"encoder error {s} in tobytes"
|
|
|
|
raise RuntimeError(msg)
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
|
|
|
|
return b"".join(data)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def tobitmap(self, name="image"):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
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"
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.load()
|
|
|
|
if self.mode != "1":
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "not a bitmap"
|
|
|
|
raise ValueError(msg)
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
data = self.tobytes("xbm")
|
2019-03-21 16:28:20 +03:00
|
|
|
return b"".join(
|
|
|
|
[
|
2020-07-16 12:43:29 +03:00
|
|
|
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"),
|
2019-03-21 16:28:20 +03:00
|
|
|
data,
|
|
|
|
b"};",
|
|
|
|
]
|
|
|
|
)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
def frombytes(self, data, decoder_name="raw", *args):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Loads this image with pixel data from a bytes object.
|
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
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.
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
# may pass tuple instead of argument list
|
2012-10-16 07:14:10 +04:00
|
|
|
if len(args) == 1 and isinstance(args[0], tuple):
|
2010-07-31 06:52:47 +04:00
|
|
|
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:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "not enough image data"
|
|
|
|
raise ValueError(msg)
|
2010-07-31 06:52:47 +04:00
|
|
|
if s[1] != 0:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "cannot decode image data"
|
|
|
|
raise ValueError(msg)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def load(self):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
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
|
2018-06-30 09:44:59 +03:00
|
|
|
accessed for the first time.
|
|
|
|
|
2018-12-11 06:39:10 +03:00
|
|
|
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.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
|
|
|
:returns: An image access object.
|
2014-11-28 04:21:03 +03:00
|
|
|
:rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess`
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2022-03-03 14:10:19 +03:00
|
|
|
if self.im is not None and self.palette and self.palette.dirty:
|
2010-07-31 06:52:47 +04:00
|
|
|
# realize palette
|
2020-12-12 06:12:30 +03:00
|
|
|
mode, arr = self.palette.getdata()
|
2022-02-16 01:56:13 +03:00
|
|
|
self.im.putpalette(mode, arr)
|
2010-07-31 06:52:47 +04:00
|
|
|
self.palette.dirty = 0
|
|
|
|
self.palette.rawmode = None
|
2021-12-30 03:45:40 +03:00
|
|
|
if "transparency" in self.info and mode in ("LA", "PA"):
|
2013-03-13 00:29:46 +04:00
|
|
|
if isinstance(self.info["transparency"], int):
|
2013-03-11 23:33:04 +04:00
|
|
|
self.im.putpalettealpha(self.info["transparency"], 0)
|
2013-03-13 00:29:46 +04:00
|
|
|
else:
|
|
|
|
self.im.putpalettealphas(self.info["transparency"])
|
2010-07-31 06:52:47 +04:00
|
|
|
self.palette.mode = "RGBA"
|
2020-12-12 06:12:30 +03:00
|
|
|
else:
|
2022-02-14 12:28:47 +03:00
|
|
|
palette_mode = "RGBA" if mode.startswith("RGBA") else "RGB"
|
|
|
|
self.palette.mode = palette_mode
|
2022-02-16 01:56:13 +03:00
|
|
|
self.palette.palette = self.im.getpalette(palette_mode, palette_mode)
|
2013-03-11 23:33:04 +04:00
|
|
|
|
2022-03-03 14:10:19 +03:00
|
|
|
if self.im is not None:
|
2018-10-18 19:46:20 +03:00
|
|
|
if cffi and USE_CFFI_ACCESS:
|
2014-01-05 22:41:25 +04:00
|
|
|
if self.pyaccess:
|
|
|
|
return self.pyaccess
|
2017-01-17 16:22:18 +03:00
|
|
|
from . import PyAccess
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2014-01-05 22:41:25 +04:00
|
|
|
self.pyaccess = PyAccess.new(self, self.readonly)
|
|
|
|
if self.pyaccess:
|
|
|
|
return self.pyaccess
|
2010-07-31 06:52:47 +04:00
|
|
|
return self.im.pixel_access(self.readonly)
|
|
|
|
|
|
|
|
def verify(self):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
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.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
pass
|
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
def convert(
|
|
|
|
self, mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256
|
|
|
|
):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
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
|
2022-10-13 12:21:39 +03:00
|
|
|
"L", "RGB" and "CMYK". The ``matrix`` argument only supports "L"
|
2013-10-12 09:18:40 +04:00
|
|
|
and "RGB".
|
2013-07-09 18:32:14 +04:00
|
|
|
|
2018-12-27 23:14:44 +03:00
|
|
|
When translating a color image to greyscale (mode "L"),
|
2013-10-12 09:18:40 +04:00
|
|
|
the library uses the ITU-R 601-2 luma transform::
|
2013-07-09 18:32:14 +04:00
|
|
|
|
|
|
|
L = R * 299/1000 + G * 587/1000 + B * 114/1000
|
|
|
|
|
2013-11-13 10:40:36 +04:00
|
|
|
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
|
2022-01-15 01:02:31 +03:00
|
|
|
dither is ``None``, all values larger than 127 are set to 255 (white),
|
2018-10-05 02:11:24 +03:00
|
|
|
all other values to 0 (black). To use other thresholds, use the
|
|
|
|
:py:meth:`~PIL.Image.Image.point` method.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
2020-09-01 20:16:46 +03:00
|
|
|
When converting from "RGBA" to "P" without a ``matrix`` argument,
|
2018-09-29 13:14:56 +03:00
|
|
|
this passes the operation to :py:meth:`~PIL.Image.Image.quantize`,
|
2020-09-01 20:16:46 +03:00
|
|
|
and ``dither`` and ``palette`` are ignored.
|
2018-09-29 13:14:56 +03:00
|
|
|
|
2022-10-13 12:21:39 +03:00
|
|
|
When converting from "PA", if an "RGBA" palette is present, the alpha
|
|
|
|
channel from the image will be used instead of the values from the palette.
|
|
|
|
|
2014-11-19 23:49:27 +03:00
|
|
|
:param mode: The requested mode. See: :ref:`concept-modes`.
|
2013-07-09 18:32:14 +04:00
|
|
|
:param matrix: An optional conversion matrix. If given, this
|
2015-09-15 11:00:36 +03:00
|
|
|
should be 4- or 12-tuple containing floating point values.
|
2013-07-09 18:32:14 +04:00
|
|
|
:param dither: Dithering method, used when converting from
|
2013-11-13 10:40:36 +04:00
|
|
|
mode "RGB" to "P" or from "RGB" or "L" to "1".
|
2022-01-15 01:02:31 +03:00
|
|
|
Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG`
|
|
|
|
(default). Note that this is not used when ``matrix`` is supplied.
|
2013-07-09 18:32:14 +04:00
|
|
|
:param palette: Palette to use when converting from mode "RGB"
|
2022-01-15 01:02:31 +03:00
|
|
|
to "P". Available palettes are :data:`Palette.WEB` or
|
|
|
|
:data:`Palette.ADAPTIVE`.
|
|
|
|
:param colors: Number of colors to use for the :data:`Palette.ADAPTIVE`
|
|
|
|
palette. Defaults to 256.
|
2013-10-12 09:18:40 +04:00
|
|
|
:rtype: :py:class:`~PIL.Image.Image`
|
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2017-09-06 07:49:15 +03:00
|
|
|
self.load()
|
|
|
|
|
2021-07-08 10:08:11 +03:00
|
|
|
has_transparency = self.info.get("transparency") is not None
|
2017-09-06 07:49:15 +03:00
|
|
|
if not mode and self.mode == "P":
|
2010-07-31 06:52:47 +04:00
|
|
|
# determine default mode
|
2017-09-06 07:49:15 +03:00
|
|
|
if self.palette:
|
|
|
|
mode = self.palette.mode
|
2010-07-31 06:52:47 +04:00
|
|
|
else:
|
2017-09-06 07:49:15 +03:00
|
|
|
mode = "RGB"
|
2021-07-08 10:08:11 +03:00
|
|
|
if mode == "RGB" and has_transparency:
|
|
|
|
mode = "RGBA"
|
2017-09-06 07:49:15 +03:00
|
|
|
if not mode or (mode == self.mode and not matrix):
|
|
|
|
return self.copy()
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
if matrix:
|
2010-07-31 06:52:47 +04:00
|
|
|
# matrix conversion
|
|
|
|
if mode not in ("L", "RGB"):
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "illegal conversion"
|
|
|
|
raise ValueError(msg)
|
2013-10-12 09:18:40 +04:00
|
|
|
im = self.im.convert_matrix(mode, matrix)
|
2018-06-25 14:08:41 +03:00
|
|
|
new = self._new(im)
|
|
|
|
if has_transparency and self.im.bands == 3:
|
2019-03-21 16:28:20 +03:00
|
|
|
transparency = new.info["transparency"]
|
2018-06-25 14:08:41 +03:00
|
|
|
|
|
|
|
def convert_transparency(m, v):
|
2019-03-21 16:28:20 +03:00
|
|
|
v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5
|
2018-06-25 14:08:41 +03:00
|
|
|
return max(0, min(255, int(v)))
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2018-06-25 14:08:41 +03:00
|
|
|
if mode == "L":
|
|
|
|
transparency = convert_transparency(matrix, transparency)
|
|
|
|
elif len(mode) == 3:
|
2019-03-21 16:28:20 +03:00
|
|
|
transparency = tuple(
|
2021-10-15 13:10:22 +03:00
|
|
|
convert_transparency(matrix[i * 4 : i * 4 + 4], transparency)
|
|
|
|
for i in range(0, len(transparency))
|
2019-03-21 16:28:20 +03:00
|
|
|
)
|
|
|
|
new.info["transparency"] = transparency
|
2018-06-25 14:08:41 +03:00
|
|
|
return new
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-03-26 08:35:20 +04:00
|
|
|
if mode == "P" and self.mode == "RGBA":
|
|
|
|
return self.quantize(colors)
|
|
|
|
|
2014-03-26 10:34:41 +04:00
|
|
|
trns = None
|
|
|
|
delete_trns = False
|
|
|
|
# transparency handling
|
2018-06-25 14:08:41 +03:00
|
|
|
if has_transparency:
|
2022-03-01 12:25:25 +03:00
|
|
|
if (self.mode in ("1", "L", "I") and mode in ("LA", "RGBA")) or (
|
|
|
|
self.mode == "RGB" and mode == "RGBA"
|
|
|
|
):
|
2014-03-26 10:34:41 +04:00
|
|
|
# Use transparent conversion to promote from transparent
|
2014-05-14 19:04:18 +04:00
|
|
|
# color to an alpha channel.
|
2019-03-21 16:28:20 +03:00
|
|
|
new_im = self._new(
|
|
|
|
self.im.convert_transparent(mode, self.info["transparency"])
|
|
|
|
)
|
|
|
|
del new_im.info["transparency"]
|
2017-07-18 16:00:09 +03:00
|
|
|
return new_im
|
2019-03-21 16:28:20 +03:00
|
|
|
elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"):
|
|
|
|
t = self.info["transparency"]
|
2014-03-26 10:34:41 +04:00
|
|
|
if isinstance(t, bytes):
|
|
|
|
# Dragons. This can't be represented by a single color
|
2019-03-21 16:28:20 +03:00
|
|
|
warnings.warn(
|
|
|
|
"Palette images with Transparency expressed in bytes should be "
|
|
|
|
"converted to RGBA images"
|
|
|
|
)
|
2014-03-26 10:34:41 +04:00
|
|
|
delete_trns = True
|
|
|
|
else:
|
|
|
|
# get the new transparency color.
|
|
|
|
# use existing conversions
|
2014-04-22 10:23:34 +04:00
|
|
|
trns_im = Image()._new(core.new(self.mode, (1, 1)))
|
2019-03-21 16:28:20 +03:00
|
|
|
if self.mode == "P":
|
2014-03-26 10:34:41 +04:00
|
|
|
trns_im.putpalette(self.palette)
|
2016-10-31 03:43:32 +03:00
|
|
|
if isinstance(t, tuple):
|
2021-06-23 12:37:56 +03:00
|
|
|
err = "Couldn't allocate a palette color for transparency"
|
2016-01-14 19:58:13 +03:00
|
|
|
try:
|
2021-06-23 11:41:46 +03:00
|
|
|
t = trns_im.palette.getcolor(t, self)
|
2021-06-23 12:28:46 +03:00
|
|
|
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:
|
2021-06-23 12:37:56 +03:00
|
|
|
raise ValueError(err) from e
|
2021-06-23 12:28:46 +03:00
|
|
|
if t is None:
|
|
|
|
trns = None
|
2014-03-26 10:34:41 +04:00
|
|
|
else:
|
2021-06-23 12:28:46 +03:00
|
|
|
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))
|
2014-05-14 19:04:18 +04:00
|
|
|
|
2021-07-12 15:55:12 +03:00
|
|
|
elif self.mode == "P" and mode in ("LA", "PA", "RGBA"):
|
2019-03-21 16:28:20 +03:00
|
|
|
t = self.info["transparency"]
|
2014-05-19 11:04:56 +04:00
|
|
|
delete_trns = True
|
2014-11-04 12:31:36 +03:00
|
|
|
|
2014-09-20 21:27:52 +04:00
|
|
|
if isinstance(t, bytes):
|
|
|
|
self.im.putpalettealphas(t)
|
|
|
|
elif isinstance(t, int):
|
2015-04-02 08:29:18 +03:00
|
|
|
self.im.putpalettealpha(t, 0)
|
2014-09-20 21:27:52 +04:00
|
|
|
else:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Transparency for P mode should be bytes or int"
|
|
|
|
raise ValueError(msg)
|
2014-09-20 21:27:52 +04:00
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
if mode == "P" and palette == Palette.ADAPTIVE:
|
2010-07-31 06:52:47 +04:00
|
|
|
im = self.im.quantize(colors)
|
2014-02-05 16:49:08 +04:00
|
|
|
new = self._new(im)
|
2017-01-17 16:22:18 +03:00
|
|
|
from . import ImagePalette
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2021-06-27 08:09:39 +03:00
|
|
|
new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB"))
|
2014-03-26 10:34:41 +04:00
|
|
|
if delete_trns:
|
|
|
|
# This could possibly happen if we requantize to fewer colors.
|
2014-05-14 19:04:18 +04:00
|
|
|
# The transparency would be totally off in that case.
|
2019-03-21 16:28:20 +03:00
|
|
|
del new.info["transparency"]
|
2014-03-26 10:34:41 +04:00
|
|
|
if trns is not None:
|
|
|
|
try:
|
2021-06-23 11:41:46 +03:00
|
|
|
new.info["transparency"] = new.palette.getcolor(trns, new)
|
2018-11-17 00:51:52 +03:00
|
|
|
except Exception:
|
2014-03-26 10:34:41 +04:00
|
|
|
# if we can't make a transparent color, don't leave the old
|
2014-03-26 11:01:10 +04:00
|
|
|
# transparency hanging around to mess us up.
|
2019-03-21 16:28:20 +03:00
|
|
|
del new.info["transparency"]
|
|
|
|
warnings.warn("Couldn't allocate palette entry for transparency")
|
2014-02-05 16:49:08 +04:00
|
|
|
return new
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2022-10-07 14:33:45 +03:00
|
|
|
if "LAB" in (self.mode, mode):
|
|
|
|
other_mode = mode if self.mode == "LAB" else self.mode
|
|
|
|
if other_mode in ("RGB", "RGBA", "RGBX"):
|
|
|
|
from . import ImageCms
|
|
|
|
|
|
|
|
srgb = ImageCms.createProfile("sRGB")
|
|
|
|
lab = ImageCms.createProfile("LAB")
|
|
|
|
profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab]
|
|
|
|
transform = ImageCms.buildTransform(
|
|
|
|
profiles[0], profiles[1], self.mode, mode
|
|
|
|
)
|
|
|
|
return transform.apply(self)
|
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
# colorspace conversion
|
2010-07-31 06:52:47 +04:00
|
|
|
if dither is None:
|
2022-01-15 01:02:31 +03:00
|
|
|
dither = Dither.FLOYDSTEINBERG
|
2014-05-14 19:04:18 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
try:
|
|
|
|
im = self.im.convert(mode, dither)
|
|
|
|
except ValueError:
|
|
|
|
try:
|
|
|
|
# normalize source image and try again
|
2022-10-07 01:48:56 +03:00
|
|
|
modebase = getmodebase(self.mode)
|
|
|
|
if modebase == self.mode:
|
|
|
|
raise
|
|
|
|
im = self.im.convert(modebase)
|
2010-07-31 06:52:47 +04:00
|
|
|
im = im.convert(mode, dither)
|
2020-06-21 13:13:35 +03:00
|
|
|
except KeyError as e:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "illegal conversion"
|
|
|
|
raise ValueError(msg) from e
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-03-26 10:34:41 +04:00
|
|
|
new_im = self._new(im)
|
2022-01-15 01:02:31 +03:00
|
|
|
if mode == "P" and palette != Palette.ADAPTIVE:
|
2021-06-23 12:22:21 +03:00
|
|
|
from . import ImagePalette
|
|
|
|
|
|
|
|
new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3)
|
2014-03-26 10:34:41 +04:00
|
|
|
if delete_trns:
|
2014-04-26 20:43:53 +04:00
|
|
|
# crash fail if we leave a bytes transparency in an rgb/l mode.
|
2019-03-21 16:28:20 +03:00
|
|
|
del new_im.info["transparency"]
|
2014-03-26 10:34:41 +04:00
|
|
|
if trns is not None:
|
2019-03-21 16:28:20 +03:00
|
|
|
if new_im.mode == "P":
|
2014-03-26 11:01:10 +04:00
|
|
|
try:
|
2021-06-23 11:41:46 +03:00
|
|
|
new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im)
|
2021-06-23 12:28:46 +03:00
|
|
|
except ValueError as e:
|
2019-03-21 16:28:20 +03:00
|
|
|
del new_im.info["transparency"]
|
2021-06-23 12:28:46 +03:00
|
|
|
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"
|
|
|
|
)
|
2014-03-26 11:01:10 +04:00
|
|
|
else:
|
2019-03-21 16:28:20 +03:00
|
|
|
new_im.info["transparency"] = trns
|
2014-03-26 10:34:41 +04:00
|
|
|
return new_im
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2022-02-19 02:49:46 +03:00
|
|
|
def quantize(
|
|
|
|
self,
|
|
|
|
colors=256,
|
|
|
|
method=None,
|
|
|
|
kmeans=0,
|
|
|
|
palette=None,
|
|
|
|
dither=Dither.FLOYDSTEINBERG,
|
|
|
|
):
|
2014-11-20 01:26:07 +03:00
|
|
|
"""
|
|
|
|
Convert the image to 'P' mode with the specified number
|
|
|
|
of colors.
|
2014-11-28 04:21:03 +03:00
|
|
|
|
2014-11-20 01:26:07 +03:00
|
|
|
:param colors: The desired number of colors, <= 256
|
2022-01-15 01:02:31 +03:00
|
|
|
:param method: :data:`Quantize.MEDIANCUT` (median cut),
|
|
|
|
:data:`Quantize.MAXCOVERAGE` (maximum coverage),
|
|
|
|
:data:`Quantize.FASTOCTREE` (fast octree),
|
|
|
|
:data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support
|
|
|
|
using :py:func:`PIL.features.check_feature` with
|
|
|
|
``feature="libimagequant"``).
|
|
|
|
|
|
|
|
By default, :data:`Quantize.MEDIANCUT` will be used.
|
|
|
|
|
|
|
|
The exception to this is RGBA images. :data:`Quantize.MEDIANCUT`
|
|
|
|
and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so
|
|
|
|
:data:`Quantize.FASTOCTREE` is used by default instead.
|
2014-11-20 01:26:07 +03:00
|
|
|
:param kmeans: Integer
|
2018-10-21 10:26:08 +03:00
|
|
|
:param palette: Quantize to the palette of given
|
|
|
|
:py:class:`PIL.Image.Image`.
|
2019-03-09 02:36:13 +03:00
|
|
|
:param dither: Dithering method, used when converting from
|
|
|
|
mode "RGB" to "P" or from "RGB" or "L" to "1".
|
2022-01-15 01:02:31 +03:00
|
|
|
Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG`
|
|
|
|
(default).
|
2014-11-28 04:21:03 +03:00
|
|
|
:returns: A new image
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-11-20 01:26:07 +03:00
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.load()
|
2014-05-14 19:04:18 +04:00
|
|
|
|
2014-03-26 08:35:20 +04:00
|
|
|
if method is None:
|
|
|
|
# defaults:
|
2022-01-15 01:02:31 +03:00
|
|
|
method = Quantize.MEDIANCUT
|
2019-03-21 16:28:20 +03:00
|
|
|
if self.mode == "RGBA":
|
2022-01-15 01:02:31 +03:00
|
|
|
method = Quantize.FASTOCTREE
|
2014-03-26 08:35:20 +04:00
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
if self.mode == "RGBA" and method not in (
|
|
|
|
Quantize.FASTOCTREE,
|
|
|
|
Quantize.LIBIMAGEQUANT,
|
|
|
|
):
|
2014-05-14 19:04:18 +04:00
|
|
|
# Caller specified an invalid mode.
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = (
|
2019-03-21 16:28:20 +03:00
|
|
|
"Fast Octree (method == 2) and libimagequant (method == 3) "
|
|
|
|
"are the only valid methods for quantizing RGBA images"
|
|
|
|
)
|
2022-12-22 00:51:35 +03:00
|
|
|
raise ValueError(msg)
|
2014-05-14 19:04:18 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
if palette:
|
|
|
|
# use palette from reference image
|
|
|
|
palette.load()
|
|
|
|
if palette.mode != "P":
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "bad mode for palette image"
|
|
|
|
raise ValueError(msg)
|
2010-07-31 06:52:47 +04:00
|
|
|
if self.mode != "RGB" and self.mode != "L":
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "only RGB or L mode images can be quantized to a palette"
|
|
|
|
raise ValueError(msg)
|
2019-03-09 02:36:13 +03:00
|
|
|
im = self.im.convert("P", dither, palette.im)
|
2021-08-30 17:33:10 +03:00
|
|
|
new_im = self._new(im)
|
|
|
|
new_im.palette = palette.palette.copy()
|
|
|
|
return new_im
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2019-03-16 05:36:58 +03:00
|
|
|
im = self._new(self.im.quantize(colors, method, kmeans))
|
|
|
|
|
|
|
|
from . import ImagePalette
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2019-03-16 05:36:58 +03:00
|
|
|
mode = im.im.getpalettemode()
|
2021-12-11 08:23:37 +03:00
|
|
|
palette = im.im.getpalette(mode, mode)[: colors * len(mode)]
|
|
|
|
im.palette = ImagePalette.ImagePalette(mode, palette)
|
2019-03-16 05:36:58 +03:00
|
|
|
|
|
|
|
return im
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def copy(self):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Copies this image. Use this method if you wish to paste things
|
|
|
|
into an image, but still retain the original.
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
:rtype: :py:class:`~PIL.Image.Image`
|
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
self.load()
|
2016-06-02 10:06:49 +03:00
|
|
|
return self._new(self.im.copy())
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2016-03-16 12:23:51 +03:00
|
|
|
__copy__ = copy
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def crop(self, box=None):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Returns a rectangular region from this image. The box is a
|
|
|
|
4-tuple defining the left, upper, right, and lower pixel
|
2018-06-24 07:34:01 +03:00
|
|
|
coordinate. See :ref:`coordinate-system`.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
2016-10-04 03:06:35 +03:00
|
|
|
Note: Prior to Pillow 3.4.0, this was a lazy operation.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
|
|
|
:param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
|
2013-10-12 09:18:40 +04:00
|
|
|
:rtype: :py:class:`~PIL.Image.Image`
|
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
if box is None:
|
|
|
|
return self.copy()
|
|
|
|
|
2022-01-18 08:38:00 +03:00
|
|
|
if box[2] < box[0]:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Coordinate 'right' is less than 'left'"
|
|
|
|
raise ValueError(msg)
|
2022-01-18 08:38:00 +03:00
|
|
|
elif box[3] < box[1]:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Coordinate 'lower' is less than 'upper'"
|
|
|
|
raise ValueError(msg)
|
2022-01-18 08:38:00 +03:00
|
|
|
|
2017-06-22 13:24:21 +03:00
|
|
|
self.load()
|
2017-02-17 18:07:14 +03:00
|
|
|
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.
|
|
|
|
"""
|
|
|
|
|
2016-09-29 23:28:24 +03:00
|
|
|
x0, y0, x1, y1 = map(int, map(round, box))
|
|
|
|
|
2018-08-23 16:40:46 +03:00
|
|
|
absolute_values = (abs(x1 - x0), abs(y1 - y0))
|
2016-09-29 23:28:24 +03:00
|
|
|
|
2018-08-23 16:40:46 +03:00
|
|
|
_decompression_bomb_check(absolute_values)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2017-02-17 18:07:14 +03:00
|
|
|
return im.crop((x0, y0, x1, y1))
|
2017-07-16 10:37:51 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def draft(self, mode, size):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Configures the image file loader so it returns a version of the
|
|
|
|
image that as closely as possible matches the given mode and
|
2019-11-24 04:33:34 +03:00
|
|
|
size. For example, you can use this method to convert a color
|
2019-12-24 06:50:53 +03:00
|
|
|
JPEG to greyscale while loading it.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
2019-11-30 18:17:10 +03:00
|
|
|
If any changes are made, returns a tuple with the chosen ``mode`` and
|
|
|
|
``box`` with coordinates of the original image within the altered one.
|
2019-11-24 04:55:49 +03:00
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
Note that this method modifies the :py:class:`~PIL.Image.Image` object
|
2019-11-24 04:33:34 +03:00
|
|
|
in place. If the image has already been loaded, this method has no
|
2013-10-12 09:18:40 +04:00
|
|
|
effect.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
2017-06-14 00:23:18 +03:00
|
|
|
Note: This method is not implemented for most images. It is
|
2019-12-24 06:50:53 +03:00
|
|
|
currently implemented only for JPEG and MPO images.
|
2017-02-17 17:22:40 +03:00
|
|
|
|
2013-07-09 18:32:14 +04:00
|
|
|
:param mode: The requested mode.
|
2023-01-02 00:41:50 +03:00
|
|
|
:param size: The requested size in pixels, as a 2-tuple:
|
|
|
|
(width, height).
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
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):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Filters this image using the given filter. For a list of
|
2013-10-12 09:18:40 +04:00
|
|
|
available filters, see the :py:mod:`~PIL.ImageFilter` module.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
|
|
|
:param filter: Filter kernel.
|
2020-09-01 20:16:46 +03:00
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object."""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2017-09-10 12:59:51 +03:00
|
|
|
from . import ImageFilter
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
self.load()
|
|
|
|
|
2018-05-06 15:31:43 +03:00
|
|
|
if isinstance(filter, Callable):
|
2010-07-31 06:52:47 +04:00
|
|
|
filter = filter()
|
|
|
|
if not hasattr(filter, "filter"):
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "filter argument should be ImageFilter.Filter instance or class"
|
|
|
|
raise TypeError(msg)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2017-09-10 12:59:51 +03:00
|
|
|
multiband = isinstance(filter, ImageFilter.MultibandFilter)
|
2017-08-13 00:03:50 +03:00
|
|
|
if self.im.bands == 1 or multiband:
|
2010-07-31 06:52:47 +04:00
|
|
|
return self._new(filter.filter(self.im))
|
2017-09-10 12:59:51 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
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):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Returns a tuple containing the name of each band in this image.
|
2020-09-01 20:16:46 +03:00
|
|
|
For example, ``getbands`` on an RGB image returns ("R", "G", "B").
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2013-07-09 18:32:14 +04:00
|
|
|
:returns: A tuple containing band names.
|
|
|
|
:rtype: tuple
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
return ImageMode.getmode(self.mode).bands
|
|
|
|
|
|
|
|
def getbbox(self):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Calculates the bounding box of the non-zero regions in the
|
|
|
|
image.
|
|
|
|
|
|
|
|
:returns: The bounding box is returned as a 4-tuple defining the
|
2018-06-24 07:34:01 +03:00
|
|
|
left, upper, right, and lower pixel coordinate. See
|
|
|
|
:ref:`coordinate-system`. If the image is completely empty, this
|
|
|
|
method returns None.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.load()
|
|
|
|
return self.im.getbbox()
|
|
|
|
|
|
|
|
def getcolors(self, maxcolors=256):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Returns a list of colors used in this image.
|
|
|
|
|
2021-01-09 13:30:16 +03:00
|
|
|
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.
|
|
|
|
|
2013-07-09 18:32:14 +04:00
|
|
|
: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.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
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)
|
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
def getdata(self, band=None):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
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
|
2020-09-01 20:16:46 +03:00
|
|
|
printing), use ``list(im.getdata())``.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
|
|
|
: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.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.load()
|
|
|
|
if band is not None:
|
|
|
|
return self.im.getband(band)
|
2014-04-22 10:23:34 +04:00
|
|
|
return self.im # could be abused
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def getextrema(self):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2022-05-14 07:46:46 +03:00
|
|
|
Gets the minimum and maximum pixel values for each band in
|
2013-07-09 18:32:14 +04:00
|
|
|
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.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
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()
|
|
|
|
|
2021-06-12 06:57:14 +03:00
|
|
|
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
|
|
|
|
|
2021-06-30 04:28:00 +03:00
|
|
|
if ElementTree is None:
|
2021-06-30 04:23:57 +03:00
|
|
|
warnings.warn("XMP data cannot be read without defusedxml dependency")
|
2021-06-30 04:28:00 +03:00
|
|
|
return {}
|
|
|
|
else:
|
|
|
|
root = ElementTree.fromstring(xmp_tags)
|
|
|
|
return {get_name(root.tag): get_value(root)}
|
2021-06-12 06:57:14 +03:00
|
|
|
|
2019-04-01 12:03:02 +03:00
|
|
|
def getexif(self):
|
2019-08-22 23:13:20 +03:00
|
|
|
if self._exif is None:
|
|
|
|
self._exif = Exif()
|
2022-05-27 00:54:54 +03:00
|
|
|
self._exif._loaded = False
|
|
|
|
elif self._exif._loaded:
|
|
|
|
return self._exif
|
|
|
|
self._exif._loaded = True
|
2020-04-16 14:14:19 +03:00
|
|
|
|
|
|
|
exif_info = self.info.get("exif")
|
2021-04-19 12:46:49 +03:00
|
|
|
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"):
|
2022-03-01 01:23:12 +03:00
|
|
|
self._exif.bigtiff = self.tag_v2._bigtiff
|
2021-04-19 12:46:49 +03:00
|
|
|
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)
|
2020-04-16 14:14:19 +03:00
|
|
|
|
|
|
|
# XMP tags
|
|
|
|
if 0x0112 not in self._exif:
|
|
|
|
xmp_tags = self.info.get("XML:com.adobe.xmp")
|
|
|
|
if xmp_tags:
|
2022-07-26 04:58:44 +03:00
|
|
|
match = re.search(r'tiff:Orientation(="|>)([0-9])', xmp_tags)
|
2021-06-30 04:20:55 +03:00
|
|
|
if match:
|
2022-07-26 04:58:44 +03:00
|
|
|
self._exif[0x0112] = int(match[2])
|
2020-04-16 14:14:19 +03:00
|
|
|
|
2019-08-22 23:13:20 +03:00
|
|
|
return self._exif
|
2019-04-01 12:03:02 +03:00
|
|
|
|
2022-05-27 00:54:54 +03:00
|
|
|
def _reload_exif(self):
|
|
|
|
if self._exif is None or not self._exif._loaded:
|
|
|
|
return
|
|
|
|
self._exif._loaded = False
|
|
|
|
self.getexif()
|
|
|
|
|
2022-12-06 11:30:53 +03:00
|
|
|
def get_child_images(self):
|
|
|
|
child_images = []
|
|
|
|
exif = self.getexif()
|
|
|
|
ifds = []
|
|
|
|
if ExifTags.Base.SubIFDs in exif:
|
|
|
|
subifd_offsets = exif[ExifTags.Base.SubIFDs]
|
|
|
|
if subifd_offsets:
|
|
|
|
if not isinstance(subifd_offsets, tuple):
|
|
|
|
subifd_offsets = (subifd_offsets,)
|
|
|
|
for subifd_offset in subifd_offsets:
|
|
|
|
ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset))
|
|
|
|
ifd1 = exif.get_ifd(ExifTags.IFD.IFD1)
|
|
|
|
if ifd1 and ifd1.get(513):
|
|
|
|
ifds.append((ifd1, exif._info.next))
|
|
|
|
|
|
|
|
offset = None
|
|
|
|
for ifd, ifd_offset in ifds:
|
|
|
|
current_offset = self.fp.tell()
|
|
|
|
if offset is None:
|
|
|
|
offset = current_offset
|
|
|
|
|
|
|
|
fp = self.fp
|
2022-12-13 22:48:36 +03:00
|
|
|
thumbnail_offset = ifd.get(513)
|
|
|
|
if thumbnail_offset is not None:
|
2022-12-06 11:30:53 +03:00
|
|
|
try:
|
2022-12-13 22:48:36 +03:00
|
|
|
thumbnail_offset += self._exif_offset
|
2022-12-06 11:30:53 +03:00
|
|
|
except AttributeError:
|
|
|
|
pass
|
2022-12-13 22:48:36 +03:00
|
|
|
self.fp.seek(thumbnail_offset)
|
2022-12-06 11:30:53 +03:00
|
|
|
data = self.fp.read(ifd.get(514))
|
|
|
|
fp = io.BytesIO(data)
|
|
|
|
|
|
|
|
with open(fp) as im:
|
2022-12-13 22:48:36 +03:00
|
|
|
if thumbnail_offset is None:
|
2022-12-06 11:30:53 +03:00
|
|
|
im._frame_pos = [ifd_offset]
|
|
|
|
im._seek(0)
|
|
|
|
im.load()
|
|
|
|
child_images.append(im)
|
|
|
|
|
|
|
|
if offset is not None:
|
|
|
|
self.fp.seek(offset)
|
|
|
|
return child_images
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def getim(self):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Returns a capsule that points to the internal image memory.
|
|
|
|
|
|
|
|
:returns: A capsule object.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.load()
|
|
|
|
return self.im.ptr
|
|
|
|
|
2022-02-17 02:04:43 +03:00
|
|
|
def getpalette(self, rawmode="RGB"):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Returns the image palette as a list.
|
|
|
|
|
2022-02-17 02:35:13 +03:00
|
|
|
:param rawmode: The mode in which to return the palette. ``None`` will
|
|
|
|
return the palette in its current mode.
|
2022-02-19 14:55:23 +03:00
|
|
|
|
|
|
|
.. versionadded:: 9.1.0
|
|
|
|
|
2013-07-09 18:32:14 +04:00
|
|
|
:returns: A list of color values [r, g, b, ...], or None if the
|
|
|
|
image has no palette.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.load()
|
|
|
|
try:
|
2022-02-17 02:04:43 +03:00
|
|
|
mode = self.im.getpalettemode()
|
2010-07-31 06:52:47 +04:00
|
|
|
except ValueError:
|
2014-04-22 10:23:34 +04:00
|
|
|
return None # no palette
|
2022-02-17 02:35:13 +03:00
|
|
|
if rawmode is None:
|
|
|
|
rawmode = mode
|
2022-02-17 02:04:43 +03:00
|
|
|
return list(self.im.getpalette(mode, rawmode))
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2022-06-06 15:47:58 +03:00
|
|
|
def apply_transparency(self):
|
|
|
|
"""
|
|
|
|
If a P mode image has a "transparency" key in the info dictionary,
|
2022-12-11 22:36:27 +03:00
|
|
|
remove the key and instead apply the transparency to the palette.
|
|
|
|
Otherwise, the image is unchanged.
|
2022-06-06 15:47:58 +03:00
|
|
|
"""
|
|
|
|
if self.mode != "P" or "transparency" not in self.info:
|
|
|
|
return
|
|
|
|
|
|
|
|
from . import ImagePalette
|
|
|
|
|
|
|
|
palette = self.getpalette("RGBA")
|
|
|
|
transparency = self.info["transparency"]
|
|
|
|
if isinstance(transparency, bytes):
|
|
|
|
for i, alpha in enumerate(transparency):
|
|
|
|
palette[i * 4 + 3] = alpha
|
|
|
|
else:
|
|
|
|
palette[transparency * 4 + 3] = 0
|
|
|
|
self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette))
|
|
|
|
self.palette.dirty = 1
|
|
|
|
|
|
|
|
del self.info["transparency"]
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def getpixel(self, xy):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Returns the pixel value at a given position.
|
|
|
|
|
2018-06-24 07:34:01 +03:00
|
|
|
:param xy: The coordinate, given as (x, y). See
|
|
|
|
:ref:`coordinate-system`.
|
2013-07-09 18:32:14 +04:00
|
|
|
:returns: The pixel value. If the image is a multi-layer image,
|
|
|
|
this method returns a tuple.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.load()
|
2014-01-05 22:41:25 +04:00
|
|
|
if self.pyaccess:
|
|
|
|
return self.pyaccess.getpixel(xy)
|
2010-07-31 06:52:47 +04:00
|
|
|
return self.im.getpixel(xy)
|
|
|
|
|
|
|
|
def getprojection(self):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
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.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.load()
|
|
|
|
x, y = self.im.getprojection()
|
2020-05-08 19:48:02 +03:00
|
|
|
return list(x), list(y)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def histogram(self, mask=None, extrema=None):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2022-03-02 13:21:25 +03:00
|
|
|
Returns a histogram for the image. The histogram is returned as a
|
|
|
|
list of pixel counts, one for each pixel value in the source
|
|
|
|
image. Counts are grouped into 256 bins for each band, even if
|
|
|
|
the image has more than 8 bits per band. If the image has more
|
|
|
|
than one band, the histograms for all bands are concatenated (for
|
|
|
|
example, the histogram for an "RGB" image contains 768 values).
|
2013-07-09 18:32:14 +04:00
|
|
|
|
|
|
|
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.
|
Added an `image.entropy()` method
This calculates the entropy for the image, based on the histogram.
Because this uses image histogram data directly, the existing C
function underpinning the `image.histogram()` method was abstracted
into a static function to parse extrema tuple arguments, and a new
C function was added to calculate image entropy, making use of the
new static extrema function.
The extrema-parsing function was written by @homm, based on the
macro abstraction I wrote, during the discussion of my first
entropy-method pull request: https://git.io/fhodS
The new `image.entropy()` method is based on `image.histogram()`,
and will accept the same arguments to calculate the histogram data
it will use to assess the entropy of the image.
The algorithm and methodology is based on existing Python code:
* https://git.io/fhmIU
... A test case in the `Tests/` directory, and doctest lines in
`selftest.py`, have both been added and checked.
Changes proposed in this pull request:
* Added “math.h” include to _imaging.c
* The addition of an `image.entropy()` method to the `Image`
Python class,
* The abstraction of the extrema-parsing logic of of the C
function `_histogram` into a static function, and
* The use of that static function in both the `_histogram` and
`_entropy` C functions.
* Minor documentation addenda in the docstrings for both the
`image.entropy()` and `image.histogram()` methods were also
added.
* Removed outdated boilerplate from testing code
* Removed unused “unittest” import
2019-01-25 20:38:11 +03:00
|
|
|
:param extrema: An optional tuple of manually-specified extrema.
|
2013-07-09 18:32:14 +04:00
|
|
|
:returns: A list containing pixel counts.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
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()
|
|
|
|
|
Added an `image.entropy()` method
This calculates the entropy for the image, based on the histogram.
Because this uses image histogram data directly, the existing C
function underpinning the `image.histogram()` method was abstracted
into a static function to parse extrema tuple arguments, and a new
C function was added to calculate image entropy, making use of the
new static extrema function.
The extrema-parsing function was written by @homm, based on the
macro abstraction I wrote, during the discussion of my first
entropy-method pull request: https://git.io/fhodS
The new `image.entropy()` method is based on `image.histogram()`,
and will accept the same arguments to calculate the histogram data
it will use to assess the entropy of the image.
The algorithm and methodology is based on existing Python code:
* https://git.io/fhmIU
... A test case in the `Tests/` directory, and doctest lines in
`selftest.py`, have both been added and checked.
Changes proposed in this pull request:
* Added “math.h” include to _imaging.c
* The addition of an `image.entropy()` method to the `Image`
Python class,
* The abstraction of the extrema-parsing logic of of the C
function `_histogram` into a static function, and
* The use of that static function in both the `_histogram` and
`_entropy` C functions.
* Minor documentation addenda in the docstrings for both the
`image.entropy()` and `image.histogram()` methods were also
added.
* Removed outdated boilerplate from testing code
* Removed unused “unittest” import
2019-01-25 20:38:11 +03:00
|
|
|
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()
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def paste(self, im, box=None, mask=None):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
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
|
2018-06-24 07:34:01 +03:00
|
|
|
(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.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
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
|
2013-07-09 18:32:14 +04:00
|
|
|
details).
|
|
|
|
|
|
|
|
Instead of an image, the source can be a integer or tuple
|
|
|
|
containing pixel values. The method then fills the region
|
2013-10-12 09:18:40 +04:00
|
|
|
with the given color. When creating RGB images, you can
|
|
|
|
also use color strings as supported by the ImageColor module.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
|
|
|
If a mask is given, this method updates only the regions
|
2022-03-01 13:05:42 +03:00
|
|
|
indicated by the mask. You can use either "1", "L", "LA", "RGBA"
|
|
|
|
or "RGBa" images (if present, the alpha band is used as mask).
|
2013-07-09 18:32:14 +04:00
|
|
|
Where the mask is 255, the given image is copied as is. Where
|
|
|
|
the mask is 0, the current value is preserved. Intermediate
|
2015-04-11 06:23:26 +03:00
|
|
|
values will mix the two images together, including their alpha
|
|
|
|
channels if they have them.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
2015-04-08 22:57:17 +03:00
|
|
|
See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to
|
2015-04-11 06:24:30 +03:00
|
|
|
combine images with respect to their alpha channels.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
|
|
|
: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.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
if isImageType(box) and mask is None:
|
|
|
|
# abbreviated paste(im, mask) syntax
|
2014-04-22 10:23:34 +04:00
|
|
|
mask = box
|
|
|
|
box = None
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
if box is None:
|
2016-11-10 11:55:56 +03:00
|
|
|
box = (0, 0)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
if len(box) == 2:
|
2016-01-31 03:57:02 +03:00
|
|
|
# upper left corner given; get size from image or mask
|
2010-07-31 06:52:47 +04:00
|
|
|
if isImageType(im):
|
|
|
|
size = im.size
|
|
|
|
elif isImageType(mask):
|
|
|
|
size = mask.size
|
|
|
|
else:
|
|
|
|
# FIXME: use self.size here?
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "cannot determine region size; use 4-item box"
|
|
|
|
raise ValueError(msg)
|
2019-03-21 16:28:20 +03:00
|
|
|
box += (box[0] + size[0], box[1] + size[1])
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2019-10-08 17:01:11 +03:00
|
|
|
if isinstance(im, str):
|
2017-01-17 16:22:18 +03:00
|
|
|
from . import ImageColor
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
im = ImageColor.getcolor(im, self.mode)
|
|
|
|
|
|
|
|
elif isImageType(im):
|
|
|
|
im.load()
|
|
|
|
if self.mode != im.mode:
|
2022-03-01 13:05:42 +03:00
|
|
|
if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"):
|
2010-07-31 06:52:47 +04:00
|
|
|
# should use an adapter for this!
|
|
|
|
im = im.convert(self.mode)
|
|
|
|
im = im.im
|
|
|
|
|
2017-09-29 11:39:56 +03:00
|
|
|
self._ensure_mutable()
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
if mask:
|
|
|
|
mask.load()
|
|
|
|
self.im.paste(im, box, mask.im)
|
|
|
|
else:
|
|
|
|
self.im.paste(im, box)
|
|
|
|
|
2018-03-06 11:53:07 +03:00
|
|
|
def alpha_composite(self, im, dest=(0, 0), source=(0, 0)):
|
2020-09-01 20:16:46 +03:00
|
|
|
"""'In-place' analog of Image.alpha_composite. Composites an image
|
2017-06-29 15:14:43 +03:00
|
|
|
onto this image.
|
2017-06-20 19:54:59 +03:00
|
|
|
|
|
|
|
:param im: image to composite over this one
|
2017-07-16 10:37:51 +03:00
|
|
|
:param dest: Optional 2 tuple (left, top) specifying the upper
|
2017-06-29 15:14:43 +03:00
|
|
|
left corner in this (destination) image.
|
2017-07-16 10:37:51 +03:00
|
|
|
: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
|
|
|
|
|
2017-06-29 15:14:43 +03:00
|
|
|
Performance Note: Not currently implemented in-place in the core layer.
|
2017-06-20 19:54:59 +03:00
|
|
|
"""
|
2017-06-26 22:04:44 +03:00
|
|
|
|
2017-09-01 13:36:25 +03:00
|
|
|
if not isinstance(source, (list, tuple)):
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Source must be a tuple"
|
|
|
|
raise ValueError(msg)
|
2017-09-01 13:36:25 +03:00
|
|
|
if not isinstance(dest, (list, tuple)):
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Destination must be a tuple"
|
|
|
|
raise ValueError(msg)
|
2017-06-28 00:03:38 +03:00
|
|
|
if not len(source) in (2, 4):
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Source must be a 2 or 4-tuple"
|
|
|
|
raise ValueError(msg)
|
2017-06-28 00:03:38 +03:00
|
|
|
if not len(dest) == 2:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Destination must be a 2-tuple"
|
|
|
|
raise ValueError(msg)
|
2017-06-26 22:04:44 +03:00
|
|
|
if min(source) < 0:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Source must be non-negative"
|
|
|
|
raise ValueError(msg)
|
2017-06-28 00:03:38 +03:00
|
|
|
|
|
|
|
if len(source) == 2:
|
|
|
|
source = source + im.size
|
|
|
|
|
2017-07-16 10:37:51 +03:00
|
|
|
# over image, crop if it's not the whole thing.
|
2018-03-06 11:53:07 +03:00
|
|
|
if source == (0, 0) + im.size:
|
2017-06-20 19:54:59 +03:00
|
|
|
overlay = im
|
|
|
|
else:
|
2017-06-28 00:03:38 +03:00
|
|
|
overlay = im.crop(source)
|
|
|
|
|
|
|
|
# target for the paste
|
|
|
|
box = dest + (dest[0] + overlay.width, dest[1] + overlay.height)
|
2017-07-16 10:37:51 +03:00
|
|
|
|
2017-06-28 00:03:38 +03:00
|
|
|
# destination image. don't copy if we're using the whole image.
|
2018-03-06 11:53:07 +03:00
|
|
|
if box == (0, 0) + self.size:
|
2017-06-28 00:03:38 +03:00
|
|
|
background = self
|
|
|
|
else:
|
|
|
|
background = self.crop(box)
|
2017-07-16 10:37:51 +03:00
|
|
|
|
2017-06-28 00:03:38 +03:00
|
|
|
result = alpha_composite(background, overlay)
|
2017-06-20 19:54:59 +03:00
|
|
|
self.paste(result, box)
|
2017-07-16 10:37:51 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def point(self, lut, mode=None):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Maps this image through a lookup table or function.
|
|
|
|
|
2018-01-27 08:19:02 +03:00
|
|
|
:param lut: A lookup table, containing 256 (or 65536 if
|
2013-12-11 04:05:05 +04:00
|
|
|
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.
|
2020-07-09 20:48:42 +03:00
|
|
|
|
|
|
|
It may also be an :py:class:`~PIL.Image.ImagePointHandler`
|
|
|
|
object::
|
|
|
|
|
|
|
|
class Example(Image.ImagePointHandler):
|
|
|
|
def point(self, data):
|
|
|
|
# Return result
|
2013-07-09 18:32:14 +04:00
|
|
|
:param mode: Output mode (default is same as input). In the
|
|
|
|
current version, this can only be used if the source image
|
2013-12-11 04:05:05 +04:00
|
|
|
has mode "L" or "P", and the output has mode "1" or the
|
|
|
|
source image mode is "I" and the output mode is "L".
|
2013-10-12 09:18:40 +04:00
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.load()
|
|
|
|
|
|
|
|
if isinstance(lut, ImagePointHandler):
|
|
|
|
return lut.point(self)
|
|
|
|
|
2013-12-11 03:47:26 +04:00
|
|
|
if callable(lut):
|
2010-07-31 06:52:47 +04:00
|
|
|
# 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
|
2013-12-11 04:05:05 +04:00
|
|
|
# UNDONE wiredfool -- I think this prevents us from ever doing
|
2014-05-14 19:04:18 +04:00
|
|
|
# a gamma function point transform on > 8bit images.
|
2010-07-31 06:52:47 +04:00
|
|
|
scale, offset = _getscaleoffset(lut)
|
|
|
|
return self._new(self.im.point_transform(scale, offset))
|
|
|
|
# for other modes, convert the function to a table
|
2012-10-16 05:58:46 +04:00
|
|
|
lut = [lut(i) for i in range(256)] * self.im.bands
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
if self.mode == "F":
|
|
|
|
# FIXME: _imaging returns a confusing error message for this case
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "point operation not supported for this mode"
|
|
|
|
raise ValueError(msg)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2022-04-07 01:58:57 +03:00
|
|
|
if mode != "F":
|
|
|
|
lut = [round(i) for i in lut]
|
2010-07-31 06:52:47 +04:00
|
|
|
return self._new(self.im.point(lut, mode))
|
|
|
|
|
|
|
|
def putalpha(self, alpha):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
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.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2017-09-29 11:39:56 +03:00
|
|
|
self._ensure_mutable()
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2019-03-19 03:13:58 +03:00
|
|
|
if self.mode not in ("LA", "PA", "RGBA"):
|
2010-07-31 06:52:47 +04:00
|
|
|
# attempt to promote self to a matching alpha mode
|
|
|
|
try:
|
|
|
|
mode = getmodebase(self.mode) + "A"
|
|
|
|
try:
|
|
|
|
self.im.setmode(mode)
|
2020-06-21 13:13:35 +03:00
|
|
|
except (AttributeError, ValueError) as e:
|
2010-07-31 06:52:47 +04:00
|
|
|
# do things the hard way
|
|
|
|
im = self.im.convert(mode)
|
2019-03-19 03:13:58 +03:00
|
|
|
if im.mode not in ("LA", "PA", "RGBA"):
|
2020-06-21 13:13:35 +03:00
|
|
|
raise ValueError from e # sanity check
|
2010-07-31 06:52:47 +04:00
|
|
|
self.im = im
|
2017-09-06 04:21:50 +03:00
|
|
|
self.pyaccess = None
|
2010-07-31 06:52:47 +04:00
|
|
|
self.mode = self.im.mode
|
2020-12-12 15:36:57 +03:00
|
|
|
except KeyError as e:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "illegal image mode"
|
|
|
|
raise ValueError(msg) from e
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2019-03-19 03:13:58 +03:00
|
|
|
if self.mode in ("LA", "PA"):
|
2010-07-31 06:52:47 +04:00
|
|
|
band = 1
|
|
|
|
else:
|
|
|
|
band = 3
|
|
|
|
|
|
|
|
if isImageType(alpha):
|
|
|
|
# alpha layer
|
|
|
|
if alpha.mode not in ("1", "L"):
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "illegal image mode"
|
|
|
|
raise ValueError(msg)
|
2010-07-31 06:52:47 +04:00
|
|
|
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):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2021-12-27 08:11:43 +03:00
|
|
|
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.
|
2013-07-09 18:32:14 +04:00
|
|
|
:param scale: An optional scale value. The default is 1.0.
|
|
|
|
:param offset: An optional offset value. The default is 0.0.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2017-09-29 11:39:56 +03:00
|
|
|
self._ensure_mutable()
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.im.putdata(data, scale, offset)
|
|
|
|
|
|
|
|
def putpalette(self, data, rawmode="RGB"):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2020-12-12 06:12:30 +03:00
|
|
|
Attaches a palette to this image. The image must be a "P", "PA", "L"
|
|
|
|
or "LA" image.
|
|
|
|
|
2021-07-25 09:32:59 +03:00
|
|
|
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.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
|
|
|
:param data: A palette sequence (either a list or a string).
|
2022-02-14 12:28:47 +03:00
|
|
|
:param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode
|
|
|
|
that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L").
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2017-01-17 16:22:18 +03:00
|
|
|
from . import ImagePalette
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2019-03-20 00:13:56 +03:00
|
|
|
if self.mode not in ("L", "LA", "P", "PA"):
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "illegal image mode"
|
|
|
|
raise ValueError(msg)
|
2010-07-31 06:52:47 +04:00
|
|
|
if isinstance(data, ImagePalette.ImagePalette):
|
|
|
|
palette = ImagePalette.raw(data.rawmode, data.palette)
|
|
|
|
else:
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
if not isinstance(data, bytes):
|
2019-09-26 15:12:28 +03:00
|
|
|
data = bytes(data)
|
2010-07-31 06:52:47 +04:00
|
|
|
palette = ImagePalette.raw(rawmode, data)
|
2019-03-20 00:13:56 +03:00
|
|
|
self.mode = "PA" if "A" in self.mode else "P"
|
2010-07-31 06:52:47 +04:00
|
|
|
self.palette = palette
|
|
|
|
self.palette.mode = "RGB"
|
2014-04-22 10:23:34 +04:00
|
|
|
self.load() # install new palette
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def putpixel(self, xy, value):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2013-10-12 09:18:40 +04:00
|
|
|
Modifies the pixel at the given position. The color is given as
|
2013-07-09 18:32:14 +04:00
|
|
|
a single numerical value for single-band images, and a tuple for
|
2018-12-31 05:37:04 +03:00
|
|
|
multi-band images. In addition to this, RGB and RGBA tuples are
|
2022-08-14 07:34:42 +03:00
|
|
|
accepted for P and PA images.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
Note that this method is relatively slow. For more extensive changes,
|
|
|
|
use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`
|
2013-07-09 18:32:14 +04:00
|
|
|
module instead.
|
|
|
|
|
|
|
|
See:
|
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
* :py:meth:`~PIL.Image.Image.paste`
|
|
|
|
* :py:meth:`~PIL.Image.Image.putdata`
|
|
|
|
* :py:mod:`~PIL.ImageDraw`
|
2013-07-09 18:32:14 +04:00
|
|
|
|
2018-06-24 07:34:01 +03:00
|
|
|
:param xy: The pixel coordinate, given as (x, y). See
|
|
|
|
:ref:`coordinate-system`.
|
2013-07-09 18:32:14 +04:00
|
|
|
:param value: The pixel value.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
if self.readonly:
|
|
|
|
self._copy()
|
2017-06-22 13:24:21 +03:00
|
|
|
self.load()
|
2014-05-14 19:04:18 +04:00
|
|
|
|
|
|
|
if self.pyaccess:
|
2014-04-22 10:23:34 +04:00
|
|
|
return self.pyaccess.putpixel(xy, value)
|
2018-12-31 03:35:15 +03:00
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
if (
|
2022-08-14 07:34:42 +03:00
|
|
|
self.mode in ("P", "PA")
|
2019-03-21 16:28:20 +03:00
|
|
|
and isinstance(value, (list, tuple))
|
|
|
|
and len(value) in [3, 4]
|
|
|
|
):
|
2022-08-14 07:34:42 +03:00
|
|
|
# RGB or RGBA value for a P or PA image
|
|
|
|
if self.mode == "PA":
|
|
|
|
alpha = value[3] if len(value) == 4 else 255
|
|
|
|
value = value[:3]
|
2021-06-23 11:41:46 +03:00
|
|
|
value = self.palette.getcolor(value, self)
|
2022-08-14 07:34:42 +03:00
|
|
|
if self.mode == "PA":
|
|
|
|
value = (value, alpha)
|
2010-07-31 06:52:47 +04:00
|
|
|
return self.im.putpixel(xy, value)
|
|
|
|
|
2017-02-23 15:25:04 +03:00
|
|
|
def remap_palette(self, dest_map, source_palette=None):
|
|
|
|
"""
|
|
|
|
Rewrites the image to reorder the palette.
|
2017-03-31 05:02:56 +03:00
|
|
|
|
2017-02-23 15:25:04 +03:00
|
|
|
:param dest_map: A list of indexes into the original palette.
|
2020-09-01 20:16:46 +03:00
|
|
|
e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))``
|
2017-02-23 15:25:04 +03:00
|
|
|
is the identity transform.
|
|
|
|
:param source_palette: Bytes or None.
|
2017-03-31 05:02:56 +03:00
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
|
|
|
|
2017-02-23 15:25:04 +03:00
|
|
|
"""
|
|
|
|
from . import ImagePalette
|
2017-03-31 05:02:56 +03:00
|
|
|
|
2017-02-23 15:25:04 +03:00
|
|
|
if self.mode not in ("L", "P"):
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "illegal image mode"
|
|
|
|
raise ValueError(msg)
|
2017-02-23 15:25:04 +03:00
|
|
|
|
2022-06-05 17:12:48 +03:00
|
|
|
bands = 3
|
|
|
|
palette_mode = "RGB"
|
2017-02-23 15:25:04 +03:00
|
|
|
if source_palette is None:
|
|
|
|
if self.mode == "P":
|
2021-06-28 13:11:14 +03:00
|
|
|
self.load()
|
2022-06-05 17:12:48 +03:00
|
|
|
palette_mode = self.im.getpalettemode()
|
|
|
|
if palette_mode == "RGBA":
|
|
|
|
bands = 4
|
|
|
|
source_palette = self.im.getpalette(palette_mode, palette_mode)
|
2017-02-23 15:25:04 +03:00
|
|
|
else: # L-mode
|
2021-07-05 16:02:26 +03:00
|
|
|
source_palette = bytearray(i // 3 for i in range(768))
|
2017-03-31 05:02:56 +03:00
|
|
|
|
2017-02-23 15:25:04 +03:00
|
|
|
palette_bytes = b""
|
2019-03-21 16:28:20 +03:00
|
|
|
new_positions = [0] * 256
|
2017-02-23 15:25:04 +03:00
|
|
|
|
|
|
|
# pick only the used colors from the palette
|
|
|
|
for i, oldPosition in enumerate(dest_map):
|
2022-06-05 17:12:48 +03:00
|
|
|
palette_bytes += source_palette[
|
|
|
|
oldPosition * bands : oldPosition * bands + bands
|
|
|
|
]
|
2017-02-23 15:25:04 +03:00
|
|
|
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()
|
2019-03-21 16:28:20 +03:00
|
|
|
m_im.mode = "P"
|
2017-02-23 15:25:04 +03:00
|
|
|
|
2022-06-05 17:12:48 +03:00
|
|
|
m_im.palette = ImagePalette.ImagePalette(
|
|
|
|
palette_mode, palette=mapping_palette * bands
|
|
|
|
)
|
2017-04-20 14:14:23 +03:00
|
|
|
# possibly set palette dirty, then
|
|
|
|
# m_im.putpalette(mapping_palette, 'L') # converts to 'P'
|
2017-02-23 15:25:04 +03:00
|
|
|
# or just force it.
|
|
|
|
# UNDONE -- this is part of the general issue with palettes
|
2022-06-05 17:12:48 +03:00
|
|
|
m_im.im.putpalette(palette_mode + ";L", m_im.palette.tobytes())
|
2017-02-23 15:25:04 +03:00
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
m_im = m_im.convert("L")
|
2017-02-23 15:25:04 +03:00
|
|
|
|
2022-08-28 08:58:30 +03:00
|
|
|
m_im.putpalette(palette_bytes, palette_mode)
|
2022-06-05 17:12:48 +03:00
|
|
|
m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes)
|
2017-02-23 15:25:04 +03:00
|
|
|
|
2022-05-21 09:35:01 +03:00
|
|
|
if "transparency" in self.info:
|
2022-05-21 10:38:44 +03:00
|
|
|
try:
|
|
|
|
m_im.info["transparency"] = dest_map.index(self.info["transparency"])
|
|
|
|
except ValueError:
|
|
|
|
if "transparency" in m_im.info:
|
|
|
|
del m_im.info["transparency"]
|
2022-05-21 09:35:01 +03:00
|
|
|
|
2017-02-23 15:25:04 +03:00
|
|
|
return m_im
|
2017-03-31 05:02:56 +03:00
|
|
|
|
2019-12-20 14:54:06 +03:00
|
|
|
def _get_safe_box(self, size, resample, box):
|
2019-12-27 15:35:17 +03:00
|
|
|
"""Expands the box so it includes adjacent pixels
|
|
|
|
that may be used by resampling with the given resampling filter.
|
2019-12-20 14:54:06 +03:00
|
|
|
"""
|
|
|
|
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)),
|
|
|
|
)
|
|
|
|
|
2021-04-17 05:18:42 +03:00
|
|
|
def resize(self, size, resample=None, box=None, reducing_gap=None):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Returns a resized copy of this image.
|
|
|
|
|
|
|
|
:param size: The requested size in pixels, as a 2-tuple:
|
|
|
|
(width, height).
|
2014-01-10 21:27:43 +04:00
|
|
|
:param resample: An optional resampling filter. This can be
|
2022-09-03 13:53:22 +03:00
|
|
|
one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`,
|
|
|
|
:py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`,
|
|
|
|
:py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`.
|
2021-04-17 05:18:42 +03:00
|
|
|
If the image has mode "1" or "P", it is always set to
|
2022-09-03 13:53:22 +03:00
|
|
|
:py:data:`Resampling.NEAREST`. If the image mode specifies a number
|
|
|
|
of bits, such as "I;16", then the default filter is
|
|
|
|
:py:data:`Resampling.NEAREST`. Otherwise, the default filter is
|
|
|
|
:py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`.
|
2019-12-27 14:27:37 +03:00
|
|
|
: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.
|
2016-12-02 03:11:02 +03:00
|
|
|
If omitted or None, the entire source is used.
|
2019-12-20 14:59:18 +03:00
|
|
|
:param reducing_gap: Apply optimization by resizing the image
|
2019-12-27 15:35:17 +03:00
|
|
|
in two steps. First, reducing the image by integer times
|
2019-12-07 03:50:29 +03:00
|
|
|
using :py:meth:`~PIL.Image.Image.reduce`.
|
|
|
|
Second, resizing using regular resampling. The last step
|
2019-12-27 15:35:17 +03:00
|
|
|
changes size no less than by ``reducing_gap`` times.
|
|
|
|
``reducing_gap`` may be None (no first step is performed)
|
2019-12-21 01:17:08 +03:00
|
|
|
or should be greater than 1.0. The bigger ``reducing_gap``,
|
2019-12-07 03:50:29 +03:00
|
|
|
the closer the result to the fair resampling.
|
2019-12-21 01:17:08 +03:00
|
|
|
The smaller ``reducing_gap``, the faster resizing.
|
2019-12-30 03:23:30 +03:00
|
|
|
With ``reducing_gap`` greater or equal to 3.0, the result is
|
2019-12-07 03:50:29 +03:00
|
|
|
indistinguishable from fair resampling in most cases.
|
|
|
|
The default value is None (no optimization).
|
2013-10-12 09:18:40 +04:00
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2021-04-17 05:18:42 +03:00
|
|
|
if resample is None:
|
|
|
|
type_special = ";" in self.mode
|
2022-01-15 01:02:31 +03:00
|
|
|
resample = Resampling.NEAREST if type_special else Resampling.BICUBIC
|
|
|
|
elif resample not in (
|
|
|
|
Resampling.NEAREST,
|
|
|
|
Resampling.BILINEAR,
|
|
|
|
Resampling.BICUBIC,
|
|
|
|
Resampling.LANCZOS,
|
|
|
|
Resampling.BOX,
|
|
|
|
Resampling.HAMMING,
|
|
|
|
):
|
2022-12-30 06:24:28 +03:00
|
|
|
msg = f"Unknown resampling filter ({resample})."
|
2019-05-20 23:08:57 +03:00
|
|
|
|
2019-06-11 11:42:05 +03:00
|
|
|
filters = [
|
2021-10-15 13:10:22 +03:00
|
|
|
f"{filter[1]} ({filter[0]})"
|
2019-06-11 11:42:05 +03:00
|
|
|
for filter in (
|
2022-01-15 01:02:31 +03:00
|
|
|
(Resampling.NEAREST, "Image.Resampling.NEAREST"),
|
|
|
|
(Resampling.LANCZOS, "Image.Resampling.LANCZOS"),
|
|
|
|
(Resampling.BILINEAR, "Image.Resampling.BILINEAR"),
|
|
|
|
(Resampling.BICUBIC, "Image.Resampling.BICUBIC"),
|
|
|
|
(Resampling.BOX, "Image.Resampling.BOX"),
|
|
|
|
(Resampling.HAMMING, "Image.Resampling.HAMMING"),
|
2019-06-11 11:42:05 +03:00
|
|
|
)
|
|
|
|
]
|
2022-12-30 06:24:28 +03:00
|
|
|
msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
|
|
|
|
raise ValueError(msg)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2019-12-20 14:59:18 +03:00
|
|
|
if reducing_gap is not None and reducing_gap < 1.0:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "reducing_gap must be 1.0 or greater"
|
|
|
|
raise ValueError(msg)
|
2019-12-07 03:50:29 +03:00
|
|
|
|
2015-04-02 08:29:18 +03:00
|
|
|
size = tuple(size)
|
2016-12-02 15:40:32 +03:00
|
|
|
|
2022-04-08 12:11:27 +03:00
|
|
|
self.load()
|
2016-12-02 15:40:32 +03:00
|
|
|
if box is None:
|
|
|
|
box = (0, 0) + self.size
|
|
|
|
else:
|
|
|
|
box = tuple(box)
|
|
|
|
|
|
|
|
if self.size == size and box == (0, 0) + self.size:
|
2016-11-24 03:30:36 +03:00
|
|
|
return self.copy()
|
2014-09-10 04:41:46 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
if self.mode in ("1", "P"):
|
2022-01-15 01:02:31 +03:00
|
|
|
resample = Resampling.NEAREST
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST:
|
2021-03-07 05:14:07 +03:00
|
|
|
im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
|
2018-10-21 10:26:08 +03:00
|
|
|
im = im.resize(size, resample, box)
|
|
|
|
return im.convert(self.mode)
|
2013-10-05 00:25:32 +04:00
|
|
|
|
2016-12-02 15:40:32 +03:00
|
|
|
self.load()
|
2013-10-05 00:25:32 +04:00
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
if reducing_gap is not None and resample != Resampling.NEAREST:
|
2019-12-20 14:59:18 +03:00
|
|
|
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
|
2019-12-20 14:54:06 +03:00
|
|
|
if factor_x > 1 or factor_y > 1:
|
|
|
|
reduce_box = self._get_safe_box(size, resample, box)
|
2020-03-24 11:19:46 +03:00
|
|
|
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)
|
2019-12-07 03:50:29 +03:00
|
|
|
box = (
|
2019-12-20 14:54:06 +03:00
|
|
|
(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,
|
2019-12-07 03:50:29 +03:00
|
|
|
)
|
|
|
|
|
2016-11-30 20:01:28 +03:00
|
|
|
return self._new(self.im.resize(size, resample, box))
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2019-12-02 04:32:08 +03:00
|
|
|
def reduce(self, factor, box=None):
|
2019-11-24 04:13:48 +03:00
|
|
|
"""
|
2020-09-01 20:16:46 +03:00
|
|
|
Returns a copy of the image reduced ``factor`` times.
|
|
|
|
If the size of the image is not dividable by ``factor``,
|
2019-11-24 04:13:48 +03:00
|
|
|
the resulting size will be rounded up.
|
|
|
|
|
|
|
|
:param factor: A greater than 0 integer or tuple of two integers
|
2019-12-27 14:27:37 +03:00
|
|
|
for width and height separately.
|
|
|
|
:param box: An optional 4-tuple of ints providing
|
|
|
|
the source image region to be reduced.
|
2020-09-01 20:16:46 +03:00
|
|
|
The values must be within ``(0, 0, width, height)`` rectangle.
|
|
|
|
If omitted or ``None``, the entire source is used.
|
2019-11-24 04:13:48 +03:00
|
|
|
"""
|
|
|
|
if not isinstance(factor, (list, tuple)):
|
|
|
|
factor = (factor, factor)
|
|
|
|
|
2019-12-02 04:32:08 +03:00
|
|
|
if box is None:
|
|
|
|
box = (0, 0) + self.size
|
|
|
|
else:
|
|
|
|
box = tuple(box)
|
|
|
|
|
|
|
|
if factor == (1, 1) and box == (0, 0) + self.size:
|
2019-11-26 03:36:58 +03:00
|
|
|
return self.copy()
|
|
|
|
|
|
|
|
if self.mode in ["LA", "RGBA"]:
|
2021-03-07 05:14:07 +03:00
|
|
|
im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
|
2019-12-02 04:32:08 +03:00
|
|
|
im = im.reduce(factor, box)
|
2019-11-26 03:36:58 +03:00
|
|
|
return im.convert(self.mode)
|
|
|
|
|
2019-11-24 04:13:48 +03:00
|
|
|
self.load()
|
|
|
|
|
2019-12-02 04:32:08 +03:00
|
|
|
return self._new(self.im.reduce(factor, box))
|
2019-11-24 04:13:48 +03:00
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
def rotate(
|
|
|
|
self,
|
|
|
|
angle,
|
2022-01-15 01:02:31 +03:00
|
|
|
resample=Resampling.NEAREST,
|
2019-03-21 16:28:20 +03:00
|
|
|
expand=0,
|
|
|
|
center=None,
|
|
|
|
translate=None,
|
|
|
|
fillcolor=None,
|
|
|
|
):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
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.
|
2014-06-04 00:34:23 +04:00
|
|
|
:param resample: An optional resampling filter. This can be
|
2022-09-03 13:53:22 +03:00
|
|
|
one of :py:data:`Resampling.NEAREST` (use nearest neighbour),
|
|
|
|
:py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2
|
|
|
|
environment), or :py:data:`Resampling.BICUBIC` (cubic spline
|
|
|
|
interpolation in a 4x4 environment). If omitted, or if the image has
|
|
|
|
mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`.
|
|
|
|
See :ref:`concept-filters`.
|
2013-07-09 18:32:14 +04:00
|
|
|
: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
|
2016-10-05 23:26:26 +03:00
|
|
|
input image. Note that the expand flag assumes rotation around
|
|
|
|
the center and no translation.
|
2017-01-01 14:10:39 +03:00
|
|
|
: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).
|
2018-03-27 16:33:35 +03:00
|
|
|
:param fillcolor: An optional color for area outside the rotated image.
|
2013-10-12 09:18:40 +04:00
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2016-06-02 10:57:55 +03:00
|
|
|
angle = angle % 360.0
|
|
|
|
|
2017-01-01 14:11:10 +03:00
|
|
|
# Fast paths regardless of filter, as long as we're not
|
2017-01-17 16:22:18 +03:00
|
|
|
# translating or changing the center.
|
2017-01-01 14:11:10 +03:00
|
|
|
if not (center or translate):
|
|
|
|
if angle == 0:
|
|
|
|
return self.copy()
|
|
|
|
if angle == 180:
|
2022-01-15 01:02:31 +03:00
|
|
|
return self.transpose(Transpose.ROTATE_180)
|
2021-07-30 12:57:09 +03:00
|
|
|
if angle in (90, 270) and (expand or self.width == self.height):
|
2022-01-15 01:02:31 +03:00
|
|
|
return self.transpose(
|
|
|
|
Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270
|
|
|
|
)
|
2016-06-02 10:57:55 +03:00
|
|
|
|
2016-10-05 23:26:26 +03:00
|
|
|
# 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:
|
2017-08-21 05:22:51 +03:00
|
|
|
post_trans = (0, 0)
|
|
|
|
else:
|
|
|
|
post_trans = translate
|
2016-10-05 23:26:26 +03:00
|
|
|
if center is None:
|
2018-10-21 10:26:08 +03:00
|
|
|
# FIXME These should be rounded to ints?
|
|
|
|
rotn_center = (w / 2.0, h / 2.0)
|
2017-08-21 05:22:51 +03:00
|
|
|
else:
|
|
|
|
rotn_center = center
|
2016-10-05 23:26:26 +03:00
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
angle = -math.radians(angle)
|
2016-06-02 11:36:41 +03:00
|
|
|
matrix = [
|
2019-03-21 16:28:20 +03:00
|
|
|
round(math.cos(angle), 15),
|
|
|
|
round(math.sin(angle), 15),
|
|
|
|
0.0,
|
|
|
|
round(-math.sin(angle), 15),
|
|
|
|
round(math.cos(angle), 15),
|
|
|
|
0.0,
|
2016-10-05 23:26:26 +03:00
|
|
|
]
|
2017-01-29 19:38:06 +03:00
|
|
|
|
2016-10-05 23:26:26 +03:00
|
|
|
def transform(x, y, matrix):
|
2016-06-02 11:36:41 +03:00
|
|
|
(a, b, c, d, e, f) = matrix
|
2019-03-21 16:28:20 +03:00
|
|
|
return a * x + b * y + c, d * x + e * y + f
|
2017-01-29 19:38:06 +03:00
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
matrix[2], matrix[5] = transform(
|
|
|
|
-rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix
|
|
|
|
)
|
2017-08-21 05:22:51 +03:00
|
|
|
matrix[2] += rotn_center[0]
|
|
|
|
matrix[5] += rotn_center[1]
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2016-06-02 11:36:41 +03:00
|
|
|
if expand:
|
2010-07-31 06:52:47 +04:00
|
|
|
# calculate output size
|
|
|
|
xx = []
|
|
|
|
yy = []
|
|
|
|
for x, y in ((0, 0), (w, 0), (w, h), (0, h)):
|
2016-10-05 23:26:26 +03:00
|
|
|
x, y = transform(x, y, matrix)
|
2010-07-31 06:52:47 +04:00
|
|
|
xx.append(x)
|
|
|
|
yy.append(y)
|
2020-02-08 00:34:53 +03:00
|
|
|
nw = math.ceil(max(xx)) - math.floor(min(xx))
|
|
|
|
nh = math.ceil(max(yy)) - math.floor(min(yy))
|
2016-10-05 23:26:26 +03:00
|
|
|
|
|
|
|
# We multiply a translation matrix from the right. Because of its
|
2017-01-29 19:38:06 +03:00
|
|
|
# special form, this is the same as taking the image of the
|
|
|
|
# translation vector as new translation vector.
|
2019-03-21 16:28:20 +03:00
|
|
|
matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix)
|
2016-10-05 23:26:26 +03:00
|
|
|
w, h = nw, nh
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
return self.transform(
|
|
|
|
(w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor
|
|
|
|
)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def save(self, fp, format=None, **params):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
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
|
2014-11-20 01:54:43 +03:00
|
|
|
silently ignored. The available options are described in the
|
|
|
|
:doc:`image format documentation
|
|
|
|
<../handbook/image-file-formats>` for each writer.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
|
|
|
You can use a file object instead of a filename. In this case,
|
|
|
|
you must always specify the format. The file object must
|
2014-11-20 01:54:43 +03:00
|
|
|
implement the ``seek``, ``tell``, and ``write``
|
2013-07-09 18:32:14 +04:00
|
|
|
methods, and be opened in binary mode.
|
|
|
|
|
2015-08-05 15:32:15 +03:00
|
|
|
:param fp: A filename (string), pathlib.Path object or file object.
|
2013-07-09 18:32:14 +04:00
|
|
|
: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.
|
2018-06-10 07:11:08 +03:00
|
|
|
:param params: Extra parameters to the image writer.
|
2013-07-09 18:32:14 +04:00
|
|
|
:returns: None
|
2018-09-11 11:30:42 +03:00
|
|
|
:exception ValueError: If the output format could not be determined
|
2013-07-09 18:32:14 +04:00
|
|
|
from the file name. Use the format option to solve this.
|
2020-04-07 09:58:21 +03:00
|
|
|
:exception OSError: If the file could not be written. The file
|
2013-07-09 18:32:14 +04:00
|
|
|
may have been created, and may contain partial data.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2015-08-05 13:54:33 +03:00
|
|
|
filename = ""
|
2015-10-03 10:12:44 +03:00
|
|
|
open_fp = False
|
2021-07-24 07:21:33 +03:00
|
|
|
if isinstance(fp, Path):
|
2016-12-17 20:50:50 +03:00
|
|
|
filename = str(fp)
|
|
|
|
open_fp = True
|
2022-04-10 21:20:48 +03:00
|
|
|
elif is_path(fp):
|
2021-07-24 07:21:33 +03:00
|
|
|
filename = fp
|
|
|
|
open_fp = True
|
2021-04-25 07:21:00 +03:00
|
|
|
elif fp == sys.stdout:
|
2021-05-03 11:07:05 +03:00
|
|
|
try:
|
|
|
|
fp = sys.stdout.buffer
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
2022-04-10 21:20:48 +03:00
|
|
|
if not filename and hasattr(fp, "name") and is_path(fp.name):
|
2015-10-03 10:12:44 +03:00
|
|
|
# only set the name for metadata purposes
|
2015-08-05 13:54:33 +03:00
|
|
|
filename = fp.name
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
# may mutate self!
|
2019-03-17 15:37:40 +03:00
|
|
|
self._ensure_mutable()
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
save_all = params.pop("save_all", False)
|
2010-07-31 06:52:47 +04:00
|
|
|
self.encoderinfo = params
|
|
|
|
self.encoderconfig = ()
|
|
|
|
|
|
|
|
preinit()
|
|
|
|
|
2012-10-11 02:11:13 +04:00
|
|
|
ext = os.path.splitext(filename)[1].lower()
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
if not format:
|
2015-07-01 02:19:28 +03:00
|
|
|
if ext not in EXTENSION:
|
2010-07-31 06:52:47 +04:00
|
|
|
init()
|
2017-02-17 16:39:16 +03:00
|
|
|
try:
|
|
|
|
format = EXTENSION[ext]
|
2020-06-21 13:13:35 +03:00
|
|
|
except KeyError as e:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = f"unknown file extension: {ext}"
|
|
|
|
raise ValueError(msg) from e
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2015-06-30 11:02:48 +03:00
|
|
|
if format.upper() not in SAVE:
|
2010-07-31 06:52:47 +04:00
|
|
|
init()
|
2015-06-30 11:02:48 +03:00
|
|
|
if save_all:
|
|
|
|
save_handler = SAVE_ALL[format.upper()]
|
|
|
|
else:
|
|
|
|
save_handler = SAVE[format.upper()]
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2022-03-14 15:33:45 +03:00
|
|
|
created = False
|
2015-10-03 10:12:44 +03:00
|
|
|
if open_fp:
|
2022-03-14 15:33:45 +03:00
|
|
|
created = not os.path.exists(filename)
|
2019-03-21 16:28:20 +03:00
|
|
|
if params.get("append", False):
|
2018-01-18 16:33:11 +03:00
|
|
|
# Open also for reading ("+"), because TIFF save_all
|
|
|
|
# writer needs to go back and edit the written data.
|
2019-09-16 14:06:13 +03:00
|
|
|
fp = builtins.open(filename, "r+b")
|
|
|
|
else:
|
2018-01-18 16:33:11 +03:00
|
|
|
fp = builtins.open(filename, "w+b")
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
try:
|
|
|
|
save_handler(self, fp, filename)
|
2022-03-14 15:33:45 +03:00
|
|
|
except Exception:
|
2015-10-03 10:12:44 +03:00
|
|
|
if open_fp:
|
2010-07-31 06:52:47 +04:00
|
|
|
fp.close()
|
2022-03-14 15:33:45 +03:00
|
|
|
if created:
|
|
|
|
try:
|
|
|
|
os.remove(filename)
|
|
|
|
except PermissionError:
|
|
|
|
pass
|
|
|
|
raise
|
|
|
|
if open_fp:
|
|
|
|
fp.close()
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def seek(self, frame):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Seeks to the given frame in this sequence file. If you seek
|
|
|
|
beyond the end of the sequence, the method raises an
|
2020-06-12 16:57:21 +03:00
|
|
|
``EOFError`` exception. When a sequence file is opened, the
|
2013-07-09 18:32:14 +04:00
|
|
|
library automatically seeks to frame 0.
|
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
See :py:meth:`~PIL.Image.Image.tell`.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
2020-06-27 18:24:13 +03:00
|
|
|
If defined, :attr:`~PIL.Image.Image.n_frames` refers to the
|
|
|
|
number of available frames.
|
|
|
|
|
2013-07-09 18:32:14 +04:00
|
|
|
:param frame: Frame number, starting at 0.
|
|
|
|
:exception EOFError: If the call attempts to seek beyond the end
|
|
|
|
of the sequence.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
# overridden by file handlers
|
|
|
|
if frame != 0:
|
|
|
|
raise EOFError
|
|
|
|
|
2021-10-18 03:08:51 +03:00
|
|
|
def show(self, title=None):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2020-06-15 15:54:38 +03:00
|
|
|
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.
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2019-08-16 12:43:28 +03:00
|
|
|
The image is first saved to a temporary file. By default, it will be in
|
|
|
|
PNG format.
|
2016-05-05 12:30:07 +03:00
|
|
|
|
2019-08-16 12:43:28 +03:00
|
|
|
On Unix, the image is then opened using the **display**, **eog** or
|
|
|
|
**xv** utility, depending on which one can be found.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
2019-08-16 12:43:28 +03:00
|
|
|
On macOS, the image is opened with the native Preview application.
|
|
|
|
|
|
|
|
On Windows, the image is opened with the standard PNG display utility.
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2020-06-15 15:54:38 +03:00
|
|
|
:param title: Optional title to use for the image window, where possible.
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
|
2021-10-18 03:08:51 +03:00
|
|
|
_show(self, title=title)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def split(self):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
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).
|
|
|
|
|
2017-08-12 01:24:53 +03:00
|
|
|
If you need only one band, :py:meth:`~PIL.Image.Image.getchannel`
|
2017-08-12 10:32:42 +03:00
|
|
|
method can be more convenient and faster.
|
2017-08-12 01:24:53 +03:00
|
|
|
|
2013-07-09 18:32:14 +04:00
|
|
|
:returns: A tuple containing bands.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2012-01-20 00:07:18 +04:00
|
|
|
self.load()
|
2010-07-31 06:52:47 +04:00
|
|
|
if self.im.bands == 1:
|
|
|
|
ims = [self.copy()]
|
|
|
|
else:
|
2017-08-12 03:43:19 +03:00
|
|
|
ims = map(self._new, self.im.split())
|
2010-07-31 06:52:47 +04:00
|
|
|
return tuple(ims)
|
|
|
|
|
2017-08-09 01:58:22 +03:00
|
|
|
def getchannel(self, channel):
|
|
|
|
"""
|
2017-08-12 10:32:42 +03:00
|
|
|
Returns an image containing a single channel of the source image.
|
2017-08-09 01:58:22 +03:00
|
|
|
|
|
|
|
:param channel: What channel to return. Could be index
|
2017-08-12 01:24:53 +03:00
|
|
|
(0 for "R" channel of "RGB") or channel name
|
|
|
|
("A" for alpha channel of "RGBA").
|
2017-08-09 01:58:22 +03:00
|
|
|
:returns: An image in "L" mode.
|
2017-08-12 01:24:53 +03:00
|
|
|
|
|
|
|
.. versionadded:: 4.3.0
|
2017-08-09 01:58:22 +03:00
|
|
|
"""
|
2017-08-09 02:39:53 +03:00
|
|
|
self.load()
|
2017-08-09 01:58:22 +03:00
|
|
|
|
2019-10-08 17:01:11 +03:00
|
|
|
if isinstance(channel, str):
|
2017-08-12 14:10:39 +03:00
|
|
|
try:
|
|
|
|
channel = self.getbands().index(channel)
|
2020-06-21 13:13:35 +03:00
|
|
|
except ValueError as e:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = f'The image has no channel "{channel}"'
|
|
|
|
raise ValueError(msg) from e
|
2017-08-09 01:58:22 +03:00
|
|
|
|
|
|
|
return self._new(self.im.getband(channel))
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def tell(self):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2013-10-12 09:18:40 +04:00
|
|
|
Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2020-06-27 18:24:13 +03:00
|
|
|
If defined, :attr:`~PIL.Image.Image.n_frames` refers to the
|
|
|
|
number of available frames.
|
|
|
|
|
2013-07-09 18:32:14 +04:00
|
|
|
:returns: Frame number, starting with 0.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
return 0
|
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
def thumbnail(self, size, resample=Resampling.BICUBIC, reducing_gap=2.0):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
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
|
2013-10-12 09:18:40 +04:00
|
|
|
:py:meth:`~PIL.Image.Image.draft` method to configure the file reader
|
2013-07-09 18:32:14 +04:00
|
|
|
(where applicable), and finally resizes the image.
|
|
|
|
|
2014-11-09 04:26:53 +03:00
|
|
|
Note that this function modifies the :py:class:`~PIL.Image.Image`
|
2014-04-22 10:23:34 +04:00
|
|
|
object in place. If you need to use the full resolution image as well,
|
2014-05-10 13:34:36 +04:00
|
|
|
apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original
|
|
|
|
image.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
2023-01-02 00:41:50 +03:00
|
|
|
:param size: The requested size in pixels, as a 2-tuple:
|
|
|
|
(width, height).
|
2013-07-09 18:32:14 +04:00
|
|
|
:param resample: Optional resampling filter. This can be one
|
2022-09-03 13:53:22 +03:00
|
|
|
of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`,
|
|
|
|
:py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`,
|
|
|
|
:py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`.
|
|
|
|
If omitted, it defaults to :py:data:`Resampling.BICUBIC`.
|
|
|
|
(was :py:data:`Resampling.NEAREST` prior to version 2.5.0).
|
2020-04-23 11:18:24 +03:00
|
|
|
See: :ref:`concept-filters`.
|
2019-12-20 14:59:18 +03:00
|
|
|
:param reducing_gap: Apply optimization by resizing the image
|
2019-12-27 15:35:17 +03:00
|
|
|
in two steps. First, reducing the image by integer times
|
2019-12-07 03:50:29 +03:00
|
|
|
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
|
2019-12-27 15:35:17 +03:00
|
|
|
changes size no less than by ``reducing_gap`` times.
|
2019-12-30 03:23:30 +03:00
|
|
|
``reducing_gap`` may be None (no first step is performed)
|
2019-12-21 01:17:08 +03:00
|
|
|
or should be greater than 1.0. The bigger ``reducing_gap``,
|
2019-12-07 03:50:29 +03:00
|
|
|
the closer the result to the fair resampling.
|
2019-12-21 01:17:08 +03:00
|
|
|
The smaller ``reducing_gap``, the faster resizing.
|
2019-12-30 03:23:30 +03:00
|
|
|
With ``reducing_gap`` greater or equal to 3.0, the result is
|
2019-12-07 03:50:29 +03:00
|
|
|
indistinguishable from fair resampling in most cases.
|
|
|
|
The default value is 2.0 (very close to fair resampling
|
2019-12-27 15:35:17 +03:00
|
|
|
while still being faster in many cases).
|
2013-07-09 18:32:14 +04:00
|
|
|
:returns: None
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2022-08-26 13:33:51 +03:00
|
|
|
provided_size = tuple(map(math.floor, size))
|
2020-02-04 23:58:54 +03:00
|
|
|
|
2022-08-26 13:33:51 +03:00
|
|
|
def preserve_aspect_ratio():
|
|
|
|
def round_aspect(number, key):
|
|
|
|
return max(min(math.floor(number), math.ceil(number), key=key), 1)
|
2020-02-22 02:30:35 +03:00
|
|
|
|
2022-08-26 13:33:51 +03:00
|
|
|
x, y = provided_size
|
|
|
|
if x >= self.width and y >= self.height:
|
|
|
|
return
|
|
|
|
|
|
|
|
aspect = self.width / self.height
|
|
|
|
if x / y >= aspect:
|
|
|
|
x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y))
|
|
|
|
else:
|
|
|
|
y = round_aspect(
|
|
|
|
x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n)
|
|
|
|
)
|
|
|
|
return x, y
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2020-02-04 23:14:00 +03:00
|
|
|
box = None
|
2019-12-20 14:59:18 +03:00
|
|
|
if reducing_gap is not None:
|
2022-08-26 13:33:51 +03:00
|
|
|
size = preserve_aspect_ratio()
|
|
|
|
if size is None:
|
|
|
|
return
|
|
|
|
|
2019-12-20 14:59:18 +03:00
|
|
|
res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap))
|
2019-12-07 03:50:29 +03:00
|
|
|
if res is not None:
|
|
|
|
box = res[1]
|
2022-08-26 13:33:51 +03:00
|
|
|
if box is None:
|
|
|
|
self.load()
|
|
|
|
|
|
|
|
# load() may have changed the size of the image
|
|
|
|
size = preserve_aspect_ratio()
|
|
|
|
if size is None:
|
|
|
|
return
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2019-02-04 22:15:50 +03:00
|
|
|
if self.size != size:
|
2019-12-20 14:59:18 +03:00
|
|
|
im = self.resize(size, resample, box=box, reducing_gap=reducing_gap)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2019-02-04 22:15:50 +03:00
|
|
|
self.im = im.im
|
|
|
|
self._size = size
|
|
|
|
self.mode = self.im.mode
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.readonly = 0
|
2014-01-06 10:18:42 +04:00
|
|
|
self.pyaccess = None
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2015-05-29 07:59:54 +03:00
|
|
|
# FIXME: the different transform methods need further explanation
|
2010-07-31 06:52:47 +04:00
|
|
|
# instead of bloating the method docs, add a separate chapter.
|
2019-03-21 16:28:20 +03:00
|
|
|
def transform(
|
2022-01-15 01:02:31 +03:00
|
|
|
self,
|
|
|
|
size,
|
|
|
|
method,
|
|
|
|
data=None,
|
|
|
|
resample=Resampling.NEAREST,
|
|
|
|
fill=1,
|
|
|
|
fillcolor=None,
|
2019-03-21 16:28:20 +03:00
|
|
|
):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
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.
|
|
|
|
|
2023-01-02 00:41:50 +03:00
|
|
|
:param size: The output size in pixels, as a 2-tuple:
|
|
|
|
(width, height).
|
2013-07-09 18:32:14 +04:00
|
|
|
:param method: The transformation method. This is one of
|
2022-09-03 13:53:22 +03:00
|
|
|
:py:data:`Transform.EXTENT` (cut out a rectangular subregion),
|
|
|
|
:py:data:`Transform.AFFINE` (affine transform),
|
|
|
|
:py:data:`Transform.PERSPECTIVE` (perspective transform),
|
|
|
|
:py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or
|
|
|
|
:py:data:`Transform.MESH` (map a number of source quadrilaterals
|
2013-07-09 18:32:14 +04:00
|
|
|
in one operation).
|
2018-06-08 15:04:13 +03:00
|
|
|
|
|
|
|
It may also be an :py:class:`~PIL.Image.ImageTransformHandler`
|
|
|
|
object::
|
2019-12-21 15:05:50 +03:00
|
|
|
|
2018-06-08 15:04:13 +03:00
|
|
|
class Example(Image.ImageTransformHandler):
|
2020-07-09 20:48:04 +03:00
|
|
|
def transform(self, size, data, resample, fill=1):
|
2018-06-08 15:04:13 +03:00
|
|
|
# Return result
|
|
|
|
|
2020-07-09 20:48:04 +03:00
|
|
|
It may also be an object with a ``method.getdata`` method
|
2020-09-01 20:16:46 +03:00
|
|
|
that returns a tuple supplying new ``method`` and ``data`` values::
|
2019-12-21 15:05:50 +03:00
|
|
|
|
2020-04-23 13:05:30 +03:00
|
|
|
class Example:
|
2018-06-08 15:04:13 +03:00
|
|
|
def getdata(self):
|
2022-01-15 01:02:31 +03:00
|
|
|
method = Image.Transform.EXTENT
|
2018-06-08 15:04:13 +03:00
|
|
|
data = (0, 0, 100, 100)
|
|
|
|
return method, data
|
2013-07-09 18:32:14 +04:00
|
|
|
:param data: Extra data to the transformation method.
|
|
|
|
:param resample: Optional resampling filter. It can be one of
|
2022-09-03 13:53:22 +03:00
|
|
|
:py:data:`Resampling.NEAREST` (use nearest neighbour),
|
|
|
|
:py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2
|
|
|
|
environment), or :py:data:`Resampling.BICUBIC` (cubic spline
|
2013-07-09 18:32:14 +04:00
|
|
|
interpolation in a 4x4 environment). If omitted, or if the image
|
2022-09-03 13:53:22 +03:00
|
|
|
has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`.
|
2020-04-23 11:18:24 +03:00
|
|
|
See: :ref:`concept-filters`.
|
2020-09-01 20:16:46 +03:00
|
|
|
:param fill: If ``method`` is an
|
2018-06-08 15:04:13 +03:00
|
|
|
:py:class:`~PIL.Image.ImageTransformHandler` object, this is one of
|
|
|
|
the arguments passed to it. Otherwise, it is unused.
|
2018-10-21 10:26:08 +03:00
|
|
|
:param fillcolor: Optional fill color for the area outside the
|
|
|
|
transform in the output image.
|
2013-10-12 09:18:40 +04:00
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
2018-01-27 08:19:02 +03:00
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST:
|
2019-03-21 16:28:20 +03:00
|
|
|
return (
|
2021-03-07 05:14:07 +03:00
|
|
|
self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
|
2019-03-21 16:28:20 +03:00
|
|
|
.transform(size, method, data, resample, fill, fillcolor)
|
2021-03-06 13:44:31 +03:00
|
|
|
.convert(self.mode)
|
2019-03-21 16:28:20 +03:00
|
|
|
)
|
2013-10-05 00:25:32 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
if isinstance(method, ImageTransformHandler):
|
|
|
|
return method.transform(size, self, resample=resample, fill=fill)
|
2016-06-02 10:57:55 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
if hasattr(method, "getdata"):
|
|
|
|
# compatibility w. old-style transform objects
|
|
|
|
method, data = method.getdata()
|
2016-06-02 10:57:55 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
if data is None:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "missing method data"
|
|
|
|
raise ValueError(msg)
|
2013-10-12 09:18:40 +04:00
|
|
|
|
2017-11-11 19:53:24 +03:00
|
|
|
im = new(self.mode, size, fillcolor)
|
2021-07-30 13:11:05 +03:00
|
|
|
if self.mode == "P" and self.palette:
|
|
|
|
im.palette = self.palette.copy()
|
2019-10-10 12:22:41 +03:00
|
|
|
im.info = self.info.copy()
|
2022-01-15 01:02:31 +03:00
|
|
|
if method == Transform.MESH:
|
2010-07-31 06:52:47 +04:00
|
|
|
# list of quads
|
|
|
|
for box, quad in data:
|
2022-01-15 01:02:31 +03:00
|
|
|
im.__transformer(
|
|
|
|
box, self, Transform.QUAD, quad, resample, fillcolor is None
|
|
|
|
)
|
2010-07-31 06:52:47 +04:00
|
|
|
else:
|
2019-03-21 16:28:20 +03:00
|
|
|
im.__transformer(
|
|
|
|
(0, 0) + size, self, method, data, resample, fillcolor is None
|
|
|
|
)
|
2013-10-12 09:18:40 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
return im
|
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
def __transformer(
|
|
|
|
self, box, image, method, data, resample=Resampling.NEAREST, fill=1
|
|
|
|
):
|
2016-06-02 10:57:55 +03:00
|
|
|
w = box[2] - box[0]
|
|
|
|
h = box[3] - box[1]
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
if method == Transform.AFFINE:
|
2022-04-25 15:50:08 +03:00
|
|
|
data = data[:6]
|
2016-06-02 10:57:55 +03:00
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
elif method == Transform.EXTENT:
|
2010-07-31 06:52:47 +04:00
|
|
|
# convert extent to an affine transform
|
|
|
|
x0, y0, x1, y1 = data
|
2020-01-26 17:21:41 +03:00
|
|
|
xs = (x1 - x0) / w
|
|
|
|
ys = (y1 - y0) / h
|
2022-01-15 01:02:31 +03:00
|
|
|
method = Transform.AFFINE
|
2016-07-11 01:47:25 +03:00
|
|
|
data = (xs, 0, x0, 0, ys, y0)
|
2016-06-02 10:57:55 +03:00
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
elif method == Transform.PERSPECTIVE:
|
2022-04-25 15:50:08 +03:00
|
|
|
data = data[:8]
|
2016-06-02 10:57:55 +03:00
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
elif method == Transform.QUAD:
|
2010-07-31 06:52:47 +04:00
|
|
|
# quadrilateral warp. data specifies the four corners
|
|
|
|
# given as NW, SW, SE, and NE.
|
2022-04-25 15:50:08 +03:00
|
|
|
nw = data[:2]
|
2014-04-22 10:23:34 +04:00
|
|
|
sw = data[2:4]
|
|
|
|
se = data[4:6]
|
|
|
|
ne = data[6:8]
|
|
|
|
x0, y0 = nw
|
|
|
|
As = 1.0 / w
|
|
|
|
At = 1.0 / h
|
2019-03-21 16:28:20 +03:00
|
|
|
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,
|
|
|
|
)
|
2016-06-02 10:57:55 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
else:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "unknown transformation method"
|
|
|
|
raise ValueError(msg)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
if resample not in (
|
|
|
|
Resampling.NEAREST,
|
|
|
|
Resampling.BILINEAR,
|
|
|
|
Resampling.BICUBIC,
|
|
|
|
):
|
|
|
|
if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS):
|
2022-12-30 06:24:28 +03:00
|
|
|
msg = {
|
2022-01-15 01:02:31 +03:00
|
|
|
Resampling.BOX: "Image.Resampling.BOX",
|
|
|
|
Resampling.HAMMING: "Image.Resampling.HAMMING",
|
|
|
|
Resampling.LANCZOS: "Image.Resampling.LANCZOS",
|
2020-07-16 12:43:29 +03:00
|
|
|
}[resample] + f" ({resample}) cannot be used."
|
2019-05-20 23:08:57 +03:00
|
|
|
else:
|
2022-12-30 06:24:28 +03:00
|
|
|
msg = f"Unknown resampling filter ({resample})."
|
2019-05-20 23:08:57 +03:00
|
|
|
|
2019-06-11 11:42:05 +03:00
|
|
|
filters = [
|
2021-10-15 13:10:22 +03:00
|
|
|
f"{filter[1]} ({filter[0]})"
|
2019-06-11 11:42:05 +03:00
|
|
|
for filter in (
|
2022-01-15 01:02:31 +03:00
|
|
|
(Resampling.NEAREST, "Image.Resampling.NEAREST"),
|
|
|
|
(Resampling.BILINEAR, "Image.Resampling.BILINEAR"),
|
|
|
|
(Resampling.BICUBIC, "Image.Resampling.BICUBIC"),
|
2019-06-11 11:42:05 +03:00
|
|
|
)
|
|
|
|
]
|
2022-12-30 06:24:28 +03:00
|
|
|
msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
|
|
|
|
raise ValueError(msg)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
image.load()
|
|
|
|
|
|
|
|
self.load()
|
|
|
|
|
|
|
|
if image.mode in ("1", "P"):
|
2022-01-15 01:02:31 +03:00
|
|
|
resample = Resampling.NEAREST
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.im.transform2(box, image.im, method, data, resample, fill)
|
|
|
|
|
|
|
|
def transpose(self, method):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Transpose image (flip or rotate in 90 degree steps)
|
|
|
|
|
2022-09-03 13:53:22 +03:00
|
|
|
:param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`,
|
|
|
|
:py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`,
|
|
|
|
:py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`,
|
|
|
|
:py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`.
|
2013-07-09 18:32:14 +04:00
|
|
|
:returns: Returns a flipped or rotated copy of this image.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.load()
|
2014-11-07 03:37:12 +03:00
|
|
|
return self._new(self.im.transpose(method))
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-09-02 16:53:58 +04:00
|
|
|
def effect_spread(self, distance):
|
|
|
|
"""
|
|
|
|
Randomly spread pixels in an image.
|
|
|
|
|
|
|
|
:param distance: Distance to spread pixels.
|
|
|
|
"""
|
|
|
|
self.load()
|
2016-06-02 10:06:49 +03:00
|
|
|
return self._new(self.im.effect_spread(distance))
|
2014-09-02 16:53:58 +04:00
|
|
|
|
2015-06-19 08:55:35 +03:00
|
|
|
def toqimage(self):
|
2015-06-21 09:31:51 +03:00
|
|
|
"""Returns a QImage copy of this image"""
|
2017-01-17 16:22:18 +03:00
|
|
|
from . import ImageQt
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2015-06-19 08:55:35 +03:00
|
|
|
if not ImageQt.qt_is_installed:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Qt bindings are not installed"
|
|
|
|
raise ImportError(msg)
|
2015-06-19 08:55:35 +03:00
|
|
|
return ImageQt.toqimage(self)
|
2014-09-15 22:24:56 +04:00
|
|
|
|
2015-06-19 08:55:35 +03:00
|
|
|
def toqpixmap(self):
|
2015-06-21 09:31:51 +03:00
|
|
|
"""Returns a QPixmap copy of this image"""
|
2017-01-17 16:22:18 +03:00
|
|
|
from . import ImageQt
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2015-06-19 08:55:35 +03:00
|
|
|
if not ImageQt.qt_is_installed:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Qt bindings are not installed"
|
|
|
|
raise ImportError(msg)
|
2015-06-19 08:55:35 +03:00
|
|
|
return ImageQt.toqpixmap(self)
|
2014-09-15 22:24:56 +04:00
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Abstract handlers.
|
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2019-09-30 17:56:31 +03:00
|
|
|
class ImagePointHandler:
|
2020-07-09 20:48:42 +03:00
|
|
|
"""
|
|
|
|
Used as a mixin by point transforms
|
|
|
|
(for use with :py:meth:`~PIL.Image.Image.point`)
|
|
|
|
"""
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
pass
|
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2019-09-30 17:56:31 +03:00
|
|
|
class ImageTransformHandler:
|
2020-07-09 20:48:42 +03:00
|
|
|
"""
|
|
|
|
Used as a mixin by geometry transforms
|
|
|
|
(for use with :py:meth:`~PIL.Image.Image.transform`)
|
|
|
|
"""
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
pass
|
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Factories
|
|
|
|
|
|
|
|
#
|
|
|
|
# Debugging
|
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def _wedge():
|
2018-04-09 16:13:19 +03:00
|
|
|
"""Create greyscale wedge (for debugging only)"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
return Image()._new(core.wedge("L"))
|
|
|
|
|
2017-01-29 19:38:06 +03:00
|
|
|
|
2016-10-03 13:38:15 +03:00
|
|
|
def _check_size(size):
|
|
|
|
"""
|
|
|
|
Common check to enforce type and sanity check on size tuples
|
|
|
|
|
|
|
|
:param size: Should be a 2 tuple of (width, height)
|
|
|
|
:returns: True, or raises a ValueError
|
|
|
|
"""
|
|
|
|
|
2016-10-04 03:06:35 +03:00
|
|
|
if not isinstance(size, (list, tuple)):
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Size must be a tuple"
|
|
|
|
raise ValueError(msg)
|
2016-10-03 13:38:15 +03:00
|
|
|
if len(size) != 2:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Size must be a tuple of length 2"
|
|
|
|
raise ValueError(msg)
|
2016-11-29 22:25:49 +03:00
|
|
|
if size[0] < 0 or size[1] < 0:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Width and height must be >= 0"
|
|
|
|
raise ValueError(msg)
|
2016-10-03 13:38:15 +03:00
|
|
|
|
|
|
|
return True
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2017-01-29 19:38:06 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def new(mode, size, color=0):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Creates a new image with the given mode and size.
|
|
|
|
|
2014-11-19 23:49:27 +03:00
|
|
|
:param mode: The mode to use for the new image. See:
|
|
|
|
:ref:`concept-modes`.
|
2013-07-09 23:12:28 +04:00
|
|
|
:param size: A 2-tuple, containing (width, height) in pixels.
|
2013-10-12 09:18:40 +04:00
|
|
|
:param color: What color to use for the image. Default is black.
|
2013-07-09 23:12:28 +04:00
|
|
|
If given, this should be a single integer or floating point value
|
|
|
|
for single-band modes, and a tuple for multi-band modes (one value
|
2013-10-12 09:18:40 +04:00
|
|
|
per band). When creating RGB images, you can also use color
|
|
|
|
strings as supported by the ImageColor module. If the color is
|
2013-07-09 23:12:28 +04:00
|
|
|
None, the image is not initialised.
|
2013-10-12 09:18:40 +04:00
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2016-10-03 13:38:15 +03:00
|
|
|
_check_size(size)
|
2016-10-04 03:06:35 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
if color is None:
|
|
|
|
# don't initialize
|
|
|
|
return Image()._new(core.new(mode, size))
|
|
|
|
|
2019-10-08 17:01:11 +03:00
|
|
|
if isinstance(color, str):
|
2010-07-31 06:52:47 +04:00
|
|
|
# css3-style specifier
|
|
|
|
|
2017-01-17 16:22:18 +03:00
|
|
|
from . import ImageColor
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
color = ImageColor.getcolor(color, mode)
|
|
|
|
|
2019-03-15 09:30:28 +03:00
|
|
|
im = Image()
|
2019-03-21 16:28:20 +03:00
|
|
|
if mode == "P" and isinstance(color, (list, tuple)) and len(color) in [3, 4]:
|
2019-03-15 09:30:28 +03:00
|
|
|
# RGB or RGBA value for a P image
|
|
|
|
from . import ImagePalette
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2019-03-15 09:30:28 +03:00
|
|
|
im.palette = ImagePalette.ImagePalette()
|
|
|
|
color = im.palette.getcolor(color)
|
|
|
|
return im._new(core.fill(mode, size, color))
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
def frombytes(mode, size, data, decoder_name="raw", *args):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Creates a copy of an image memory from pixel data in a buffer.
|
|
|
|
|
|
|
|
In its simplest form, this function takes three arguments
|
|
|
|
(mode, size, and unpacked pixel data).
|
|
|
|
|
2022-03-01 08:34:21 +03:00
|
|
|
You can also use any pixel decoder supported by PIL. For more
|
2013-07-09 23:12:28 +04:00
|
|
|
information on available decoders, see the section
|
2022-03-01 08:34:21 +03:00
|
|
|
:ref:`Writing Your Own File Codec <file-codecs>`.
|
2013-07-09 23:12:28 +04:00
|
|
|
|
|
|
|
Note that this function decodes pixel data only, not entire images.
|
|
|
|
If you have an entire image in a string, wrap it in a
|
2013-10-12 09:18:40 +04:00
|
|
|
:py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load
|
|
|
|
it.
|
2013-07-09 23:12:28 +04:00
|
|
|
|
2014-11-19 23:49:27 +03:00
|
|
|
:param mode: The image mode. See: :ref:`concept-modes`.
|
2013-07-09 23:12:28 +04:00
|
|
|
:param size: The image size.
|
|
|
|
:param data: A byte buffer containing raw data for the given mode.
|
|
|
|
:param decoder_name: What decoder to use.
|
|
|
|
:param args: Additional parameters for the given decoder.
|
2013-10-12 09:18:40 +04:00
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2016-10-03 13:38:15 +03:00
|
|
|
_check_size(size)
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# may pass tuple instead of argument list
|
2012-10-16 07:14:10 +04:00
|
|
|
if len(args) == 1 and isinstance(args[0], tuple):
|
2010-07-31 06:52:47 +04:00
|
|
|
args = args[0]
|
|
|
|
|
|
|
|
if decoder_name == "raw" and args == ():
|
|
|
|
args = mode
|
|
|
|
|
|
|
|
im = new(mode, size)
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
im.frombytes(data, decoder_name, args)
|
2010-07-31 06:52:47 +04:00
|
|
|
return im
|
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def frombuffer(mode, size, data, decoder_name="raw", *args):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Creates an image memory referencing pixel data in a byte buffer.
|
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
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".
|
2013-07-09 23:12:28 +04:00
|
|
|
|
|
|
|
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
|
2020-09-01 20:16:46 +03:00
|
|
|
:py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load it.
|
2013-07-09 23:12:28 +04:00
|
|
|
|
|
|
|
In the current version, the default parameters used for the "raw" decoder
|
2016-02-14 13:02:38 +03:00
|
|
|
differs from that used for :py:func:`~PIL.Image.frombytes`. This is a
|
2013-10-12 09:18:40 +04:00
|
|
|
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.
|
2013-07-09 23:12:28 +04:00
|
|
|
|
2014-11-19 23:49:27 +03:00
|
|
|
:param mode: The image mode. See: :ref:`concept-modes`.
|
2013-07-09 23:12:28 +04:00
|
|
|
: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)
|
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
2013-07-09 23:12:28 +04:00
|
|
|
|
|
|
|
.. versionadded:: 1.1.4
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2016-10-03 13:38:15 +03:00
|
|
|
_check_size(size)
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# may pass tuple instead of argument list
|
2012-10-16 07:14:10 +04:00
|
|
|
if len(args) == 1 and isinstance(args[0], tuple):
|
2010-07-31 06:52:47 +04:00
|
|
|
args = args[0]
|
|
|
|
|
|
|
|
if decoder_name == "raw":
|
|
|
|
if args == ():
|
2016-02-16 12:02:15 +03:00
|
|
|
args = mode, 0, 1
|
2010-07-31 06:52:47 +04:00
|
|
|
if args[0] in _MAPMODES:
|
2014-04-22 10:23:34 +04:00
|
|
|
im = new(mode, (1, 1))
|
2020-01-25 14:37:26 +03:00
|
|
|
im = im._new(core.map_buffer(data, size, decoder_name, 0, args))
|
2022-05-09 11:50:54 +03:00
|
|
|
if mode == "P":
|
|
|
|
from . import ImagePalette
|
|
|
|
|
|
|
|
im.palette = ImagePalette.ImagePalette("RGB", im.im.getpalette("RGB"))
|
2010-07-31 06:52:47 +04:00
|
|
|
im.readonly = 1
|
|
|
|
return im
|
|
|
|
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
return frombytes(mode, size, data, decoder_name, args)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
|
|
|
|
def fromarray(obj, mode=None):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Creates an image memory from an object exporting the array interface
|
|
|
|
(using the buffer protocol).
|
|
|
|
|
2020-09-01 20:16:46 +03:00
|
|
|
If ``obj`` is not contiguous, then the ``tobytes`` method is called
|
2013-10-12 09:18:40 +04:00
|
|
|
and :py:func:`~PIL.Image.frombuffer` is used.
|
2013-07-09 23:12:28 +04:00
|
|
|
|
2018-08-12 06:58:26 +03:00
|
|
|
If you have an image in NumPy::
|
|
|
|
|
|
|
|
from PIL import Image
|
|
|
|
import numpy as np
|
2021-11-23 12:35:35 +03:00
|
|
|
im = Image.open("hopper.jpg")
|
2018-09-20 15:27:30 +03:00
|
|
|
a = np.asarray(im)
|
2018-08-12 06:58:26 +03:00
|
|
|
|
|
|
|
Then this can be used to convert it to a Pillow image::
|
|
|
|
|
|
|
|
im = Image.fromarray(a)
|
|
|
|
|
2013-07-09 23:12:28 +04:00
|
|
|
:param obj: Object with array interface
|
2021-11-23 12:35:35 +03:00
|
|
|
: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.
|
2014-11-19 23:49:27 +03:00
|
|
|
:returns: An image object.
|
2013-07-09 23:12:28 +04:00
|
|
|
|
|
|
|
.. versionadded:: 1.1.6
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
arr = obj.__array_interface__
|
2019-03-21 16:28:20 +03:00
|
|
|
shape = arr["shape"]
|
2010-07-31 06:52:47 +04:00
|
|
|
ndim = len(shape)
|
2019-03-21 16:28:20 +03:00
|
|
|
strides = arr.get("strides", None)
|
2010-07-31 06:52:47 +04:00
|
|
|
if mode is None:
|
|
|
|
try:
|
2019-03-21 16:28:20 +03:00
|
|
|
typekey = (1, 1) + shape[2:], arr["typestr"]
|
2020-06-21 13:13:35 +03:00
|
|
|
except KeyError as e:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Cannot handle this data type"
|
|
|
|
raise TypeError(msg) from e
|
2019-10-29 23:23:08 +03:00
|
|
|
try:
|
2010-07-31 06:52:47 +04:00
|
|
|
mode, rawmode = _fromarray_typemap[typekey]
|
2020-06-21 13:13:35 +03:00
|
|
|
except KeyError as e:
|
2022-12-30 06:24:28 +03:00
|
|
|
msg = "Cannot handle this data type: %s, %s" % typekey
|
|
|
|
raise TypeError(msg) from e
|
2010-07-31 06:52:47 +04:00
|
|
|
else:
|
|
|
|
rawmode = mode
|
|
|
|
if mode in ["1", "L", "I", "P", "F"]:
|
|
|
|
ndmax = 2
|
|
|
|
elif mode == "RGB":
|
|
|
|
ndmax = 3
|
|
|
|
else:
|
|
|
|
ndmax = 4
|
|
|
|
if ndim > ndmax:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = f"Too many dimensions: {ndim} > {ndmax}."
|
|
|
|
raise ValueError(msg)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2020-05-04 13:07:23 +03:00
|
|
|
size = 1 if ndim == 1 else shape[1], shape[0]
|
2010-07-31 06:52:47 +04:00
|
|
|
if strides is not None:
|
2019-03-21 16:28:20 +03:00
|
|
|
if hasattr(obj, "tobytes"):
|
2013-05-22 08:04:22 +04:00
|
|
|
obj = obj.tobytes()
|
|
|
|
else:
|
|
|
|
obj = obj.tostring()
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)
|
|
|
|
|
2014-09-15 22:24:56 +04:00
|
|
|
|
2015-06-19 08:55:35 +03:00
|
|
|
def fromqimage(im):
|
2015-06-21 09:31:51 +03:00
|
|
|
"""Creates an image instance from a QImage image"""
|
2017-01-17 16:22:18 +03:00
|
|
|
from . import ImageQt
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2015-06-19 08:55:35 +03:00
|
|
|
if not ImageQt.qt_is_installed:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Qt bindings are not installed"
|
|
|
|
raise ImportError(msg)
|
2015-06-19 08:55:35 +03:00
|
|
|
return ImageQt.fromqimage(im)
|
|
|
|
|
2014-09-15 22:24:56 +04:00
|
|
|
|
2015-06-19 08:55:35 +03:00
|
|
|
def fromqpixmap(im):
|
2015-06-21 09:31:51 +03:00
|
|
|
"""Creates an image instance from a QPixmap image"""
|
2017-01-17 16:22:18 +03:00
|
|
|
from . import ImageQt
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2015-06-19 08:55:35 +03:00
|
|
|
if not ImageQt.qt_is_installed:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "Qt bindings are not installed"
|
|
|
|
raise ImportError(msg)
|
2015-06-19 08:55:35 +03:00
|
|
|
return ImageQt.fromqpixmap(im)
|
2014-09-15 22:24:56 +04:00
|
|
|
|
2017-01-29 19:38:06 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
_fromarray_typemap = {
|
|
|
|
# (shape, typestr) => mode, rawmode
|
|
|
|
# first two members of shape are set to one
|
2017-09-06 04:21:50 +03:00
|
|
|
((1, 1), "|b1"): ("1", "1;8"),
|
2010-07-31 06:52:47 +04:00
|
|
|
((1, 1), "|u1"): ("L", "L"),
|
|
|
|
((1, 1), "|i1"): ("I", "I;8"),
|
2016-04-11 21:33:41 +03:00
|
|
|
((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"),
|
2010-07-31 06:52:47 +04:00
|
|
|
((1, 1), "<f4"): ("F", "F;32F"),
|
|
|
|
((1, 1), ">f4"): ("F", "F;32BF"),
|
|
|
|
((1, 1), "<f8"): ("F", "F;64F"),
|
|
|
|
((1, 1), ">f8"): ("F", "F;64BF"),
|
2016-04-27 16:23:44 +03:00
|
|
|
((1, 1, 2), "|u1"): ("LA", "LA"),
|
2010-07-31 06:52:47 +04:00
|
|
|
((1, 1, 3), "|u1"): ("RGB", "RGB"),
|
|
|
|
((1, 1, 4), "|u1"): ("RGBA", "RGBA"),
|
2022-04-10 19:59:42 +03:00
|
|
|
# shortcuts:
|
|
|
|
((1, 1), _ENDIAN + "i4"): ("I", "I"),
|
|
|
|
((1, 1), _ENDIAN + "f4"): ("F", "F"),
|
2019-03-21 16:28:20 +03:00
|
|
|
}
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
|
2014-05-27 13:40:52 +04:00
|
|
|
def _decompression_bomb_check(size):
|
2014-05-26 17:25:15 +04:00
|
|
|
if MAX_IMAGE_PIXELS is None:
|
2014-05-14 19:04:18 +04:00
|
|
|
return
|
|
|
|
|
2014-05-26 17:25:15 +04:00
|
|
|
pixels = size[0] * size[1]
|
2014-05-14 19:04:18 +04:00
|
|
|
|
2017-06-21 12:52:18 +03:00
|
|
|
if pixels > 2 * MAX_IMAGE_PIXELS:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = (
|
2020-07-16 12:43:29 +03:00
|
|
|
f"Image size ({pixels} pixels) exceeds limit of {2 * MAX_IMAGE_PIXELS} "
|
|
|
|
"pixels, could be decompression bomb DOS attack."
|
2019-03-21 16:28:20 +03:00
|
|
|
)
|
2022-12-22 00:51:35 +03:00
|
|
|
raise DecompressionBombError(msg)
|
2017-06-21 12:52:18 +03:00
|
|
|
|
2014-05-26 17:25:15 +04:00
|
|
|
if pixels > MAX_IMAGE_PIXELS:
|
|
|
|
warnings.warn(
|
2020-07-16 12:43:29 +03:00
|
|
|
f"Image size ({pixels} pixels) exceeds limit of {MAX_IMAGE_PIXELS} pixels, "
|
|
|
|
"could be decompression bomb DOS attack.",
|
2019-03-21 16:28:20 +03:00
|
|
|
DecompressionBombWarning,
|
|
|
|
)
|
2014-05-14 19:04:18 +04:00
|
|
|
|
|
|
|
|
2020-08-03 01:24:02 +03:00
|
|
|
def open(fp, mode="r", formats=None):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Opens and identifies the given image file.
|
|
|
|
|
2014-04-18 08:53:49 +04:00
|
|
|
This is a lazy operation; this function identifies the file, but
|
|
|
|
the file remains open and the actual image data is not read from
|
|
|
|
the file until you try to process the data (or call the
|
|
|
|
:py:meth:`~PIL.Image.Image.load` method). See
|
2018-06-30 09:44:59 +03:00
|
|
|
:py:func:`~PIL.Image.new`. See :ref:`file-handling`.
|
2013-07-09 23:12:28 +04:00
|
|
|
|
2015-08-05 15:32:15 +03:00
|
|
|
:param fp: A filename (string), pathlib.Path object or a file object.
|
2020-07-09 20:48:04 +03:00
|
|
|
The file object must implement ``file.read``,
|
2020-07-21 13:42:11 +03:00
|
|
|
``file.seek``, and ``file.tell`` methods,
|
2015-08-05 17:24:08 +03:00
|
|
|
and be opened in binary mode.
|
2013-07-09 23:12:28 +04:00
|
|
|
:param mode: The mode. If given, this argument must be "r".
|
2020-08-03 01:38:59 +03:00
|
|
|
:param formats: A list or tuple of formats to attempt to load the file in.
|
|
|
|
This can be used to restrict the set of formats checked.
|
|
|
|
Pass ``None`` to try all supported formats. You can print the set of
|
2021-05-08 05:37:06 +03:00
|
|
|
available formats by running ``python3 -m PIL`` or using
|
2020-08-03 01:38:59 +03:00
|
|
|
the :py:func:`PIL.features.pilinfo` function.
|
2013-10-12 09:18:40 +04:00
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
2019-12-26 05:16:49 +03:00
|
|
|
:exception FileNotFoundError: If the file cannot be found.
|
|
|
|
:exception PIL.UnidentifiedImageError: If the image cannot be opened and
|
|
|
|
identified.
|
2019-12-26 11:55:10 +03:00
|
|
|
:exception ValueError: If the ``mode`` is not "r", or if a ``StringIO``
|
2019-12-26 05:10:39 +03:00
|
|
|
instance is used for ``fp``.
|
2020-08-05 11:45:23 +03:00
|
|
|
:exception TypeError: If ``formats`` is not ``None``, a list or a tuple.
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
if mode != "r":
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = f"bad mode {repr(mode)}"
|
|
|
|
raise ValueError(msg)
|
2019-12-26 05:10:39 +03:00
|
|
|
elif isinstance(fp, io.StringIO):
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = (
|
2019-12-26 12:21:16 +03:00
|
|
|
"StringIO cannot be used to open an image. "
|
|
|
|
"Binary data must be used instead."
|
2019-12-26 05:10:39 +03:00
|
|
|
)
|
2022-12-22 00:51:35 +03:00
|
|
|
raise ValueError(msg)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2020-08-03 01:24:02 +03:00
|
|
|
if formats is None:
|
|
|
|
formats = ID
|
|
|
|
elif not isinstance(formats, (list, tuple)):
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "formats must be a list or tuple"
|
|
|
|
raise TypeError(msg)
|
2020-08-03 01:24:02 +03:00
|
|
|
|
2016-07-17 06:29:36 +03:00
|
|
|
exclusive_fp = False
|
2015-08-05 13:54:33 +03:00
|
|
|
filename = ""
|
2019-09-26 15:12:28 +03:00
|
|
|
if isinstance(fp, Path):
|
2016-12-17 20:50:50 +03:00
|
|
|
filename = str(fp.resolve())
|
2022-04-10 21:20:48 +03:00
|
|
|
elif is_path(fp):
|
2019-05-04 08:00:49 +03:00
|
|
|
filename = fp
|
2016-09-14 21:51:10 +03:00
|
|
|
|
2015-08-05 13:54:33 +03:00
|
|
|
if filename:
|
|
|
|
fp = builtins.open(filename, "rb")
|
2016-07-17 06:29:36 +03:00
|
|
|
exclusive_fp = True
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2015-03-26 15:25:26 +03:00
|
|
|
try:
|
|
|
|
fp.seek(0)
|
|
|
|
except (AttributeError, io.UnsupportedOperation):
|
|
|
|
fp = io.BytesIO(fp.read())
|
2016-07-17 06:29:36 +03:00
|
|
|
exclusive_fp = True
|
2015-03-26 15:25:26 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
prefix = fp.read(16)
|
|
|
|
|
|
|
|
preinit()
|
|
|
|
|
2018-09-29 19:34:03 +03:00
|
|
|
accept_warnings = []
|
2018-10-21 09:01:25 +03:00
|
|
|
|
2020-08-03 01:24:02 +03:00
|
|
|
def _open_core(fp, filename, prefix, formats):
|
|
|
|
for i in formats:
|
2021-02-05 12:28:34 +03:00
|
|
|
i = i.upper()
|
2020-11-11 13:05:57 +03:00
|
|
|
if i not in OPEN:
|
|
|
|
init()
|
2010-07-31 06:52:47 +04:00
|
|
|
try:
|
2021-02-05 12:28:34 +03:00
|
|
|
factory, accept = OPEN[i]
|
2018-09-30 08:34:27 +03:00
|
|
|
result = not accept or accept(prefix)
|
|
|
|
if type(result) in [str, bytes]:
|
2018-09-29 19:34:03 +03:00
|
|
|
accept_warnings.append(result)
|
2018-09-30 08:34:27 +03:00
|
|
|
elif result:
|
2010-07-31 06:52:47 +04:00
|
|
|
fp.seek(0)
|
2014-05-14 19:04:18 +04:00
|
|
|
im = factory(fp, filename)
|
2014-05-27 13:40:52 +04:00
|
|
|
_decompression_bomb_check(im.size)
|
2014-05-14 19:04:18 +04:00
|
|
|
return im
|
2015-04-02 08:29:18 +03:00
|
|
|
except (SyntaxError, IndexError, TypeError, struct.error):
|
2015-09-14 13:42:08 +03:00
|
|
|
# Leave disabled by default, spams the logs with image
|
2015-10-11 13:24:35 +03:00
|
|
|
# opening failures that are entirely expected.
|
2015-12-10 01:35:35 +03:00
|
|
|
# logger.debug("", exc_info=True)
|
2015-09-14 13:42:08 +03:00
|
|
|
continue
|
2019-01-13 05:32:14 +03:00
|
|
|
except BaseException:
|
2018-11-09 03:35:08 +03:00
|
|
|
if exclusive_fp:
|
|
|
|
fp.close()
|
|
|
|
raise
|
2015-09-10 17:03:24 +03:00
|
|
|
return None
|
|
|
|
|
2020-08-03 01:24:02 +03:00
|
|
|
im = _open_core(fp, filename, prefix, formats)
|
2015-09-11 12:28:19 +03:00
|
|
|
|
2023-01-14 15:22:35 +03:00
|
|
|
if im is None and formats is ID:
|
2023-01-19 00:06:30 +03:00
|
|
|
checked_formats = formats.copy()
|
2015-09-10 17:03:24 +03:00
|
|
|
if init():
|
2023-01-19 00:06:30 +03:00
|
|
|
im = _open_core(
|
|
|
|
fp,
|
|
|
|
filename,
|
|
|
|
prefix,
|
|
|
|
tuple(format for format in formats if format not in checked_formats),
|
|
|
|
)
|
2015-09-10 17:03:24 +03:00
|
|
|
|
|
|
|
if im:
|
2017-03-15 02:16:38 +03:00
|
|
|
im._exclusive_fp = exclusive_fp
|
2015-09-10 17:03:24 +03:00
|
|
|
return im
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2016-07-17 06:29:36 +03:00
|
|
|
if exclusive_fp:
|
|
|
|
fp.close()
|
2018-09-29 19:34:03 +03:00
|
|
|
for message in accept_warnings:
|
2018-09-30 08:34:27 +03:00
|
|
|
warnings.warn(message)
|
2022-12-30 06:24:28 +03:00
|
|
|
msg = "cannot identify image file %r" % (filename if filename else fp)
|
|
|
|
raise UnidentifiedImageError(msg)
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
#
|
|
|
|
# Image processing.
|
|
|
|
|
2015-09-11 12:28:19 +03:00
|
|
|
|
2012-12-04 19:44:26 +04:00
|
|
|
def alpha_composite(im1, im2):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Alpha composite im2 over im1.
|
|
|
|
|
2016-02-01 13:02:43 +03:00
|
|
|
:param im1: The first image. Must have mode RGBA.
|
|
|
|
:param im2: The second image. Must have mode RGBA, and the same size as
|
2013-07-09 23:12:28 +04:00
|
|
|
the first image.
|
2013-10-12 09:18:40 +04:00
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
2012-12-04 19:44:26 +04:00
|
|
|
|
|
|
|
im1.load()
|
|
|
|
im2.load()
|
|
|
|
return im1._new(core.alpha_composite(im1.im, im2.im))
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def blend(im1, im2, alpha):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Creates a new image by interpolating between two input images, using
|
2022-03-19 09:48:31 +03:00
|
|
|
a constant alpha::
|
2013-07-09 23:12:28 +04:00
|
|
|
|
|
|
|
out = image1 * (1.0 - alpha) + image2 * alpha
|
|
|
|
|
|
|
|
:param im1: The first image.
|
|
|
|
:param im2: The second image. Must have the same mode and size as
|
|
|
|
the first image.
|
|
|
|
:param alpha: The interpolation alpha factor. If alpha is 0.0, a
|
|
|
|
copy of the first image is returned. If alpha is 1.0, a copy of
|
|
|
|
the second image is returned. There are no restrictions on the
|
|
|
|
alpha value. If necessary, the result is clipped to fit into
|
|
|
|
the allowed output range.
|
2013-10-12 09:18:40 +04:00
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
im1.load()
|
|
|
|
im2.load()
|
|
|
|
return im1._new(core.blend(im1.im, im2.im, alpha))
|
|
|
|
|
|
|
|
|
|
|
|
def composite(image1, image2, mask):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Create composite image by blending images using a transparency mask.
|
|
|
|
|
|
|
|
:param image1: The first image.
|
|
|
|
:param image2: The second image. Must have the same mode and
|
|
|
|
size as the first image.
|
2014-10-25 12:07:34 +04:00
|
|
|
:param mask: A mask image. This image can have mode
|
2013-07-09 23:12:28 +04:00
|
|
|
"1", "L", or "RGBA", and must have the same size as the
|
|
|
|
other two images.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
image = image2.copy()
|
|
|
|
image.paste(image1, None, mask)
|
|
|
|
return image
|
|
|
|
|
|
|
|
|
|
|
|
def eval(image, *args):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Applies the function (which should take one argument) to each pixel
|
|
|
|
in the given image. If the image has more than one band, the same
|
|
|
|
function is applied to each band. Note that the function is
|
|
|
|
evaluated once for each possible pixel value, so you cannot use
|
|
|
|
random components or other generators.
|
|
|
|
|
|
|
|
:param image: The input image.
|
|
|
|
:param function: A function object, taking one integer argument.
|
2013-10-12 09:18:40 +04:00
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
return image.point(args[0])
|
|
|
|
|
|
|
|
|
|
|
|
def merge(mode, bands):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Merge a set of single band images into a new multiband image.
|
|
|
|
|
2014-11-19 23:49:27 +03:00
|
|
|
:param mode: The mode to use for the output image. See:
|
|
|
|
:ref:`concept-modes`.
|
2013-07-09 23:12:28 +04:00
|
|
|
:param bands: A sequence containing one single-band image for
|
|
|
|
each band in the output image. All bands must have the
|
|
|
|
same size.
|
2013-10-12 09:18:40 +04:00
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
if getmodebands(mode) != len(bands) or "*" in mode:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "wrong number of bands"
|
|
|
|
raise ValueError(msg)
|
2017-08-19 23:12:51 +03:00
|
|
|
for band in bands[1:]:
|
|
|
|
if band.mode != getmodetype(mode):
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "mode mismatch"
|
|
|
|
raise ValueError(msg)
|
2017-08-19 23:12:51 +03:00
|
|
|
if band.size != bands[0].size:
|
2022-12-22 00:51:35 +03:00
|
|
|
msg = "size mismatch"
|
|
|
|
raise ValueError(msg)
|
2017-08-12 19:08:07 +03:00
|
|
|
for band in bands:
|
|
|
|
band.load()
|
|
|
|
return bands[0]._new(core.merge(mode, *[b.im for b in bands]))
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Plugin registry
|
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def register_open(id, factory, accept=None):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Register an image file plugin. This function should not be used
|
|
|
|
in application code.
|
|
|
|
|
|
|
|
:param id: An image format identifier.
|
|
|
|
:param factory: An image file factory method.
|
|
|
|
:param accept: An optional function that can be used to quickly
|
|
|
|
reject images having another format.
|
|
|
|
"""
|
2012-10-11 02:11:13 +04:00
|
|
|
id = id.upper()
|
2023-01-28 14:43:04 +03:00
|
|
|
if id not in ID:
|
|
|
|
ID.append(id)
|
2010-07-31 06:52:47 +04:00
|
|
|
OPEN[id] = factory, accept
|
|
|
|
|
|
|
|
|
|
|
|
def register_mime(id, mimetype):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Registers an image MIME type. This function should not be used
|
|
|
|
in application code.
|
|
|
|
|
|
|
|
:param id: An image format identifier.
|
|
|
|
:param mimetype: The image MIME type for this format.
|
|
|
|
"""
|
2012-10-11 02:11:13 +04:00
|
|
|
MIME[id.upper()] = mimetype
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
|
|
|
|
def register_save(id, driver):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Registers an image save function. This function should not be
|
|
|
|
used in application code.
|
|
|
|
|
|
|
|
:param id: An image format identifier.
|
|
|
|
:param driver: A function to save images in this format.
|
|
|
|
"""
|
2012-10-11 02:11:13 +04:00
|
|
|
SAVE[id.upper()] = driver
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
|
2015-06-30 11:02:48 +03:00
|
|
|
def register_save_all(id, driver):
|
|
|
|
"""
|
|
|
|
Registers an image function to save all the frames
|
|
|
|
of a multiframe format. This function should not be
|
|
|
|
used in application code.
|
|
|
|
|
|
|
|
:param id: An image format identifier.
|
|
|
|
:param driver: A function to save images in this format.
|
|
|
|
"""
|
|
|
|
SAVE_ALL[id.upper()] = driver
|
|
|
|
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def register_extension(id, extension):
|
2013-07-09 23:12:28 +04:00
|
|
|
"""
|
|
|
|
Registers an image extension. This function should not be
|
|
|
|
used in application code.
|
|
|
|
|
|
|
|
:param id: An image format identifier.
|
|
|
|
:param extension: An extension used for this format.
|
|
|
|
"""
|
2012-10-11 02:11:13 +04:00
|
|
|
EXTENSION[extension.lower()] = id.upper()
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2018-03-03 12:54:00 +03:00
|
|
|
|
2016-04-25 07:59:02 +03:00
|
|
|
def register_extensions(id, extensions):
|
|
|
|
"""
|
|
|
|
Registers image extensions. This function should not be
|
|
|
|
used in application code.
|
|
|
|
|
|
|
|
:param id: An image format identifier.
|
|
|
|
:param extensions: A list of extensions used for this format.
|
|
|
|
"""
|
|
|
|
for extension in extensions:
|
|
|
|
register_extension(id, extension)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2018-03-03 12:54:00 +03:00
|
|
|
|
2016-06-20 03:39:31 +03:00
|
|
|
def registered_extensions():
|
|
|
|
"""
|
|
|
|
Returns a dictionary containing all file extensions belonging
|
|
|
|
to registered plugins
|
|
|
|
"""
|
2022-12-19 00:19:15 +03:00
|
|
|
init()
|
2016-06-20 03:39:31 +03:00
|
|
|
return EXTENSION
|
|
|
|
|
2017-04-20 14:14:23 +03:00
|
|
|
|
2016-05-31 11:10:01 +03:00
|
|
|
def register_decoder(name, decoder):
|
|
|
|
"""
|
|
|
|
Registers an image decoder. This function should not be
|
|
|
|
used in application code.
|
|
|
|
|
|
|
|
:param name: The name of the decoder
|
|
|
|
:param decoder: A callable(mode, args) that returns an
|
|
|
|
ImageFile.PyDecoder object
|
|
|
|
|
2017-03-31 05:02:56 +03:00
|
|
|
.. versionadded:: 4.1.0
|
2016-05-31 11:10:01 +03:00
|
|
|
"""
|
|
|
|
DECODERS[name] = decoder
|
|
|
|
|
|
|
|
|
|
|
|
def register_encoder(name, encoder):
|
|
|
|
"""
|
|
|
|
Registers an image encoder. This function should not be
|
|
|
|
used in application code.
|
|
|
|
|
|
|
|
:param name: The name of the encoder
|
|
|
|
:param encoder: A callable(mode, args) that returns an
|
|
|
|
ImageFile.PyEncoder object
|
|
|
|
|
2017-02-21 17:40:45 +03:00
|
|
|
.. versionadded:: 4.1.0
|
2016-05-31 11:10:01 +03:00
|
|
|
"""
|
|
|
|
ENCODERS[name] = encoder
|
|
|
|
|
2016-06-20 03:39:31 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# --------------------------------------------------------------------
|
2020-06-21 13:26:10 +03:00
|
|
|
# Simple display support.
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def _show(image, **options):
|
2017-01-17 16:22:18 +03:00
|
|
|
from . import ImageShow
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2021-10-18 02:53:48 +03:00
|
|
|
ImageShow.show(image, **options)
|
2014-09-02 15:11:08 +04:00
|
|
|
|
|
|
|
|
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Effects
|
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2014-09-02 16:14:00 +04:00
|
|
|
def effect_mandelbrot(size, extent, quality):
|
|
|
|
"""
|
|
|
|
Generate a Mandelbrot set covering the given extent.
|
|
|
|
|
|
|
|
:param size: The requested size in pixels, as a 2-tuple:
|
|
|
|
(width, height).
|
|
|
|
:param extent: The extent to cover, as a 4-tuple:
|
2022-04-24 16:12:37 +03:00
|
|
|
(x0, y0, x1, y1).
|
2014-09-02 16:14:00 +04:00
|
|
|
:param quality: Quality.
|
|
|
|
"""
|
|
|
|
return Image()._new(core.effect_mandelbrot(size, extent, quality))
|
|
|
|
|
2014-09-02 16:53:58 +04:00
|
|
|
|
2014-09-02 15:11:08 +04:00
|
|
|
def effect_noise(size, sigma):
|
|
|
|
"""
|
2014-09-02 16:14:00 +04:00
|
|
|
Generate Gaussian noise centered around 128.
|
2014-09-02 15:11:08 +04:00
|
|
|
|
|
|
|
:param size: The requested size in pixels, as a 2-tuple:
|
|
|
|
(width, height).
|
|
|
|
:param sigma: Standard deviation of noise.
|
|
|
|
"""
|
|
|
|
return Image()._new(core.effect_noise(size, sigma))
|
2017-01-29 19:17:31 +03:00
|
|
|
|
|
|
|
|
|
|
|
def linear_gradient(mode):
|
|
|
|
"""
|
|
|
|
Generate 256x256 linear gradient from black to white, top to bottom.
|
|
|
|
|
|
|
|
:param mode: Input mode.
|
|
|
|
"""
|
|
|
|
return Image()._new(core.linear_gradient(mode))
|
2017-01-29 19:44:24 +03:00
|
|
|
|
|
|
|
|
|
|
|
def radial_gradient(mode):
|
|
|
|
"""
|
|
|
|
Generate 256x256 radial gradient from black to white, centre to edge.
|
|
|
|
|
|
|
|
:param mode: Input mode.
|
|
|
|
"""
|
|
|
|
return Image()._new(core.radial_gradient(mode))
|
2017-09-18 21:29:48 +03:00
|
|
|
|
|
|
|
|
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Resources
|
|
|
|
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2017-09-18 21:29:48 +03:00
|
|
|
def _apply_env_variables(env=None):
|
|
|
|
if env is None:
|
|
|
|
env = os.environ
|
|
|
|
|
|
|
|
for var_name, setter in [
|
2019-03-21 16:28:20 +03:00
|
|
|
("PILLOW_ALIGNMENT", core.set_alignment),
|
|
|
|
("PILLOW_BLOCK_SIZE", core.set_block_size),
|
|
|
|
("PILLOW_BLOCKS_MAX", core.set_blocks_max),
|
2017-09-18 21:29:48 +03:00
|
|
|
]:
|
|
|
|
if var_name not in env:
|
|
|
|
continue
|
|
|
|
|
|
|
|
var = env[var_name].lower()
|
|
|
|
|
|
|
|
units = 1
|
2019-03-21 16:28:20 +03:00
|
|
|
for postfix, mul in [("k", 1024), ("m", 1024 * 1024)]:
|
2017-09-18 21:29:48 +03:00
|
|
|
if var.endswith(postfix):
|
|
|
|
units = mul
|
2019-03-21 16:28:20 +03:00
|
|
|
var = var[: -len(postfix)]
|
2017-09-18 21:29:48 +03:00
|
|
|
|
|
|
|
try:
|
|
|
|
var = int(var) * units
|
|
|
|
except ValueError:
|
2020-07-16 12:43:29 +03:00
|
|
|
warnings.warn(f"{var_name} is not int")
|
2017-09-18 21:29:48 +03:00
|
|
|
continue
|
|
|
|
|
|
|
|
try:
|
|
|
|
setter(var)
|
|
|
|
except ValueError as e:
|
2020-07-16 12:43:29 +03:00
|
|
|
warnings.warn(f"{var_name}: {e}")
|
2017-09-18 21:29:48 +03:00
|
|
|
|
2018-03-03 12:54:00 +03:00
|
|
|
|
2017-09-18 21:29:48 +03:00
|
|
|
_apply_env_variables()
|
2017-09-19 03:10:57 +03:00
|
|
|
atexit.register(core.clear_cache)
|
2019-04-01 12:03:02 +03:00
|
|
|
|
|
|
|
|
|
|
|
class Exif(MutableMapping):
|
2021-04-19 12:46:49 +03:00
|
|
|
endian = None
|
2022-03-01 01:23:12 +03:00
|
|
|
bigtiff = False
|
2019-04-01 12:03:02 +03:00
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self._data = {}
|
2022-11-26 07:44:03 +03:00
|
|
|
self._hidden_data = {}
|
2019-04-01 12:03:02 +03:00
|
|
|
self._ifds = {}
|
2019-08-22 23:13:20 +03:00
|
|
|
self._info = None
|
|
|
|
self._loaded_exif = None
|
2019-08-18 16:03:43 +03:00
|
|
|
|
|
|
|
def _fixup(self, value):
|
|
|
|
try:
|
2020-05-22 14:12:09 +03:00
|
|
|
if len(value) == 1 and isinstance(value, tuple):
|
2019-08-18 16:03:43 +03:00
|
|
|
return value[0]
|
|
|
|
except Exception:
|
|
|
|
pass
|
|
|
|
return value
|
2019-04-01 12:03:02 +03:00
|
|
|
|
|
|
|
def _fixup_dict(self, src_dict):
|
2020-10-08 16:07:57 +03:00
|
|
|
# Helper function
|
2019-04-01 12:03:02 +03:00
|
|
|
# returns a dict with any single item tuples/lists as individual values
|
2019-08-18 16:03:43 +03:00
|
|
|
return {k: self._fixup(v) for k, v in src_dict.items()}
|
2019-04-01 12:03:02 +03:00
|
|
|
|
2020-10-05 12:35:45 +03:00
|
|
|
def _get_ifd_dict(self, offset):
|
2019-04-01 12:03:02 +03:00
|
|
|
try:
|
|
|
|
# an offset pointer to the location of the nested embedded IFD.
|
|
|
|
# It should be a long, but may be corrupted.
|
2020-10-05 12:35:45 +03:00
|
|
|
self.fp.seek(offset)
|
2019-04-01 12:03:02 +03:00
|
|
|
except (KeyError, TypeError):
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
from . import TiffImagePlugin
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2020-05-22 14:12:09 +03:00
|
|
|
info = TiffImagePlugin.ImageFileDirectory_v2(self.head)
|
2019-04-01 12:03:02 +03:00
|
|
|
info.load(self.fp)
|
|
|
|
return self._fixup_dict(info)
|
|
|
|
|
2021-04-19 12:46:49 +03:00
|
|
|
def _get_head(self):
|
2022-03-01 01:23:12 +03:00
|
|
|
version = b"\x2B" if self.bigtiff else b"\x2A"
|
2021-04-19 12:46:49 +03:00
|
|
|
if self.endian == "<":
|
2022-03-01 01:23:12 +03:00
|
|
|
head = b"II" + version + b"\x00" + o32le(8)
|
2021-04-19 12:46:49 +03:00
|
|
|
else:
|
2022-03-01 01:23:12 +03:00
|
|
|
head = b"MM\x00" + version + o32be(8)
|
|
|
|
if self.bigtiff:
|
|
|
|
head += o32le(8) if self.endian == "<" else o32be(8)
|
|
|
|
head += b"\x00\x00\x00\x00"
|
|
|
|
return head
|
2021-04-19 12:46:49 +03:00
|
|
|
|
2019-04-01 12:03:02 +03:00
|
|
|
def load(self, data):
|
|
|
|
# Extract EXIF information. This is highly experimental,
|
|
|
|
# and is likely to be replaced with something better in a future
|
|
|
|
# version.
|
|
|
|
|
|
|
|
# The EXIF record consists of a TIFF file embedded in a JPEG
|
|
|
|
# application marker (!).
|
2019-08-22 23:13:20 +03:00
|
|
|
if data == self._loaded_exif:
|
|
|
|
return
|
|
|
|
self._loaded_exif = data
|
|
|
|
self._data.clear()
|
2022-11-26 07:44:03 +03:00
|
|
|
self._hidden_data.clear()
|
2019-08-22 23:13:20 +03:00
|
|
|
self._ifds.clear()
|
2022-03-12 00:23:40 +03:00
|
|
|
if data and data.startswith(b"Exif\x00\x00"):
|
|
|
|
data = data[6:]
|
2019-08-22 23:13:20 +03:00
|
|
|
if not data:
|
2021-04-19 12:46:49 +03:00
|
|
|
self._info = None
|
2019-08-22 23:13:20 +03:00
|
|
|
return
|
|
|
|
|
2020-06-07 13:01:04 +03:00
|
|
|
self.fp = io.BytesIO(data)
|
2019-04-01 12:03:02 +03:00
|
|
|
self.head = self.fp.read(8)
|
|
|
|
# process dictionary
|
|
|
|
from . import TiffImagePlugin
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2020-05-22 14:12:09 +03:00
|
|
|
self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head)
|
2019-08-22 23:13:20 +03:00
|
|
|
self.endian = self._info._endian
|
|
|
|
self.fp.seek(self._info.next)
|
|
|
|
self._info.load(self.fp)
|
2019-04-01 12:03:02 +03:00
|
|
|
|
2021-04-19 12:46:49 +03:00
|
|
|
def load_from_fp(self, fp, offset=None):
|
|
|
|
self._loaded_exif = None
|
|
|
|
self._data.clear()
|
2022-11-26 07:44:03 +03:00
|
|
|
self._hidden_data.clear()
|
2021-04-19 12:46:49 +03:00
|
|
|
self._ifds.clear()
|
|
|
|
|
|
|
|
# process dictionary
|
|
|
|
from . import TiffImagePlugin
|
|
|
|
|
|
|
|
self.fp = fp
|
|
|
|
if offset is not None:
|
|
|
|
self.head = self._get_head()
|
|
|
|
else:
|
|
|
|
self.head = self.fp.read(8)
|
|
|
|
self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head)
|
|
|
|
if self.endian is None:
|
|
|
|
self.endian = self._info._endian
|
|
|
|
if offset is None:
|
|
|
|
offset = self._info.next
|
|
|
|
self.fp.seek(offset)
|
|
|
|
self._info.load(self.fp)
|
|
|
|
|
2020-10-05 12:35:45 +03:00
|
|
|
def _get_merged_dict(self):
|
|
|
|
merged_dict = dict(self)
|
|
|
|
|
2019-04-01 12:03:02 +03:00
|
|
|
# get EXIF extension
|
2022-11-28 00:39:56 +03:00
|
|
|
if ExifTags.IFD.Exif in self:
|
|
|
|
ifd = self._get_ifd_dict(self[ExifTags.IFD.Exif])
|
2020-10-05 12:35:45 +03:00
|
|
|
if ifd:
|
|
|
|
merged_dict.update(ifd)
|
|
|
|
|
2021-03-15 04:32:42 +03:00
|
|
|
# GPS
|
2022-11-28 00:39:56 +03:00
|
|
|
if ExifTags.IFD.GPSInfo in self:
|
|
|
|
merged_dict[ExifTags.IFD.GPSInfo] = self._get_ifd_dict(
|
|
|
|
self[ExifTags.IFD.GPSInfo]
|
|
|
|
)
|
2021-03-15 04:32:42 +03:00
|
|
|
|
2020-10-05 12:35:45 +03:00
|
|
|
return merged_dict
|
2019-04-01 12:03:02 +03:00
|
|
|
|
2020-05-01 12:41:51 +03:00
|
|
|
def tobytes(self, offset=8):
|
2019-04-01 12:03:02 +03:00
|
|
|
from . import TiffImagePlugin
|
2019-03-21 16:28:20 +03:00
|
|
|
|
2021-04-19 12:46:49 +03:00
|
|
|
head = self._get_head()
|
2019-04-01 12:03:02 +03:00
|
|
|
ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)
|
2019-08-18 16:03:43 +03:00
|
|
|
for tag, value in self.items():
|
2022-11-28 00:39:56 +03:00
|
|
|
if tag in [
|
|
|
|
ExifTags.IFD.Exif,
|
|
|
|
ExifTags.IFD.GPSInfo,
|
|
|
|
] and not isinstance(value, dict):
|
2020-10-05 12:16:48 +03:00
|
|
|
value = self.get_ifd(tag)
|
2021-02-21 23:47:59 +03:00
|
|
|
if (
|
2022-11-28 00:39:56 +03:00
|
|
|
tag == ExifTags.IFD.Exif
|
|
|
|
and ExifTags.IFD.Interop in value
|
|
|
|
and not isinstance(value[ExifTags.IFD.Interop], dict)
|
2021-02-21 23:47:59 +03:00
|
|
|
):
|
|
|
|
value = value.copy()
|
2022-11-28 00:39:56 +03:00
|
|
|
value[ExifTags.IFD.Interop] = self.get_ifd(ExifTags.IFD.Interop)
|
2019-04-01 12:03:02 +03:00
|
|
|
ifd[tag] = value
|
2019-03-21 16:28:20 +03:00
|
|
|
return b"Exif\x00\x00" + head + ifd.tobytes(offset)
|
2019-04-01 12:03:02 +03:00
|
|
|
|
|
|
|
def get_ifd(self, tag):
|
2020-10-05 12:35:45 +03:00
|
|
|
if tag not in self._ifds:
|
2022-12-05 01:09:00 +03:00
|
|
|
if tag == ExifTags.IFD.IFD1:
|
2022-12-29 13:52:09 +03:00
|
|
|
if self._info is not None and self._info.next != 0:
|
2022-12-05 01:09:00 +03:00
|
|
|
self._ifds[tag] = self._get_ifd_dict(self._info.next)
|
|
|
|
elif tag in [ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo]:
|
2022-11-26 07:44:03 +03:00
|
|
|
offset = self._hidden_data.get(tag, self.get(tag))
|
|
|
|
if offset is not None:
|
|
|
|
self._ifds[tag] = self._get_ifd_dict(offset)
|
2022-11-28 00:39:56 +03:00
|
|
|
elif tag in [ExifTags.IFD.Interop, ExifTags.IFD.Makernote]:
|
|
|
|
if ExifTags.IFD.Exif not in self._ifds:
|
|
|
|
self.get_ifd(ExifTags.IFD.Exif)
|
|
|
|
tag_data = self._ifds[ExifTags.IFD.Exif][tag]
|
|
|
|
if tag == ExifTags.IFD.Makernote:
|
2020-10-05 12:35:45 +03:00
|
|
|
from .TiffImagePlugin import ImageFileDirectory_v2
|
|
|
|
|
2020-10-07 10:35:16 +03:00
|
|
|
if tag_data[:8] == b"FUJIFILM":
|
2020-10-05 12:35:45 +03:00
|
|
|
ifd_offset = i32le(tag_data, 8)
|
|
|
|
ifd_data = tag_data[ifd_offset:]
|
|
|
|
|
|
|
|
makernote = {}
|
|
|
|
for i in range(0, struct.unpack("<H", ifd_data[:2])[0]):
|
|
|
|
ifd_tag, typ, count, data = struct.unpack(
|
|
|
|
"<HHL4s", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]
|
2019-03-21 16:28:20 +03:00
|
|
|
)
|
2020-10-05 12:35:45 +03:00
|
|
|
try:
|
|
|
|
(
|
|
|
|
unit_size,
|
|
|
|
handler,
|
|
|
|
) = ImageFileDirectory_v2._load_dispatch[typ]
|
|
|
|
except KeyError:
|
|
|
|
continue
|
|
|
|
size = count * unit_size
|
|
|
|
if size > 4:
|
|
|
|
(offset,) = struct.unpack("<L", data)
|
|
|
|
data = ifd_data[offset - 12 : offset + size - 12]
|
|
|
|
else:
|
|
|
|
data = data[:size]
|
|
|
|
|
|
|
|
if len(data) != size:
|
|
|
|
warnings.warn(
|
|
|
|
"Possibly corrupt EXIF MakerNote data. "
|
|
|
|
f"Expecting to read {size} bytes but only got "
|
|
|
|
f"{len(data)}. Skipping tag {ifd_tag}"
|
|
|
|
)
|
|
|
|
continue
|
|
|
|
|
|
|
|
if not data:
|
|
|
|
continue
|
|
|
|
|
|
|
|
makernote[ifd_tag] = handler(
|
|
|
|
ImageFileDirectory_v2(), data, False
|
2019-03-21 16:28:20 +03:00
|
|
|
)
|
2020-10-05 12:35:45 +03:00
|
|
|
self._ifds[tag] = dict(self._fixup_dict(makernote))
|
|
|
|
elif self.get(0x010F) == "Nintendo":
|
|
|
|
makernote = {}
|
|
|
|
for i in range(0, struct.unpack(">H", tag_data[:2])[0]):
|
|
|
|
ifd_tag, typ, count, data = struct.unpack(
|
|
|
|
">HHL4s", tag_data[i * 12 + 2 : (i + 1) * 12 + 2]
|
|
|
|
)
|
|
|
|
if ifd_tag == 0x1101:
|
|
|
|
# CameraInfo
|
|
|
|
(offset,) = struct.unpack(">L", data)
|
|
|
|
self.fp.seek(offset)
|
|
|
|
|
|
|
|
camerainfo = {"ModelID": self.fp.read(4)}
|
|
|
|
|
|
|
|
self.fp.read(4)
|
|
|
|
# Seconds since 2000
|
|
|
|
camerainfo["TimeStamp"] = i32le(self.fp.read(12))
|
|
|
|
|
|
|
|
self.fp.read(4)
|
|
|
|
camerainfo["InternalSerialNumber"] = self.fp.read(4)
|
|
|
|
|
|
|
|
self.fp.read(12)
|
|
|
|
parallax = self.fp.read(4)
|
|
|
|
handler = ImageFileDirectory_v2._load_dispatch[
|
|
|
|
TiffTags.FLOAT
|
|
|
|
][1]
|
|
|
|
camerainfo["Parallax"] = handler(
|
|
|
|
ImageFileDirectory_v2(), parallax, False
|
|
|
|
)
|
|
|
|
|
|
|
|
self.fp.read(4)
|
|
|
|
camerainfo["Category"] = self.fp.read(2)
|
|
|
|
|
|
|
|
makernote = {0x1101: dict(self._fixup_dict(camerainfo))}
|
|
|
|
self._ifds[tag] = makernote
|
|
|
|
else:
|
2022-12-05 01:09:00 +03:00
|
|
|
# Interop
|
2020-10-05 12:35:45 +03:00
|
|
|
self._ifds[tag] = self._get_ifd_dict(tag_data)
|
2022-11-26 07:44:03 +03:00
|
|
|
ifd = self._ifds.get(tag, {})
|
2022-12-22 01:03:11 +03:00
|
|
|
if tag == ExifTags.IFD.Exif and self._hidden_data:
|
|
|
|
ifd = {
|
|
|
|
k: v
|
|
|
|
for (k, v) in ifd.items()
|
|
|
|
if k not in (ExifTags.IFD.Interop, ExifTags.IFD.Makernote)
|
|
|
|
}
|
2022-11-26 07:44:03 +03:00
|
|
|
return ifd
|
|
|
|
|
|
|
|
def hide_offsets(self):
|
2022-12-22 01:03:11 +03:00
|
|
|
for tag in (ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo):
|
2022-11-26 07:44:03 +03:00
|
|
|
if tag in self:
|
|
|
|
self._hidden_data[tag] = self[tag]
|
|
|
|
del self[tag]
|
2019-04-01 12:03:02 +03:00
|
|
|
|
|
|
|
def __str__(self):
|
2019-08-22 23:13:20 +03:00
|
|
|
if self._info is not None:
|
2019-08-18 16:03:43 +03:00
|
|
|
# Load all keys into self._data
|
2023-01-07 21:36:17 +03:00
|
|
|
for tag in self._info:
|
2019-08-18 16:03:43 +03:00
|
|
|
self[tag]
|
|
|
|
|
2019-04-01 12:03:02 +03:00
|
|
|
return str(self._data)
|
|
|
|
|
|
|
|
def __len__(self):
|
2019-08-18 16:03:43 +03:00
|
|
|
keys = set(self._data)
|
2019-08-22 23:13:20 +03:00
|
|
|
if self._info is not None:
|
|
|
|
keys.update(self._info)
|
2019-08-18 16:03:43 +03:00
|
|
|
return len(keys)
|
2019-04-01 12:03:02 +03:00
|
|
|
|
|
|
|
def __getitem__(self, tag):
|
2019-08-22 23:13:20 +03:00
|
|
|
if self._info is not None and tag not in self._data and tag in self._info:
|
|
|
|
self._data[tag] = self._fixup(self._info[tag])
|
|
|
|
del self._info[tag]
|
2019-04-01 12:03:02 +03:00
|
|
|
return self._data[tag]
|
|
|
|
|
|
|
|
def __contains__(self, tag):
|
2019-08-22 23:13:20 +03:00
|
|
|
return tag in self._data or (self._info is not None and tag in self._info)
|
2019-04-01 12:03:02 +03:00
|
|
|
|
|
|
|
def __setitem__(self, tag, value):
|
2019-09-07 11:31:23 +03:00
|
|
|
if self._info is not None and tag in self._info:
|
|
|
|
del self._info[tag]
|
2019-04-01 12:03:02 +03:00
|
|
|
self._data[tag] = value
|
|
|
|
|
|
|
|
def __delitem__(self, tag):
|
2019-09-07 11:31:23 +03:00
|
|
|
if self._info is not None and tag in self._info:
|
|
|
|
del self._info[tag]
|
2020-10-03 13:58:12 +03:00
|
|
|
else:
|
|
|
|
del self._data[tag]
|
2019-04-01 12:03:02 +03:00
|
|
|
|
|
|
|
def __iter__(self):
|
2019-08-18 16:03:43 +03:00
|
|
|
keys = set(self._data)
|
2019-08-22 23:13:20 +03:00
|
|
|
if self._info is not None:
|
|
|
|
keys.update(self._info)
|
2019-08-18 16:03:43 +03:00
|
|
|
return iter(keys)
|