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.
|
|
|
|
#
|
|
|
|
|
2012-10-16 06:27:35 +04:00
|
|
|
from __future__ import print_function
|
|
|
|
|
2013-04-15 21:57:37 +04:00
|
|
|
from PIL import VERSION, PILLOW_VERSION, _plugins
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2015-02-06 21:58:07 +03:00
|
|
|
import logging
|
2013-07-23 21:17:15 +04:00
|
|
|
import warnings
|
2016-06-02 11:36:41 +03:00
|
|
|
import math
|
2010-07-31 06:52:47 +04: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
|
|
|
|
|
2014-08-28 15:44:19 +04:00
|
|
|
|
2015-05-26 17:07:21 +03:00
|
|
|
class _imaging_not_installed(object):
|
2010-07-31 06:52:47 +04:00
|
|
|
# module placeholder
|
|
|
|
def __getattr__(self, id):
|
|
|
|
raise ImportError("The _imaging C module is not installed")
|
|
|
|
|
2014-05-14 19:04:18 +04:00
|
|
|
|
2014-05-27 13:10:10 +04:00
|
|
|
# Limit to around a quarter gigabyte for a 24 bit (3 bpp) image
|
|
|
|
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:
|
|
|
|
# give Tk a chance to set up the environment, in case we're
|
|
|
|
# using an _imaging module linked against libtcl/libtk (use
|
|
|
|
# __import__ to hide this from naive packagers; we don't really
|
|
|
|
# depend on Tk unless ImageTk is used, and that module already
|
|
|
|
# imports Tkinter)
|
|
|
|
__import__("FixTk")
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
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.
|
2013-04-09 07:55:06 +04:00
|
|
|
from PIL import _imaging as core
|
2013-04-09 08:43:15 +04:00
|
|
|
if PILLOW_VERSION != getattr(core, 'PILLOW_VERSION', None):
|
2014-04-22 10:23:34 +04:00
|
|
|
raise ImportError("The _imaging extension was built for another "
|
|
|
|
" version of Pillow or PIL")
|
2013-06-30 23:21:37 +04:00
|
|
|
|
2012-10-11 07:52:53 +04:00
|
|
|
except ImportError as v:
|
2010-07-31 06:52:47 +04:00
|
|
|
core = _imaging_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(
|
|
|
|
"The _imaging extension was built for another version "
|
2013-07-23 21:17:15 +04:00
|
|
|
"of Python.",
|
2010-07-31 06:52:47 +04:00
|
|
|
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)
|
2016-03-08 12:04:11 +03:00
|
|
|
elif "Symbol not found: _PyUnicodeUCS2_" in str(v):
|
|
|
|
# should match _PyUnicodeUCS2_FromString and
|
|
|
|
# _PyUnicodeUCS2_AsLatin1String
|
2013-07-23 12:44:27 +04:00
|
|
|
warnings.warn(
|
2013-07-23 21:17:15 +04:00
|
|
|
"The _imaging extension was built for Python with UCS2 support; "
|
2016-03-08 12:04:11 +03:00
|
|
|
"recompile Pillow or build Python --without-wide-unicode. ",
|
2013-07-23 12:44:27 +04:00
|
|
|
RuntimeWarning
|
|
|
|
)
|
2016-03-08 12:04:11 +03:00
|
|
|
elif "Symbol not found: _PyUnicodeUCS4_" in str(v):
|
|
|
|
# should match _PyUnicodeUCS4_FromString and
|
|
|
|
# _PyUnicodeUCS4_AsLatin1String
|
2013-07-23 12:44:27 +04:00
|
|
|
warnings.warn(
|
2013-07-23 21:17:15 +04:00
|
|
|
"The _imaging extension was built for Python with UCS4 support; "
|
2016-03-08 12:04:11 +03:00
|
|
|
"recompile Pillow or build Python --with-wide-unicode. ",
|
2013-07-23 12:44:27 +04:00
|
|
|
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
|
|
|
|
2012-10-17 06:56:20 +04:00
|
|
|
try:
|
|
|
|
import builtins
|
|
|
|
except ImportError:
|
|
|
|
import __builtin__
|
|
|
|
builtins = __builtin__
|
|
|
|
|
2015-06-19 08:55:35 +03:00
|
|
|
from PIL import ImageMode
|
2014-05-10 13:34:36 +04:00
|
|
|
from PIL._binary import i8
|
|
|
|
from PIL._util import isPath
|
|
|
|
from PIL._util import isStringType
|
|
|
|
from PIL._util import deferred_error
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
import os
|
|
|
|
import sys
|
2015-03-26 15:25:26 +03:00
|
|
|
import io
|
2015-04-02 08:29:18 +03:00
|
|
|
import struct
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
# type stuff
|
2012-10-16 00:47:53 +04:00
|
|
|
import collections
|
2012-10-16 06:13:49 +04:00
|
|
|
import numbers
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-01-07 10:08:14 +04:00
|
|
|
# works everywhere, win for pypy, not cpython
|
2014-05-14 19:04:18 +04:00
|
|
|
USE_CFFI_ACCESS = hasattr(sys, 'pypy_version_info')
|
2014-01-05 22:41:25 +04:00
|
|
|
try:
|
|
|
|
import cffi
|
2014-04-22 10:23:34 +04:00
|
|
|
HAS_CFFI = True
|
2015-05-27 02:15:45 +03:00
|
|
|
except ImportError:
|
2014-04-22 10:23:34 +04:00
|
|
|
HAS_CFFI = False
|
|
|
|
|
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")
|
|
|
|
|
|
|
|
#
|
|
|
|
# Constants (also defined in _imagingmodule.c!)
|
|
|
|
|
|
|
|
NONE = 0
|
|
|
|
|
|
|
|
# transpose
|
|
|
|
FLIP_LEFT_RIGHT = 0
|
|
|
|
FLIP_TOP_BOTTOM = 1
|
|
|
|
ROTATE_90 = 2
|
|
|
|
ROTATE_180 = 3
|
|
|
|
ROTATE_270 = 4
|
2014-11-07 03:37:12 +03:00
|
|
|
TRANSPOSE = 5
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
# transforms
|
|
|
|
AFFINE = 0
|
|
|
|
EXTENT = 1
|
|
|
|
PERSPECTIVE = 2
|
|
|
|
QUAD = 3
|
|
|
|
MESH = 4
|
|
|
|
|
|
|
|
# resampling filters
|
2014-11-28 01:41:56 +03:00
|
|
|
NEAREST = NONE = 0
|
2016-06-16 20:04:20 +03:00
|
|
|
BOX = 4
|
2014-11-28 01:41:56 +03:00
|
|
|
BILINEAR = LINEAR = 2
|
2016-06-16 20:04:20 +03:00
|
|
|
HAMMING = 5
|
2014-11-28 01:41:56 +03:00
|
|
|
BICUBIC = CUBIC = 3
|
2016-06-16 20:04:20 +03:00
|
|
|
LANCZOS = ANTIALIAS = 1
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
# dithers
|
2016-06-16 20:04:20 +03:00
|
|
|
NEAREST = NONE = 0
|
2014-04-22 10:23:34 +04:00
|
|
|
ORDERED = 1 # Not yet implemented
|
|
|
|
RASTERIZE = 2 # Not yet implemented
|
|
|
|
FLOYDSTEINBERG = 3 # default
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
# palettes/quantizers
|
|
|
|
WEB = 0
|
|
|
|
ADAPTIVE = 1
|
|
|
|
|
2013-03-11 23:33:04 +04:00
|
|
|
MEDIANCUT = 0
|
|
|
|
MAXCOVERAGE = 1
|
|
|
|
FASTOCTREE = 2
|
2016-05-05 22:36:45 +03:00
|
|
|
LIBIMAGEQUANT = 3
|
2013-03-11 23:33:04 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# categories
|
|
|
|
NORMAL = 0
|
|
|
|
SEQUENCE = 1
|
|
|
|
CONTAINER = 2
|
|
|
|
|
2013-03-11 23:33:04 +04:00
|
|
|
if hasattr(core, 'DEFAULT_STRATEGY'):
|
|
|
|
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 = {}
|
|
|
|
|
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Modes supported by this version
|
|
|
|
|
|
|
|
_MODEINFO = {
|
|
|
|
# NOTE: this table will be removed in future versions. use
|
|
|
|
# getmode* functions or ImageMode descriptors instead.
|
|
|
|
|
|
|
|
# official modes
|
|
|
|
"1": ("L", "L", ("1",)),
|
|
|
|
"L": ("L", "L", ("L",)),
|
|
|
|
"I": ("L", "I", ("I",)),
|
|
|
|
"F": ("L", "F", ("F",)),
|
|
|
|
"P": ("RGB", "L", ("P",)),
|
|
|
|
"RGB": ("RGB", "L", ("R", "G", "B")),
|
|
|
|
"RGBX": ("RGB", "L", ("R", "G", "B", "X")),
|
|
|
|
"RGBA": ("RGB", "L", ("R", "G", "B", "A")),
|
|
|
|
"CMYK": ("RGB", "L", ("C", "M", "Y", "K")),
|
|
|
|
"YCbCr": ("RGB", "L", ("Y", "Cb", "Cr")),
|
2013-10-11 10:27:34 +04:00
|
|
|
"LAB": ("RGB", "L", ("L", "A", "B")),
|
2014-07-22 09:31:32 +04:00
|
|
|
"HSV": ("RGB", "L", ("H", "S", "V")),
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
# Experimental modes include I;16, I;16L, I;16B, RGBa, BGR;15, and
|
|
|
|
# BGR;24. Use these modes only if you know exactly what you're
|
|
|
|
# doing...
|
|
|
|
|
|
|
|
}
|
|
|
|
|
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 sys.byteorder == 'little':
|
2010-07-31 06:52:47 +04:00
|
|
|
_ENDIAN = '<'
|
|
|
|
else:
|
|
|
|
_ENDIAN = '>'
|
|
|
|
|
|
|
|
_MODE_CONV = {
|
|
|
|
# official modes
|
2016-08-08 01:25:43 +03:00
|
|
|
"1": ('|b1', None), # Bits need to be extended to bytes
|
2010-07-31 06:52:47 +04:00
|
|
|
"L": ('|u1', None),
|
2016-04-28 17:29:56 +03:00
|
|
|
"LA": ('|u1', 2),
|
2010-07-31 06:52:47 +04:00
|
|
|
"I": (_ENDIAN + 'i4', None),
|
|
|
|
"F": (_ENDIAN + 'f4', None),
|
|
|
|
"P": ('|u1', None),
|
|
|
|
"RGB": ('|u1', 3),
|
|
|
|
"RGBX": ('|u1', 4),
|
|
|
|
"RGBA": ('|u1', 4),
|
|
|
|
"CMYK": ('|u1', 4),
|
2013-02-14 07:52:32 +04:00
|
|
|
"YCbCr": ('|u1', 3),
|
2014-04-22 10:23:34 +04:00
|
|
|
"LAB": ('|u1', 3), # UNDONE - unsigned |u1i1i1
|
2015-12-07 20:40:42 +03:00
|
|
|
"HSV": ('|u1', 3),
|
2014-04-22 10:23:34 +04:00
|
|
|
# I;16 == I;16L, and I;32 == I;32L
|
2013-10-19 07:28:31 +04:00
|
|
|
"I;16": ('<u2', None),
|
2013-09-30 06:30:43 +04:00
|
|
|
"I;16B": ('>u2', None),
|
|
|
|
"I;16L": ('<u2', None),
|
2013-10-19 07:28:31 +04:00
|
|
|
"I;16S": ('<i2', None),
|
2013-09-30 06:30:43 +04:00
|
|
|
"I;16BS": ('>i2', None),
|
|
|
|
"I;16LS": ('<i2', None),
|
2013-10-19 07:28:31 +04:00
|
|
|
"I;32": ('<u4', None),
|
2013-09-30 06:30:43 +04:00
|
|
|
"I;32B": ('>u4', None),
|
|
|
|
"I;32L": ('<u4', None),
|
2013-10-19 07:28:31 +04:00
|
|
|
"I;32S": ('<i4', None),
|
2013-09-30 06:30:43 +04:00
|
|
|
"I;32BS": ('>i4', None),
|
|
|
|
"I;32LS": ('<i4', None),
|
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):
|
|
|
|
shape = im.size[1], im.size[0]
|
|
|
|
typ, extra = _MODE_CONV[im.mode]
|
|
|
|
if extra is None:
|
|
|
|
return shape, typ
|
|
|
|
else:
|
|
|
|
return shape+(extra,), typ
|
|
|
|
|
|
|
|
|
2012-10-17 07:39:56 +04:00
|
|
|
MODES = sorted(_MODEINFO.keys())
|
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)
|
|
|
|
|
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Helpers
|
|
|
|
|
|
|
|
_initialized = 0
|
|
|
|
|
|
|
|
|
|
|
|
def preinit():
|
2013-07-09 23:12:28 +04:00
|
|
|
"Explicitly load standard file format drivers."
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
global _initialized
|
|
|
|
if _initialized >= 1:
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
2013-03-07 20:20:28 +04:00
|
|
|
from PIL import BmpImagePlugin
|
2010-07-31 06:52:47 +04:00
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
try:
|
2013-03-07 20:20:28 +04:00
|
|
|
from PIL import GifImagePlugin
|
2010-07-31 06:52:47 +04:00
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
try:
|
2013-03-07 20:20:28 +04:00
|
|
|
from PIL import JpegImagePlugin
|
2010-07-31 06:52:47 +04:00
|
|
|
except ImportError:
|
|
|
|
pass
|
2014-07-17 20:30:45 +04:00
|
|
|
try:
|
2013-03-07 20:20:28 +04:00
|
|
|
from PIL import PpmImagePlugin
|
2010-07-31 06:52:47 +04:00
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
try:
|
2013-03-07 20:20:28 +04:00
|
|
|
from PIL import PngImagePlugin
|
2010-07-31 06:52:47 +04:00
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
# try:
|
|
|
|
# import TiffImagePlugin
|
|
|
|
# except ImportError:
|
|
|
|
# pass
|
|
|
|
|
|
|
|
_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)
|
2014-04-22 10:23:34 +04:00
|
|
|
__import__("PIL.%s" % 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
|
|
|
|
|
|
|
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,)
|
|
|
|
|
|
|
|
try:
|
|
|
|
# get decoder
|
|
|
|
decoder = getattr(core, decoder_name + "_decoder")
|
2012-10-21 01:05:13 +04:00
|
|
|
# print(decoder, mode, args + extra)
|
|
|
|
return decoder(mode, *args + extra)
|
2010-07-31 06:52:47 +04:00
|
|
|
except AttributeError:
|
|
|
|
raise IOError("decoder %s not available" % decoder_name)
|
|
|
|
|
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,)
|
|
|
|
|
|
|
|
try:
|
|
|
|
# get encoder
|
|
|
|
encoder = getattr(core, encoder_name + "_encoder")
|
2012-10-21 01:05:13 +04:00
|
|
|
# print(encoder, mode, args + extra)
|
|
|
|
return encoder(mode, *args + extra)
|
2010-07-31 06:52:47 +04:00
|
|
|
except AttributeError:
|
|
|
|
raise IOError("encoder %s not available" % encoder_name)
|
|
|
|
|
|
|
|
|
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Simple expression analyzer
|
|
|
|
|
2012-10-19 16:54:55 +04:00
|
|
|
def coerce_e(value):
|
|
|
|
return value if isinstance(value, _E) else _E(value)
|
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2015-05-26 17:07:21 +03:00
|
|
|
class _E(object):
|
2012-10-19 16:54:55 +04:00
|
|
|
def __init__(self, data):
|
|
|
|
self.data = data
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2012-10-19 16:54:55 +04:00
|
|
|
def __add__(self, other):
|
|
|
|
return _E((self.data, "__add__", coerce_e(other).data))
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2012-10-19 16:54:55 +04:00
|
|
|
def __mul__(self, other):
|
|
|
|
return _E((self.data, "__mul__", coerce_e(other).data))
|
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):
|
|
|
|
stub = ["stub"]
|
|
|
|
data = expr(_E(stub)).data
|
|
|
|
try:
|
2014-04-22 10:23:34 +04:00
|
|
|
(a, b, c) = data # simplified syntax
|
2012-10-16 06:13:49 +04:00
|
|
|
if (a is stub and b == "__mul__" and isinstance(c, numbers.Number)):
|
2010-07-31 06:52:47 +04:00
|
|
|
return c, 0.0
|
2014-05-10 08:36:15 +04:00
|
|
|
if a is stub and b == "__add__" and isinstance(c, numbers.Number):
|
2010-07-31 06:52:47 +04:00
|
|
|
return 1.0, c
|
2014-04-22 10:23:34 +04:00
|
|
|
except TypeError:
|
|
|
|
pass
|
2010-07-31 06:52:47 +04:00
|
|
|
try:
|
2014-04-22 10:23:34 +04:00
|
|
|
((a, b, c), d, e) = data # full syntax
|
2012-10-16 06:13:49 +04:00
|
|
|
if (a is stub and b == "__mul__" and isinstance(c, numbers.Number) and
|
2014-04-22 10:23:34 +04:00
|
|
|
d == "__add__" and isinstance(e, numbers.Number)):
|
2010-07-31 06:52:47 +04:00
|
|
|
return c, e
|
2014-04-22 10:23:34 +04:00
|
|
|
except TypeError:
|
|
|
|
pass
|
2010-07-31 06:52:47 +04:00
|
|
|
raise ValueError("illegal expression")
|
|
|
|
|
|
|
|
|
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Implementation wrapper
|
|
|
|
|
2015-05-26 17:07:21 +03:00
|
|
|
class Image(object):
|
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
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
format = None
|
|
|
|
format_description = None
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
# FIXME: take "new" parameters / other image?
|
|
|
|
# FIXME: turn mode and size into delegating properties?
|
|
|
|
self.im = None
|
|
|
|
self.mode = ""
|
|
|
|
self.size = (0, 0)
|
|
|
|
self.palette = None
|
|
|
|
self.info = {}
|
|
|
|
self.category = NORMAL
|
|
|
|
self.readonly = 0
|
2014-01-05 22:41:25 +04:00
|
|
|
self.pyaccess = None
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2015-06-24 03:35:37 +03:00
|
|
|
@property
|
|
|
|
def width(self):
|
|
|
|
return self.size[0]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def height(self):
|
|
|
|
return self.size[1]
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def _new(self, im):
|
|
|
|
new = Image()
|
|
|
|
new.im = im
|
|
|
|
new.mode = im.mode
|
|
|
|
new.size = im.size
|
2015-05-14 02:57:56 +03:00
|
|
|
if self.palette:
|
|
|
|
new.palette = self.palette.copy()
|
2013-11-12 17:41:35 +04:00
|
|
|
if im.mode == "P" and not new.palette:
|
2013-03-07 20:20:28 +04:00
|
|
|
from PIL import ImagePalette
|
2010-07-31 06:52:47 +04: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
|
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
_makeself = _new # compatibility
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-04-18 08:53:49 +04: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):
|
|
|
|
self.close()
|
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.
|
|
|
|
|
|
|
|
This function is only required to close images that have not
|
|
|
|
had their file read and closed by the
|
|
|
|
:py:meth:`~PIL.Image.Image.load` method.
|
|
|
|
"""
|
2014-03-01 03:57:53 +04:00
|
|
|
try:
|
|
|
|
self.fp.close()
|
|
|
|
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
|
|
|
|
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.
|
|
|
|
self.im = deferred_error(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
|
|
|
|
|
|
|
|
def _dump(self, file=None, format=None):
|
2014-05-10 13:34:36 +04:00
|
|
|
import tempfile
|
2014-04-08 03:01:49 +04:00
|
|
|
suffix = ''
|
|
|
|
if format:
|
|
|
|
suffix = '.'+format
|
2010-07-31 06:52:47 +04:00
|
|
|
if not file:
|
2014-04-08 03:01:49 +04:00
|
|
|
f, file = tempfile.mkstemp(suffix)
|
2014-03-15 02:56:41 +04:00
|
|
|
os.close(f)
|
2014-05-14 19:04:18 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
self.load()
|
|
|
|
if not format or format == "PPM":
|
|
|
|
self.im.save_ppm(file)
|
|
|
|
else:
|
2014-04-08 02:59:33 +04:00
|
|
|
if not file.endswith(format):
|
2014-03-15 02:56:41 +04:00
|
|
|
file = file + "." + format
|
2010-07-31 06:52:47 +04:00
|
|
|
self.save(file, format)
|
|
|
|
return file
|
|
|
|
|
2014-04-26 20:43:53 +04:00
|
|
|
def __eq__(self, other):
|
2016-06-20 00:44:24 +03:00
|
|
|
return (self.__class__.__name__ == other.__class__.__name__ and
|
|
|
|
self.mode == other.mode and
|
|
|
|
self.size == other.size and
|
|
|
|
self.info == other.info and
|
|
|
|
self.category == other.category and
|
|
|
|
self.readonly == other.readonly and
|
|
|
|
self.getpalette() == other.getpalette() and
|
|
|
|
self.tobytes() == other.tobytes())
|
2014-04-26 20:43:53 +04:00
|
|
|
|
|
|
|
def __ne__(self, other):
|
|
|
|
eq = (self == other)
|
|
|
|
return not eq
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def __repr__(self):
|
|
|
|
return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % (
|
|
|
|
self.__class__.__module__, self.__class__.__name__,
|
|
|
|
self.mode, self.size[0], self.size[1],
|
|
|
|
id(self)
|
|
|
|
)
|
|
|
|
|
2015-01-28 21:02:04 +03:00
|
|
|
def _repr_png_(self):
|
2015-01-28 20:35:31 +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
|
|
|
|
"""
|
|
|
|
from io import BytesIO
|
|
|
|
b = BytesIO()
|
|
|
|
self.save(b, 'PNG')
|
|
|
|
return b.getvalue()
|
|
|
|
|
2016-08-08 01:25:43 +03:00
|
|
|
@property
|
|
|
|
def __array_interface__(self):
|
|
|
|
# numpy array interface support
|
|
|
|
new = {}
|
|
|
|
shape, typestr = _conv_type_shape(self)
|
|
|
|
new['shape'] = shape
|
|
|
|
new['typestr'] = typestr
|
|
|
|
new['version'] = 3
|
|
|
|
if self.mode == '1':
|
|
|
|
# Binary images need to be extended from bits to bytes
|
|
|
|
# See: https://github.com/python-pillow/Pillow/issues/350
|
|
|
|
new['data'] = self.tobytes('raw', 'L')
|
|
|
|
else:
|
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
|
|
|
new['data'] = self.tobytes()
|
2016-08-08 01:25:43 +03:00
|
|
|
return new
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-04-22 09:54:16 +04:00
|
|
|
def __getstate__(self):
|
2014-04-26 20:43:53 +04: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-25 10:01:16 +04:00
|
|
|
self.tile = []
|
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
|
|
|
|
self.size = size
|
2014-04-25 10:01:16 +04:00
|
|
|
self.im = core.new(mode, size)
|
2015-01-30 15:04:35 +03:00
|
|
|
if mode in ("L", "P") 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.
|
2013-07-09 23:12:28 +04:00
|
|
|
:param args: Extra arguments to the encoder.
|
2013-07-09 18:32:14 +04:00
|
|
|
:rtype: A bytes object.
|
|
|
|
"""
|
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()
|
|
|
|
|
|
|
|
# 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:
|
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
|
|
|
raise RuntimeError("encoder error %d in tobytes" % s)
|
|
|
|
|
|
|
|
return b"".join(data)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2013-03-07 13:23:40 +04:00
|
|
|
def tostring(self, *args, **kw):
|
2016-04-27 11:12:57 +03:00
|
|
|
raise NotImplementedError("tostring() has been removed. " +
|
2015-09-19 14:36:19 +03:00
|
|
|
"Please call tobytes() instead.")
|
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":
|
|
|
|
raise ValueError("not a bitmap")
|
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")
|
2014-04-22 10:23:34 +04:00
|
|
|
return b"".join([
|
|
|
|
("#define %s_width %d\n" % (name, self.size[0])).encode('ascii'),
|
|
|
|
("#define %s_height %d\n" % (name, self.size[1])).encode('ascii'),
|
|
|
|
("static char %s_bits[] = {\n" % name).encode('ascii'), 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:
|
|
|
|
raise ValueError("not enough image data")
|
|
|
|
if s[1] != 0:
|
|
|
|
raise ValueError("cannot decode image data")
|
|
|
|
|
2013-03-07 13:23:40 +04:00
|
|
|
def fromstring(self, *args, **kw):
|
2016-04-27 11:12:57 +03:00
|
|
|
raise NotImplementedError("fromstring() has been removed. " +
|
2015-09-19 14:36:19 +03:00
|
|
|
"Please call frombytes() instead.")
|
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
|
|
|
|
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
|
2014-04-18 08:53:49 +04:00
|
|
|
accessed for the first time. This method will close the file
|
2014-05-14 19:04:18 +04:00
|
|
|
associated with the image.
|
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
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
if self.im and self.palette and self.palette.dirty:
|
|
|
|
# realize palette
|
2012-10-21 01:05:13 +04:00
|
|
|
self.im.putpalette(*self.palette.getdata())
|
2010-07-31 06:52:47 +04:00
|
|
|
self.palette.dirty = 0
|
|
|
|
self.palette.mode = "RGB"
|
|
|
|
self.palette.rawmode = None
|
2012-10-16 01:18:27 +04:00
|
|
|
if "transparency" in self.info:
|
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"
|
2013-03-11 23:33:04 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
if self.im:
|
2014-01-05 22:41:25 +04:00
|
|
|
if HAS_CFFI and USE_CFFI_ACCESS:
|
|
|
|
if self.pyaccess:
|
|
|
|
return self.pyaccess
|
|
|
|
from PIL import PyAccess
|
|
|
|
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
|
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
def convert(self, mode=None, matrix=None, dither=None,
|
2010-07-31 06:52:47 +04:00
|
|
|
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
|
2013-10-12 09:18:40 +04:00
|
|
|
"L", "RGB" and "CMYK." The **matrix** argument only supports "L"
|
|
|
|
and "RGB".
|
2013-07-09 18:32:14 +04:00
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
When translating a color image to black and white (mode "L"),
|
|
|
|
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
|
|
|
|
dither is NONE, all non-zero values are set to 255 (white). To
|
|
|
|
use other thresholds, use the :py:meth:`~PIL.Image.Image.point`
|
|
|
|
method.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
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".
|
2013-07-09 18:32:14 +04:00
|
|
|
Available methods are NONE or FLOYDSTEINBERG (default).
|
|
|
|
:param palette: Palette to use when converting from mode "RGB"
|
|
|
|
to "P". Available palettes are WEB or ADAPTIVE.
|
|
|
|
:param colors: Number of colors to use for the 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
|
|
|
|
|
|
|
if not mode:
|
|
|
|
# determine default mode
|
|
|
|
if self.mode == "P":
|
|
|
|
self.load()
|
|
|
|
if self.palette:
|
|
|
|
mode = self.palette.mode
|
|
|
|
else:
|
|
|
|
mode = "RGB"
|
|
|
|
else:
|
|
|
|
return self.copy()
|
|
|
|
|
|
|
|
self.load()
|
|
|
|
|
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"):
|
|
|
|
raise ValueError("illegal conversion")
|
2013-10-12 09:18:40 +04:00
|
|
|
im = self.im.convert_matrix(mode, matrix)
|
2010-07-31 06:52:47 +04:00
|
|
|
return self._new(im)
|
|
|
|
|
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
|
2014-04-22 10:23:34 +04:00
|
|
|
if "transparency" in self.info and \
|
|
|
|
self.info['transparency'] is not None:
|
2014-03-26 10:34:41 +04:00
|
|
|
if self.mode in ('L', 'RGB') and mode == 'RGBA':
|
|
|
|
# Use transparent conversion to promote from transparent
|
2014-05-14 19:04:18 +04:00
|
|
|
# color to an alpha channel.
|
2014-03-26 10:34:41 +04:00
|
|
|
return self._new(self.im.convert_transparent(
|
2014-04-22 10:23:34 +04:00
|
|
|
mode, self.info['transparency']))
|
2014-03-26 10:34:41 +04:00
|
|
|
elif self.mode in ('L', 'RGB', 'P') and mode in ('L', 'RGB', 'P'):
|
|
|
|
t = self.info['transparency']
|
|
|
|
if isinstance(t, bytes):
|
|
|
|
# Dragons. This can't be represented by a single color
|
2014-08-28 15:44:19 +04: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)))
|
2014-03-26 10:34:41 +04:00
|
|
|
if self.mode == 'P':
|
|
|
|
trns_im.putpalette(self.palette)
|
2016-01-14 19:58:13 +03:00
|
|
|
if type(t) == tuple:
|
|
|
|
try:
|
|
|
|
t = trns_im.palette.getcolor(t)
|
|
|
|
except:
|
2016-09-03 05:17:22 +03:00
|
|
|
raise ValueError("Couldn't allocate a palette " +
|
2016-01-14 19:58:13 +03:00
|
|
|
"color for transparency")
|
2014-04-22 10:23:34 +04:00
|
|
|
trns_im.putpixel((0, 0), t)
|
2014-03-26 10:34:41 +04:00
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
if mode in ('L', 'RGB'):
|
2014-03-26 10:34:41 +04:00
|
|
|
trns_im = trns_im.convert(mode)
|
|
|
|
else:
|
|
|
|
# can't just retrieve the palette number, got to do it
|
2014-05-14 19:04:18 +04:00
|
|
|
# after quantization.
|
2014-03-26 10:34:41 +04:00
|
|
|
trns_im = trns_im.convert('RGB')
|
2014-08-28 15:44:19 +04:00
|
|
|
trns = trns_im.getpixel((0, 0))
|
2014-05-14 19:04:18 +04:00
|
|
|
|
2014-05-20 01:12:43 +04:00
|
|
|
elif self.mode == 'P' and mode == 'RGBA':
|
2014-09-20 21:27:52 +04: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:
|
|
|
|
raise ValueError("Transparency for P mode should" +
|
|
|
|
" be bytes or int")
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
if mode == "P" and palette == ADAPTIVE:
|
|
|
|
im = self.im.quantize(colors)
|
2014-02-05 16:49:08 +04:00
|
|
|
new = self._new(im)
|
|
|
|
from PIL import ImagePalette
|
|
|
|
new.palette = ImagePalette.raw("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.
|
2014-03-26 10:34:41 +04:00
|
|
|
del(new.info['transparency'])
|
|
|
|
if trns is not None:
|
|
|
|
try:
|
|
|
|
new.info['transparency'] = new.palette.getcolor(trns)
|
|
|
|
except:
|
|
|
|
# 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.
|
2014-03-26 10:34:41 +04:00
|
|
|
del(new.info['transparency'])
|
2014-04-22 10:23:34 +04:00
|
|
|
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
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
# colorspace conversion
|
2010-07-31 06:52:47 +04:00
|
|
|
if dither is None:
|
|
|
|
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
|
|
|
|
im = self.im.convert(getmodebase(self.mode))
|
|
|
|
im = im.convert(mode, dither)
|
|
|
|
except KeyError:
|
|
|
|
raise ValueError("illegal conversion")
|
|
|
|
|
2014-03-26 10:34:41 +04:00
|
|
|
new_im = self._new(im)
|
|
|
|
if delete_trns:
|
2014-04-26 20:43:53 +04:00
|
|
|
# crash fail if we leave a bytes transparency in an rgb/l mode.
|
2014-04-07 19:36:36 +04:00
|
|
|
del(new_im.info['transparency'])
|
2014-03-26 10:34:41 +04:00
|
|
|
if trns is not None:
|
2014-03-26 11:01:10 +04:00
|
|
|
if new_im.mode == 'P':
|
|
|
|
try:
|
|
|
|
new_im.info['transparency'] = new_im.palette.getcolor(trns)
|
|
|
|
except:
|
|
|
|
del(new_im.info['transparency'])
|
2014-04-22 10:23:34 +04:00
|
|
|
warnings.warn("Couldn't allocate palette entry " +
|
|
|
|
"for transparency")
|
2014-03-26 11:01:10 +04:00
|
|
|
else:
|
|
|
|
new_im.info['transparency'] = trns
|
2014-03-26 10:34:41 +04:00
|
|
|
return new_im
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-03-26 08:35:20 +04:00
|
|
|
def quantize(self, colors=256, method=None, kmeans=0, palette=None):
|
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
|
|
|
|
:param method: 0 = median cut
|
|
|
|
1 = maximum coverage
|
|
|
|
2 = fast octree
|
2016-05-05 22:36:45 +03:00
|
|
|
3 = libimagequant
|
2014-11-20 01:26:07 +03:00
|
|
|
:param kmeans: Integer
|
|
|
|
:param palette: Quantize to the :py:class:`PIL.ImagingPalette` palette.
|
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:
|
|
|
|
method = 0
|
|
|
|
if self.mode == 'RGBA':
|
|
|
|
method = 2
|
|
|
|
|
2016-05-05 22:36:45 +03:00
|
|
|
if self.mode == 'RGBA' and method not in (2, 3):
|
2014-05-14 19:04:18 +04:00
|
|
|
# Caller specified an invalid mode.
|
2016-05-05 22:36:45 +03:00
|
|
|
raise ValueError(
|
|
|
|
'Fast Octree (method == 2) and libimagequant (method == 3) ' +
|
|
|
|
'are the only valid methods for quantizing RGBA images')
|
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":
|
|
|
|
raise ValueError("bad mode for palette image")
|
|
|
|
if self.mode != "RGB" and self.mode != "L":
|
|
|
|
raise ValueError(
|
|
|
|
"only RGB or L mode images can be quantized to a palette"
|
|
|
|
)
|
|
|
|
im = self.im.convert("P", 1, palette.im)
|
|
|
|
return self._makeself(im)
|
|
|
|
|
2016-06-02 10:06:49 +03:00
|
|
|
return self._new(self.im.quantize(colors, method, kmeans))
|
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
|
|
|
|
coordinate.
|
|
|
|
|
2016-09-29 23:28:24 +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
|
|
|
|
|
|
|
self.load()
|
|
|
|
if box is None:
|
|
|
|
return self.copy()
|
|
|
|
|
2016-09-29 23:28:24 +03:00
|
|
|
x0, y0, x1, y1 = map(int, map(round, box))
|
|
|
|
|
|
|
|
if x1 < x0:
|
|
|
|
x1 = x0
|
|
|
|
if y1 < y0:
|
|
|
|
y1 = y0
|
|
|
|
|
|
|
|
return self._new(self.im.crop(( x0, y0, x1, y1)))
|
|
|
|
|
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
|
2013-10-12 09:18:40 +04:00
|
|
|
size. For example, you can use this method to convert a color
|
2013-07-09 18:32:14 +04:00
|
|
|
JPEG to greyscale while loading it, or to extract a 128x192
|
|
|
|
version from a PCD file.
|
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
Note that this method modifies the :py:class:`~PIL.Image.Image` object
|
|
|
|
in place. If the image has already been loaded, this method has no
|
|
|
|
effect.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
|
|
|
:param mode: The requested mode.
|
|
|
|
:param size: The requested size.
|
|
|
|
"""
|
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.
|
2013-10-12 09:18:40 +04:00
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object. """
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.load()
|
|
|
|
|
2012-10-16 00:47:53 +04:00
|
|
|
if isinstance(filter, collections.Callable):
|
2010-07-31 06:52:47 +04:00
|
|
|
filter = filter()
|
|
|
|
if not hasattr(filter, "filter"):
|
2014-04-22 10:23:34 +04:00
|
|
|
raise TypeError("filter argument should be ImageFilter.Filter " +
|
|
|
|
"instance or class")
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
if self.im.bands == 1:
|
|
|
|
return self._new(filter.filter(self.im))
|
|
|
|
# fix to handle multiband images since _imaging doesn't
|
|
|
|
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.
|
|
|
|
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
|
|
|
|
left, upper, right, and lower pixel coordinate. If the image
|
|
|
|
is completely empty, this method returns None.
|
|
|
|
|
|
|
|
"""
|
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.
|
|
|
|
|
|
|
|
: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
|
|
|
|
printing), use **list(im.getdata())**.
|
|
|
|
|
|
|
|
:param band: What band to return. The default is to return
|
|
|
|
all bands. To return a single band, pass in the index
|
|
|
|
value (e.g. 0 to get the "R" band from an "RGB" image).
|
|
|
|
:returns: A sequence-like object.
|
|
|
|
"""
|
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
|
|
|
"""
|
|
|
|
Gets the the minimum and maximum pixel values for each band in
|
|
|
|
the image.
|
|
|
|
|
|
|
|
:returns: For a single-band image, a 2-tuple containing the
|
|
|
|
minimum and maximum pixel value. For a multi-band image,
|
|
|
|
a tuple containing one 2-tuple for each band.
|
|
|
|
"""
|
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()
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
def getpalette(self):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Returns the image palette as a list.
|
|
|
|
|
|
|
|
: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:
|
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 bytes is str:
|
|
|
|
return [i8(c) for c in self.im.getpalette()]
|
|
|
|
else:
|
|
|
|
return list(self.im.getpalette())
|
2010-07-31 06:52:47 +04:00
|
|
|
except ValueError:
|
2014-04-22 10:23:34 +04:00
|
|
|
return None # no palette
|
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.
|
|
|
|
|
|
|
|
:param xy: The coordinate, given as (x, y).
|
|
|
|
: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()
|
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 [i8(c) for c in x], [i8(c) for c in y]
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def histogram(self, mask=None, extrema=None):
|
2013-07-09 18:32:14 +04: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. If the image has more than one band, the histograms for
|
|
|
|
all bands are concatenated (for example, the histogram for an
|
|
|
|
"RGB" image contains 768 values).
|
|
|
|
|
|
|
|
A bilevel image (mode "1") is treated as a greyscale ("L") image
|
|
|
|
by this method.
|
|
|
|
|
|
|
|
If a mask is provided, the method returns a histogram for those
|
|
|
|
parts of the image where the mask image is non-zero. The mask
|
|
|
|
image must have the same size as the image, and be either a
|
|
|
|
bi-level image (mode "1") or a greyscale image ("L").
|
|
|
|
|
|
|
|
:param mask: An optional mask.
|
|
|
|
: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()
|
|
|
|
|
|
|
|
def offset(self, xoffset, yoffset=None):
|
2016-04-27 11:12:57 +03:00
|
|
|
raise NotImplementedError("offset() has been removed. " +
|
2015-09-19 14:36:19 +03:00
|
|
|
"Please call ImageChops.offset() instead.")
|
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
|
|
|
|
(0, 0)). If a 4-tuple is given, the size of the pasted image
|
|
|
|
must match the size of the region.
|
|
|
|
|
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
|
|
|
|
indicated by the mask. You can use either "1", "L" or "RGBA"
|
|
|
|
images (in the latter case, the alpha band is used as mask).
|
|
|
|
Where the mask is 255, the given image is copied as is. Where
|
|
|
|
the mask is 0, the current value is preserved. Intermediate
|
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:
|
|
|
|
# cover all of self
|
|
|
|
box = (0, 0) + self.size
|
|
|
|
|
|
|
|
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?
|
|
|
|
raise ValueError(
|
|
|
|
"cannot determine region size; use 4-item box"
|
|
|
|
)
|
|
|
|
box = box + (box[0]+size[0], box[1]+size[1])
|
|
|
|
|
|
|
|
if isStringType(im):
|
2013-03-07 20:20:28 +04:00
|
|
|
from PIL import ImageColor
|
2010-07-31 06:52:47 +04:00
|
|
|
im = ImageColor.getcolor(im, self.mode)
|
|
|
|
|
|
|
|
elif isImageType(im):
|
|
|
|
im.load()
|
|
|
|
if self.mode != im.mode:
|
|
|
|
if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"):
|
|
|
|
# should use an adapter for this!
|
|
|
|
im = im.convert(self.mode)
|
|
|
|
im = im.im
|
|
|
|
|
|
|
|
self.load()
|
|
|
|
if self.readonly:
|
|
|
|
self._copy()
|
|
|
|
|
|
|
|
if mask:
|
|
|
|
mask.load()
|
|
|
|
self.im.paste(im, box, mask.im)
|
|
|
|
else:
|
|
|
|
self.im.paste(im, box)
|
|
|
|
|
|
|
|
def point(self, lut, mode=None):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Maps this image through a lookup table or function.
|
|
|
|
|
2013-12-11 04:05:05 +04:00
|
|
|
:param lut: A lookup table, containing 256 (or 65336 if
|
|
|
|
self.mode=="I" and mode == "L") values per band in the
|
|
|
|
image. A function can be used instead, it should take a
|
|
|
|
single argument. The function is called once for each
|
|
|
|
possible pixel value, and the resulting table is applied to
|
|
|
|
all bands of the image.
|
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
|
|
|
|
raise ValueError("point operation not supported for this mode")
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
self.load()
|
|
|
|
if self.readonly:
|
|
|
|
self._copy()
|
|
|
|
|
|
|
|
if self.mode not in ("LA", "RGBA"):
|
|
|
|
# attempt to promote self to a matching alpha mode
|
|
|
|
try:
|
|
|
|
mode = getmodebase(self.mode) + "A"
|
|
|
|
try:
|
|
|
|
self.im.setmode(mode)
|
2014-01-06 10:18:42 +04:00
|
|
|
self.pyaccess = None
|
2010-07-31 06:52:47 +04:00
|
|
|
except (AttributeError, ValueError):
|
|
|
|
# do things the hard way
|
|
|
|
im = self.im.convert(mode)
|
|
|
|
if im.mode not in ("LA", "RGBA"):
|
2014-04-22 10:23:34 +04:00
|
|
|
raise ValueError # sanity check
|
2010-07-31 06:52:47 +04:00
|
|
|
self.im = im
|
2014-01-06 10:18:42 +04:00
|
|
|
self.pyaccess = None
|
2010-07-31 06:52:47 +04:00
|
|
|
self.mode = self.im.mode
|
|
|
|
except (KeyError, ValueError):
|
|
|
|
raise ValueError("illegal image mode")
|
|
|
|
|
|
|
|
if self.mode == "LA":
|
|
|
|
band = 1
|
|
|
|
else:
|
|
|
|
band = 3
|
|
|
|
|
|
|
|
if isImageType(alpha):
|
|
|
|
# alpha layer
|
|
|
|
if alpha.mode not in ("1", "L"):
|
|
|
|
raise ValueError("illegal image mode")
|
|
|
|
alpha.load()
|
|
|
|
if alpha.mode == "1":
|
|
|
|
alpha = alpha.convert("L")
|
|
|
|
else:
|
|
|
|
# constant alpha
|
|
|
|
try:
|
|
|
|
self.im.fillband(band, alpha)
|
|
|
|
except (AttributeError, ValueError):
|
|
|
|
# do things the hard way
|
|
|
|
alpha = new("L", self.size, alpha)
|
|
|
|
else:
|
|
|
|
return
|
|
|
|
|
|
|
|
self.im.putband(alpha.im, band)
|
|
|
|
|
|
|
|
def putdata(self, data, scale=1.0, offset=0.0):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Copies pixel data to this image. This method copies data from a
|
|
|
|
sequence object into the image, starting at the upper left
|
|
|
|
corner (0, 0), and continuing 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 sequence object.
|
|
|
|
: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
|
|
|
|
|
|
|
self.load()
|
|
|
|
if self.readonly:
|
|
|
|
self._copy()
|
|
|
|
|
|
|
|
self.im.putdata(data, scale, offset)
|
|
|
|
|
|
|
|
def putpalette(self, data, rawmode="RGB"):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Attaches a palette to this image. The image must be a "P" or
|
|
|
|
"L" image, and the palette sequence must contain 768 integer
|
|
|
|
values, where each group of three values represent the red,
|
|
|
|
green, and blue values for the corresponding pixel
|
|
|
|
index. Instead of an integer sequence, you can use an 8-bit
|
|
|
|
string.
|
|
|
|
|
|
|
|
:param data: A palette sequence (either a list or a string).
|
|
|
|
"""
|
2013-03-07 20:20:28 +04:00
|
|
|
from PIL import ImagePalette
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
if self.mode not in ("L", "P"):
|
|
|
|
raise ValueError("illegal image mode")
|
|
|
|
self.load()
|
|
|
|
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):
|
|
|
|
if bytes is str:
|
|
|
|
data = "".join(chr(x) for x in data)
|
|
|
|
else:
|
|
|
|
data = bytes(data)
|
2010-07-31 06:52:47 +04:00
|
|
|
palette = ImagePalette.raw(rawmode, data)
|
|
|
|
self.mode = "P"
|
|
|
|
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
|
|
|
|
multi-band images.
|
|
|
|
|
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
|
|
|
|
|
|
|
:param xy: The pixel coordinate, given as (x, y).
|
|
|
|
:param value: The pixel value.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.load()
|
|
|
|
if self.readonly:
|
|
|
|
self._copy()
|
2014-01-06 09:06:13 +04:00
|
|
|
self.pyaccess = None
|
|
|
|
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)
|
2010-07-31 06:52:47 +04:00
|
|
|
return self.im.putpixel(xy, value)
|
|
|
|
|
|
|
|
def resize(self, size, resample=NEAREST):
|
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
|
2016-06-16 20:04:20 +03:00
|
|
|
one of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BOX`,
|
|
|
|
:py:attr:`PIL.Image.BILINEAR`, :py:attr:`PIL.Image.HAMMING`,
|
2016-06-16 23:23:03 +03:00
|
|
|
:py:attr:`PIL.Image.BICUBIC` or :py:attr:`PIL.Image.LANCZOS`.
|
2013-07-09 18:32:14 +04:00
|
|
|
If omitted, or if the image has mode "1" or "P", it is
|
2013-10-12 09:18:40 +04:00
|
|
|
set :py:attr:`PIL.Image.NEAREST`.
|
2016-06-16 20:04:20 +03:00
|
|
|
See: :ref:`concept-filters`.
|
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-16 20:04:20 +03:00
|
|
|
if resample not in (
|
2016-06-16 23:23:03 +03:00
|
|
|
NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING,
|
2016-06-16 20:04:20 +03:00
|
|
|
):
|
2010-07-31 06:52:47 +04:00
|
|
|
raise ValueError("unknown resampling filter")
|
|
|
|
|
|
|
|
self.load()
|
|
|
|
|
2015-04-02 08:29:18 +03:00
|
|
|
size = tuple(size)
|
2014-09-10 04:41:46 +04:00
|
|
|
if self.size == size:
|
|
|
|
return self._new(self.im)
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
if self.mode in ("1", "P"):
|
|
|
|
resample = NEAREST
|
|
|
|
|
2016-05-10 21:46:40 +03:00
|
|
|
if self.mode == 'LA':
|
|
|
|
return self.convert('La').resize(size, resample).convert('LA')
|
|
|
|
|
2013-10-05 00:25:32 +04:00
|
|
|
if self.mode == 'RGBA':
|
|
|
|
return self.convert('RGBa').resize(size, resample).convert('RGBA')
|
|
|
|
|
2014-11-04 12:31:36 +03:00
|
|
|
return self._new(self.im.resize(size, resample))
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def rotate(self, angle, resample=NEAREST, expand=0):
|
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
|
2013-10-12 09:18:40 +04:00
|
|
|
one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
|
|
|
|
:py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
|
|
|
|
environment), or :py:attr:`PIL.Image.BICUBIC`
|
2013-07-09 18:32:14 +04:00
|
|
|
(cubic spline interpolation in a 4x4 environment).
|
|
|
|
If omitted, or if the image has mode "1" or "P", it is
|
2016-06-16 20:04:20 +03:00
|
|
|
set :py:attr:`PIL.Image.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
|
|
|
|
input 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
|
|
|
|
|
|
|
|
# Fast paths regardless of filter
|
|
|
|
if angle == 0:
|
2016-08-05 19:20:02 +03:00
|
|
|
return self.copy()
|
2016-06-02 10:57:55 +03:00
|
|
|
if angle == 180:
|
|
|
|
return self.transpose(ROTATE_180)
|
|
|
|
if angle == 90 and expand:
|
|
|
|
return self.transpose(ROTATE_90)
|
|
|
|
if angle == 270 and expand:
|
|
|
|
return self.transpose(ROTATE_270)
|
|
|
|
|
2016-06-02 11:36:41 +03:00
|
|
|
angle = - math.radians(angle)
|
|
|
|
matrix = [
|
|
|
|
round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0,
|
|
|
|
round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0
|
|
|
|
]
|
|
|
|
|
|
|
|
def transform(x, y, matrix=matrix):
|
|
|
|
(a, b, c, d, e, f) = matrix
|
|
|
|
return a*x + b*y + c, d*x + e*y + f
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2016-06-02 11:36:41 +03:00
|
|
|
w, h = self.size
|
|
|
|
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)):
|
|
|
|
x, y = transform(x, y)
|
|
|
|
xx.append(x)
|
|
|
|
yy.append(y)
|
|
|
|
w = int(math.ceil(max(xx)) - math.floor(min(xx)))
|
|
|
|
h = int(math.ceil(max(yy)) - math.floor(min(yy)))
|
|
|
|
|
2016-06-02 11:36:41 +03:00
|
|
|
# adjust center
|
|
|
|
x, y = transform(w / 2.0, h / 2.0)
|
|
|
|
matrix[2] = self.size[0] / 2.0 - x
|
|
|
|
matrix[5] = self.size[1] / 2.0 - y
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2016-06-02 11:36:41 +03:00
|
|
|
return self.transform((w, h), AFFINE, matrix, resample)
|
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.
|
2013-07-09 23:12:28 +04:00
|
|
|
:param options: Extra parameters to the image writer.
|
2013-07-09 18:32:14 +04:00
|
|
|
:returns: None
|
|
|
|
:exception KeyError: If the output format could not be determined
|
|
|
|
from the file name. Use the format option to solve this.
|
|
|
|
:exception IOError: If the file could not be written. The file
|
|
|
|
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
|
2013-06-30 15:04:42 +04:00
|
|
|
if isPath(fp):
|
2010-07-31 06:52:47 +04:00
|
|
|
filename = fp
|
2015-10-03 10:29:52 +03:00
|
|
|
open_fp = True
|
2015-08-05 13:54:33 +03:00
|
|
|
elif sys.version_info >= (3, 4):
|
|
|
|
from pathlib import Path
|
|
|
|
if isinstance(fp, Path):
|
2016-02-27 05:10:50 +03:00
|
|
|
filename = str(fp)
|
2015-10-03 10:29:52 +03:00
|
|
|
open_fp = True
|
2015-08-05 13:54:33 +03:00
|
|
|
elif hasattr(fp, "name") and isPath(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!
|
|
|
|
self.load()
|
|
|
|
|
2015-06-30 11:02:48 +03:00
|
|
|
save_all = False
|
|
|
|
if 'save_all' in params:
|
2016-06-18 04:25:39 +03:00
|
|
|
save_all = params.pop('save_all')
|
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()
|
2015-07-01 02:19:28 +03:00
|
|
|
format = EXTENSION[ext]
|
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
|
|
|
|
2015-10-03 10:12:44 +03:00
|
|
|
if open_fp:
|
2015-08-05 13:54:33 +03:00
|
|
|
fp = builtins.open(filename, "wb")
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
try:
|
|
|
|
save_handler(self, fp, filename)
|
|
|
|
finally:
|
|
|
|
# do what we can to clean up
|
2015-10-03 10:12:44 +03:00
|
|
|
if open_fp:
|
2010-07-31 06:52:47 +04:00
|
|
|
fp.close()
|
|
|
|
|
|
|
|
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
|
|
|
|
**EOFError** exception. When a sequence file is opened, the
|
|
|
|
library automatically seeks to frame 0.
|
|
|
|
|
|
|
|
Note that in the current version of the library, most sequence
|
|
|
|
formats only allows you to seek to the next frame.
|
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
See :py:meth:`~PIL.Image.Image.tell`.
|
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
|
|
|
|
|
|
|
|
def show(self, title=None, command=None):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Displays this image. This method is mainly intended for
|
|
|
|
debugging purposes.
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2013-07-09 18:32:14 +04:00
|
|
|
On Unix platforms, this method saves the image to a temporary
|
2016-05-05 12:30:07 +03:00
|
|
|
PPM file, and calls either the **xv** utility or the **display**
|
|
|
|
utility, depending on which one can be found.
|
|
|
|
|
2016-09-23 14:12:03 +03:00
|
|
|
On macOS, this method saves the image to a temporary BMP file, and opens
|
2016-05-05 12:30:07 +03:00
|
|
|
it with the native Preview application.
|
2013-07-09 18:32:14 +04:00
|
|
|
|
|
|
|
On Windows, it saves the image to a temporary BMP file, and uses
|
|
|
|
the standard BMP display utility to show it (usually Paint).
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2013-07-09 18:32:14 +04:00
|
|
|
:param title: Optional title to use for the image window,
|
|
|
|
where possible.
|
|
|
|
:param command: command used to show the image
|
|
|
|
"""
|
|
|
|
|
|
|
|
_show(self, title=title, command=command)
|
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).
|
|
|
|
|
|
|
|
: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:
|
|
|
|
ims = []
|
|
|
|
for i in range(self.im.bands):
|
|
|
|
ims.append(self._new(self.im.getband(i)))
|
|
|
|
return tuple(ims)
|
|
|
|
|
|
|
|
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
|
|
|
|
2013-07-09 18:32:14 +04:00
|
|
|
:returns: Frame number, starting with 0.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
return 0
|
|
|
|
|
2014-11-28 04:21:03 +03:00
|
|
|
def thumbnail(self, size, resample=BICUBIC):
|
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
|
|
|
|
|
|
|
:param size: Requested size.
|
|
|
|
:param resample: Optional resampling filter. This can be one
|
2013-10-12 09:18:40 +04:00
|
|
|
of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BILINEAR`,
|
2014-11-28 01:41:56 +03:00
|
|
|
:py:attr:`PIL.Image.BICUBIC`, or :py:attr:`PIL.Image.LANCZOS`.
|
2014-11-28 04:21:03 +03:00
|
|
|
If omitted, it defaults to :py:attr:`PIL.Image.BICUBIC`.
|
2014-11-09 04:26:53 +03:00
|
|
|
(was :py:attr:`PIL.Image.NEAREST` prior to version 2.5.0)
|
2013-07-09 18:32:14 +04:00
|
|
|
:returns: None
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
# preserve aspect ratio
|
|
|
|
x, y = self.size
|
2014-04-22 10:23:34 +04:00
|
|
|
if x > size[0]:
|
|
|
|
y = int(max(y * size[0] / x, 1))
|
|
|
|
x = int(size[0])
|
|
|
|
if y > size[1]:
|
|
|
|
x = int(max(x * size[1] / y, 1))
|
|
|
|
y = int(size[1])
|
2010-07-31 06:52:47 +04:00
|
|
|
size = x, y
|
|
|
|
|
|
|
|
if size == self.size:
|
|
|
|
return
|
|
|
|
|
|
|
|
self.draft(None, size)
|
|
|
|
|
2014-11-09 04:20:54 +03:00
|
|
|
im = self.resize(size, resample)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.im = im.im
|
|
|
|
self.mode = im.mode
|
|
|
|
self.size = size
|
|
|
|
|
|
|
|
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.
|
|
|
|
def transform(self, size, method, data=None, resample=NEAREST, fill=1):
|
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.
|
|
|
|
|
|
|
|
:param size: The output size.
|
|
|
|
:param method: The transformation method. This is one of
|
2013-10-12 09:18:40 +04:00
|
|
|
:py:attr:`PIL.Image.EXTENT` (cut out a rectangular subregion),
|
|
|
|
:py:attr:`PIL.Image.AFFINE` (affine transform),
|
|
|
|
:py:attr:`PIL.Image.PERSPECTIVE` (perspective transform),
|
|
|
|
:py:attr:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or
|
|
|
|
:py:attr:`PIL.Image.MESH` (map a number of source quadrilaterals
|
2013-07-09 18:32:14 +04:00
|
|
|
in one operation).
|
|
|
|
:param data: Extra data to the transformation method.
|
|
|
|
:param resample: Optional resampling filter. It can be one of
|
2013-10-12 09:18:40 +04:00
|
|
|
:py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
|
|
|
|
:py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
|
|
|
|
environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline
|
2013-07-09 18:32:14 +04:00
|
|
|
interpolation in a 4x4 environment). If omitted, or if the image
|
2013-10-12 09:18:40 +04:00
|
|
|
has mode "1" or "P", it is set to :py:attr:`PIL.Image.NEAREST`.
|
|
|
|
: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-05-10 21:46:40 +03:00
|
|
|
if self.mode == 'LA':
|
|
|
|
return self.convert('La').transform(
|
|
|
|
size, method, data, resample, fill).convert('LA')
|
|
|
|
|
2013-10-05 00:25:32 +04:00
|
|
|
if self.mode == 'RGBA':
|
2014-04-22 10:23:34 +04:00
|
|
|
return self.convert('RGBa').transform(
|
|
|
|
size, method, data, resample, fill).convert('RGBA')
|
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:
|
|
|
|
raise ValueError("missing method data")
|
2013-10-12 09:18:40 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
im = new(self.mode, size, None)
|
|
|
|
if method == MESH:
|
|
|
|
# list of quads
|
|
|
|
for box, quad in data:
|
|
|
|
im.__transformer(box, self, QUAD, quad, resample, fill)
|
|
|
|
else:
|
|
|
|
im.__transformer((0, 0)+size, self, method, data, resample, fill)
|
2013-10-12 09:18:40 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
return im
|
|
|
|
|
|
|
|
def __transformer(self, box, image, method, data,
|
|
|
|
resample=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
|
|
|
|
|
|
|
if method == AFFINE:
|
2016-06-02 21:58:42 +03:00
|
|
|
data = data[0:6]
|
2016-06-02 10:57:55 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
elif method == EXTENT:
|
|
|
|
# convert extent to an affine transform
|
|
|
|
x0, y0, x1, y1 = data
|
|
|
|
xs = float(x1 - x0) / w
|
|
|
|
ys = float(y1 - y0) / h
|
|
|
|
method = AFFINE
|
2016-07-11 01:47:25 +03:00
|
|
|
data = (xs, 0, x0, 0, ys, y0)
|
2016-06-02 10:57:55 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
elif method == PERSPECTIVE:
|
2016-06-02 23:47:45 +03:00
|
|
|
data = data[0:8]
|
2016-06-02 10:57:55 +03:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
elif method == QUAD:
|
|
|
|
# quadrilateral warp. data specifies the four corners
|
|
|
|
# given as NW, SW, SE, and NE.
|
2014-04-22 10:23:34 +04:00
|
|
|
nw = data[0:2]
|
|
|
|
sw = data[2:4]
|
|
|
|
se = data[4:6]
|
|
|
|
ne = data[6:8]
|
|
|
|
x0, y0 = nw
|
|
|
|
As = 1.0 / w
|
|
|
|
At = 1.0 / h
|
2010-07-31 06:52:47 +04: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:
|
|
|
|
raise ValueError("unknown transformation method")
|
|
|
|
|
|
|
|
if resample not in (NEAREST, BILINEAR, BICUBIC):
|
|
|
|
raise ValueError("unknown resampling filter")
|
|
|
|
|
|
|
|
image.load()
|
|
|
|
|
|
|
|
self.load()
|
|
|
|
|
|
|
|
if image.mode in ("1", "P"):
|
|
|
|
resample = NEAREST
|
|
|
|
|
|
|
|
self.im.transform2(box, image.im, method, data, resample, fill)
|
|
|
|
|
|
|
|
def transpose(self, method):
|
2013-07-09 18:32:14 +04:00
|
|
|
"""
|
|
|
|
Transpose image (flip or rotate in 90 degree steps)
|
|
|
|
|
2013-10-12 09:18:40 +04:00
|
|
|
:param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`,
|
|
|
|
:py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`,
|
2014-11-07 03:37:12 +03:00
|
|
|
:py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.ROTATE_270` or
|
|
|
|
:py:attr:`PIL.Image.TRANSPOSE`.
|
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"""
|
2015-06-19 08:55:35 +03:00
|
|
|
from PIL import ImageQt
|
|
|
|
if not ImageQt.qt_is_installed:
|
|
|
|
raise ImportError("Qt bindings are not installed")
|
|
|
|
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"""
|
2015-06-19 08:55:35 +03:00
|
|
|
from PIL import ImageQt
|
|
|
|
if not ImageQt.qt_is_installed:
|
|
|
|
raise ImportError("Qt bindings are not installed")
|
|
|
|
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.
|
|
|
|
|
2015-05-26 17:07:21 +03:00
|
|
|
class ImagePointHandler(object):
|
2010-07-31 06:52:47 +04:00
|
|
|
# used as a mixin by point transforms (for use with im.point)
|
|
|
|
pass
|
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2015-05-26 17:07:21 +03:00
|
|
|
class ImageTransformHandler(object):
|
2010-07-31 06:52:47 +04:00
|
|
|
# used as a mixin by geometry transforms (for use with im.transform)
|
|
|
|
pass
|
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Factories
|
|
|
|
|
|
|
|
#
|
|
|
|
# Debugging
|
|
|
|
|
|
|
|
def _wedge():
|
|
|
|
"Create greyscale wedge (for debugging only)"
|
|
|
|
|
|
|
|
return Image()._new(core.wedge("L"))
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
if color is None:
|
|
|
|
# don't initialize
|
|
|
|
return Image()._new(core.new(mode, size))
|
|
|
|
|
|
|
|
if isStringType(color):
|
|
|
|
# css3-style specifier
|
|
|
|
|
2013-03-07 20:20:28 +04:00
|
|
|
from PIL import ImageColor
|
2010-07-31 06:52:47 +04:00
|
|
|
color = ImageColor.getcolor(color, mode)
|
|
|
|
|
|
|
|
return Image()._new(core.fill(mode, size, color))
|
|
|
|
|
|
|
|
|
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).
|
|
|
|
|
|
|
|
You can also use any pixel decoder supported by PIL. For more
|
|
|
|
information on available decoders, see the section
|
2015-01-07 02:12:37 +03:00
|
|
|
:ref:`Writing Your Own File Decoder <file-decoders>`.
|
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
|
|
|
|
|
|
|
# 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
|
|
|
|
2013-03-07 13:23:40 +04:00
|
|
|
def fromstring(*args, **kw):
|
2016-04-27 11:12:57 +03:00
|
|
|
raise NotImplementedError("fromstring() has been removed. " +
|
2015-09-19 14:36:19 +03:00
|
|
|
"Please call frombytes() instead.")
|
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
|
|
|
|
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
|
2013-10-12 09:18:40 +04:00
|
|
|
**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
|
|
|
|
|
|
|
# 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 == ():
|
2015-12-09 08:55:33 +03:00
|
|
|
warnings.warn(
|
|
|
|
"the frombuffer defaults may change in a future release; "
|
|
|
|
"for portability, change the call to read:\n"
|
|
|
|
" frombuffer(mode, size, data, 'raw', mode, 0, 1)",
|
|
|
|
RuntimeWarning, stacklevel=2
|
|
|
|
)
|
2014-04-22 10:23:34 +04:00
|
|
|
args = mode, 0, -1 # may change to (mode, 0, 1) post-1.1.6
|
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))
|
2010-07-31 06:52:47 +04:00
|
|
|
im = im._new(
|
|
|
|
core.map_buffer(data, size, decoder_name, None, 0, args)
|
|
|
|
)
|
|
|
|
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).
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
:param obj: Object with array interface
|
|
|
|
:param mode: Mode to use (will be determined from type if None)
|
2014-11-19 23:49:27 +03:00
|
|
|
See: :ref:`concept-modes`.
|
|
|
|
: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__
|
|
|
|
shape = arr['shape']
|
|
|
|
ndim = len(shape)
|
|
|
|
try:
|
|
|
|
strides = arr['strides']
|
|
|
|
except KeyError:
|
|
|
|
strides = None
|
|
|
|
if mode is None:
|
|
|
|
try:
|
|
|
|
typekey = (1, 1) + shape[2:], arr['typestr']
|
|
|
|
mode, rawmode = _fromarray_typemap[typekey]
|
|
|
|
except KeyError:
|
|
|
|
# print typekey
|
|
|
|
raise TypeError("Cannot handle this data type")
|
|
|
|
else:
|
|
|
|
rawmode = mode
|
|
|
|
if mode in ["1", "L", "I", "P", "F"]:
|
|
|
|
ndmax = 2
|
|
|
|
elif mode == "RGB":
|
|
|
|
ndmax = 3
|
|
|
|
else:
|
|
|
|
ndmax = 4
|
|
|
|
if ndim > ndmax:
|
2014-03-24 20:49:19 +04:00
|
|
|
raise ValueError("Too many dimensions: %d > %d." % (ndim, ndmax))
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
size = shape[1], shape[0]
|
|
|
|
if strides is not None:
|
2013-05-22 08:04:22 +04:00
|
|
|
if hasattr(obj, 'tobytes'):
|
|
|
|
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"""
|
2015-06-19 08:55:35 +03:00
|
|
|
from PIL import ImageQt
|
|
|
|
if not ImageQt.qt_is_installed:
|
|
|
|
raise ImportError("Qt bindings are not installed")
|
|
|
|
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"""
|
2015-06-19 08:55:35 +03:00
|
|
|
from PIL import ImageQt
|
|
|
|
if not ImageQt.qt_is_installed:
|
|
|
|
raise ImportError("Qt bindings are not installed")
|
|
|
|
return ImageQt.fromqpixmap(im)
|
2014-09-15 22:24:56 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
_fromarray_typemap = {
|
|
|
|
# (shape, typestr) => mode, rawmode
|
|
|
|
# first two members of shape are set to one
|
|
|
|
# ((1, 1), "|b1"): ("1", "1"), # broken
|
|
|
|
((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"),
|
|
|
|
}
|
|
|
|
|
|
|
|
# shortcuts
|
|
|
|
_fromarray_typemap[((1, 1), _ENDIAN + "i4")] = ("I", "I")
|
|
|
|
_fromarray_typemap[((1, 1), _ENDIAN + "f4")] = ("F", "F")
|
|
|
|
|
|
|
|
|
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
|
|
|
|
2014-05-26 17:25:15 +04:00
|
|
|
if pixels > MAX_IMAGE_PIXELS:
|
|
|
|
warnings.warn(
|
|
|
|
"Image size (%d pixels) exceeds limit of %d pixels, "
|
|
|
|
"could be decompression bomb DOS attack." %
|
|
|
|
(pixels, MAX_IMAGE_PIXELS),
|
2014-06-23 11:53:08 +04:00
|
|
|
DecompressionBombWarning)
|
2014-05-14 19:04:18 +04:00
|
|
|
|
|
|
|
|
2014-05-26 17:25:15 +04:00
|
|
|
def open(fp, mode="r"):
|
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
|
|
|
|
:py:func:`~PIL.Image.new`.
|
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.
|
2015-08-05 17:24:08 +03:00
|
|
|
The file object must implement :py:meth:`~file.read`,
|
|
|
|
:py:meth:`~file.seek`, and :py:meth:`~file.tell` methods,
|
|
|
|
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".
|
2013-10-12 09:18:40 +04:00
|
|
|
:returns: An :py:class:`~PIL.Image.Image` object.
|
2013-07-09 23:12:28 +04:00
|
|
|
:exception IOError: If the file cannot be found, or the image cannot be
|
|
|
|
opened and identified.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
if mode != "r":
|
2014-03-24 20:49:19 +04:00
|
|
|
raise ValueError("bad mode %r" % mode)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2015-08-05 13:54:33 +03:00
|
|
|
filename = ""
|
2013-06-30 15:04:42 +04:00
|
|
|
if isPath(fp):
|
2010-07-31 06:52:47 +04:00
|
|
|
filename = fp
|
2016-09-14 21:51:10 +03:00
|
|
|
else:
|
|
|
|
try:
|
|
|
|
from pathlib import Path
|
|
|
|
if isinstance(fp, Path):
|
|
|
|
filename = str(fp.resolve())
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
|
2015-08-05 13:54:33 +03:00
|
|
|
if filename:
|
|
|
|
fp = builtins.open(filename, "rb")
|
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())
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
prefix = fp.read(16)
|
|
|
|
|
|
|
|
preinit()
|
|
|
|
|
2015-09-10 17:03:24 +03:00
|
|
|
def _open_core(fp, filename, prefix):
|
2010-07-31 06:52:47 +04:00
|
|
|
for i in ID:
|
|
|
|
try:
|
|
|
|
factory, accept = OPEN[i]
|
|
|
|
if not accept or accept(prefix):
|
|
|
|
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
|
2015-09-10 17:03:24 +03:00
|
|
|
return None
|
|
|
|
|
|
|
|
im = _open_core(fp, filename, prefix)
|
2015-09-11 12:28:19 +03:00
|
|
|
|
2015-09-10 17:03:24 +03:00
|
|
|
if im is None:
|
|
|
|
if init():
|
|
|
|
im = _open_core(fp, filename, prefix)
|
|
|
|
|
|
|
|
if im:
|
|
|
|
return im
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-03-24 20:49:19 +04:00
|
|
|
raise IOError("cannot identify image file %r"
|
|
|
|
% (filename if filename else fp))
|
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
|
|
|
|
a constant alpha.::
|
|
|
|
|
|
|
|
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:
|
|
|
|
raise ValueError("wrong number of bands")
|
|
|
|
for im in bands[1:]:
|
|
|
|
if im.mode != getmodetype(mode):
|
|
|
|
raise ValueError("mode mismatch")
|
|
|
|
if im.size != bands[0].size:
|
|
|
|
raise ValueError("size mismatch")
|
|
|
|
im = core.new(mode, bands[0].size)
|
|
|
|
for i in range(getmodebands(mode)):
|
|
|
|
bands[i].load()
|
|
|
|
im.putband(bands[i].im, i)
|
|
|
|
return bands[0]._new(im)
|
|
|
|
|
2014-04-22 10:23:34 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Plugin registry
|
|
|
|
|
|
|
|
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()
|
2010-07-31 06:52:47 +04:00
|
|
|
ID.append(id)
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Simple display support. User code may override this.
|
|
|
|
|
|
|
|
def _show(image, **options):
|
|
|
|
# override me, as necessary
|
2012-10-21 01:05:13 +04:00
|
|
|
_showxv(image, **options)
|
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 _showxv(image, title=None, **options):
|
2013-03-07 20:20:28 +04:00
|
|
|
from PIL import ImageShow
|
2012-10-21 01:05:13 +04:00
|
|
|
ImageShow.show(image, title, **options)
|
2014-09-02 15:11:08 +04:00
|
|
|
|
|
|
|
|
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Effects
|
|
|
|
|
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:
|
|
|
|
(x0, y0, x1, y2).
|
|
|
|
: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))
|