Pillow Tools
Pillow Tools
Pillow Tools
Release 7.2.0.dev0
Alex Clark
1 Installation 3
1.1 Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Basic Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Building From Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5 Platform Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.6 Old Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2 Handbook 11
2.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.2 Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.3 Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.4 Appendices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3 Reference 47
3.1 Image Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
3.2 ImageChops (“Channel Operations”) Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
3.3 ImageColor Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
3.4 ImageCms Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
3.5 ImageDraw Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
3.6 ImageEnhance Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
3.7 ImageFile Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
3.8 ImageFilter Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
3.9 ImageFont Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
3.10 ImageGrab Module (macOS and Windows only) . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
3.11 ImageMath Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
3.12 ImageMorph Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
3.13 ImageOps Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
3.14 ImagePalette Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
3.15 ImagePath Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
3.16 ImageQt Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
3.17 ImageSequence Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
3.18 ImageStat Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
3.19 ImageTk Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
3.20 ImageWin Module (Windows-only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
3.21 ExifTags Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
3.22 TiffTags Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
i
3.23 PSDraw Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
3.24 PixelAccess Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
3.25 PyAccess Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
3.26 PIL Package (autodoc of remaining modules) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
3.27 Plugin reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
3.28 Internal Reference Docs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
4 Porting 147
5 About 149
5.1 Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
5.2 License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
5.3 Why a fork? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
5.4 What about PIL? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
ii
Index 195
iii
iv
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Pillow is the friendly PIL fork by Alex Clark and Contributors. PIL is the Python Imaging Library by Fredrik Lundh
and Contributors.
Pillow for enterprise is available via the Tidelift Subscription. Learn more.
Contents 1
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
2 Contents
CHAPTER 1
Installation
1.1 Warnings
Warning: Pillow and PIL cannot co-exist in the same environment. Before installing Pillow, please uninstall PIL.
Warning: Pillow >= 1.0 no longer supports “import Image”. Please use “from PIL import Image” instead.
Warning: Pillow >= 2.1.0 no longer supports “import _imaging”. Please use “from PIL.Image import core as
_imaging” instead.
1.2 Notes
Python 3.8 3.7 3.6 3.5 3.4 3.3 3.2 2.7 2.6 2.5 2.4
Pillow >= 7 Yes Yes Yes Yes
Pillow 6.2.1 - 6.2.2 Yes Yes Yes Yes Yes
Pillow 6.0 - 6.2.0 Yes Yes Yes Yes
Pillow 5.2 - 5.4 Yes Yes Yes Yes Yes
Pillow 5.0 - 5.1 Yes Yes Yes Yes
Pillow 4 Yes Yes Yes Yes Yes
Pillow 2 - 3 Yes Yes Yes Yes Yes Yes
Pillow < 2 Yes Yes Yes Yes
3
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Note: The following instructions will install Pillow with support for most common image formats. See External
Libraries for a full list of external libraries supported.
We provide Pillow binaries for Windows compiled for the matrix of supported Pythons in both 32 and 64-bit versions
in the wheel format. These binaries have all of the optional libraries included except for raqm, libimagequant, and
libxcb:
We provide binaries for macOS for each of the supported Python versions in the wheel format. These include support
for all optional libraries except libimagequant and libxcb. Raqm support requires libraqm, fribidi, and harfbuzz to be
installed separately:
We provide binaries for Linux for each of the supported Python versions in the manylinux wheel format. These
include support for all optional libraries except libimagequant. Raqm support requires libraqm, fribidi, and harfbuzz
to be installed separately:
Most major Linux distributions, including Fedora, Debian/Ubuntu and ArchLinux also include Pillow in packages that
previously contained PIL e.g. python-imaging.
Pillow can be installed on FreeBSD via the official Ports or Packages systems:
Ports:
Packages:
4 Chapter 1. Installation
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Note: The Pillow FreeBSD port and packages are tested by the ports team with all supported FreeBSD versions.
Note: You do not need to install all supported external libraries to use Pillow’s basic features. Zlib and libjpeg
are required by default.
Note: There are Dockerfiles in our Docker images repo to install the dependencies for some operating systems.
If the prerequisites are installed in the standard library locations for your machine (e.g. /usr or /usr/local), no
additional configuration should be required. If they are installed in a non-standard location, you may need to configure
setuptools to use those locations by editing setup.py or setup.cfg, or by adding environment variables on the
command line:
If Pillow has been previously built without the required prerequisites, it may be necessary to manually clear the pip
cache or build without cache using the --no-cache-dir option to force a build with newly installed external
libraries.
• Environment variable: MAX_CONCURRENCY=n. Pillow can use multiprocessing to build the extension. Setting
MAX_CONCURRENCY sets the number of CPUs to use, or can disable parallel building by using a setting of 1.
By default, it uses 4 CPUs, or if 4 are not available, as many as are present.
• Build flags: --disable-zlib, --disable-jpeg, --disable-tiff, --disable-freetype,
--disable-lcms, --disable-webp, --disable-webpmux, --disable-jpeg2000,
--disable-imagequant, --disable-xcb. Disable building the corresponding feature even if
the development libraries are present on the building machine.
• Build flags: --enable-zlib, --enable-jpeg, --enable-tiff, --enable-freetype,
--enable-lcms, --enable-webp, --enable-webpmux, --enable-jpeg2000,
--enable-imagequant, --enable-xcb. Require that the corresponding feature is built. The
build will raise an exception if the libraries are not found. Webpmux (WebP metadata) relies on WebP support.
Tcl and Tk also must be used together.
• Build flag: --disable-platform-guessing. Skips all of the platform dependent guessing of include
and library directories for automated build systems that configure the proper paths in the environment variables
(e.g. Buildroot).
6 Chapter 1. Installation
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
• Build flag: --debug. Adds a debugging flag to the include and library search process to dump all paths
searched for and found to stdout.
Sample usage:
or using pip:
The Xcode command line tools are required to compile portions of Pillow. The tools are installed by running
xcode-select --install from the command line. The command line tools are required even if you have
the full Xcode package installed. It may be necessary to run sudo xcodebuild -license to accept the license
prior to using the tools.
The easiest way to install external libraries is via Homebrew. After you install Homebrew, run:
We don’t recommend trying to build on Windows. It is a maze of twisty passages, mostly dead ends. There are build
scripts and notes for the Windows build in the winbuild directory.
sudo pkg install jpeg-turbo tiff webp lcms2 freetype2 openjpeg harfbuzz fribidi libxcb
If you didn’t build Python from source, make sure you have Python’s development libraries installed.
In Debian or Ubuntu:
Prerequisites for Ubuntu 16.04 LTS - 20.04 LTS are installed with:
Note that the package manager may be yum or dnf, depending on the exact distribution.
See also the Dockerfiles in the Test Infrastructure repo (https://github.com/python-pillow/docker-images) for a
known working install process for other tested distros.
Basic Android support has been added for compilation within the Termux environment. The dependencies can be
installed by:
This has been tested within the Termux app on ChromeOS, on x86.
Current platform support for Pillow. Binary distributions are contributed for each release on a volunteer basis, but
the source should compile and run everywhere platform support is listed. In general, we aim to support all current
versions of Linux, macOS, and Windows.
8 Chapter 1. Installation
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Note: Contributors please test Pillow on your platform then update this document and send a pull request.
Operating system Tested Python versions Latest tested Pillow Tested pro-
version cessors
macOS 10.15 Catalina 3.5, 3.6, 3.7, 3.8 7.0.0 x86-64
macOS 10.14 Mojave 2.7, 3.5, 3.6, 3.7 6.0.0 x86-64
3.4 5.4.1
macOS 10.13 High Sierra 2.7, 3.4, 3.5, 3.6 4.2.1 x86-64
macOS 10.12 Sierra 2.7, 3.4, 3.5, 3.6 4.1.1 x86-64
Mac OS X 10.11 El Capitan 2.7, 3.4, 3.5, 3.6, 3.7 5.4.1 x86-64
3.3 4.1.0
Mac OS X 10.9 Mavericks 2.7, 3.2, 3.3, 3.4 3.0.0 x86-64
Mac OS X 10.8 Mountain 2.6, 2.7, 3.2, 3.3 x86-64
Lion
Redhat Linux 6 2.6 x86
CentOS 6.3 2.7, 3.3 x86
Fedora 23 2.7, 3.4 3.1.0 x86-64
Ubuntu Linux 12.04 LTS 2.6, 3.2, 3.3, 3.4, 3.5 PyPy5.3.1, 3.4.1 x86,x86-64
PyPy3 v2.4.0
2.7 4.3.0 x86-64
2.7, 3.2 3.4.1 ppc
Ubuntu Linux 10.04 LTS 2.6 2.3.0 x86,x86-64
Debian 8.2 Jessie 2.7, 3.4 3.1.0 x86-64
Raspbian Jessie 2.7, 3.4 3.1.0 arm
Raspbian Stretch 2.7, 3.5 4.0.0 arm
Gentoo Linux 2.7, 3.2 2.1.0 x86-64
FreeBSD 11.1 2.7, 3.4, 3.5, 3.6 4.3.0 x86-64
FreeBSD 10.3 2.7, 3.4, 3.5 4.2.0 x86-64
FreeBSD 10.2 2.7, 3.4 3.1.0 x86-64
Windows 8.1 Pro 2.6, 2.7, 3.2, 3.3, 3.4 2.4.0 x86,x86-64
Windows 8 Pro 2.6, 2.7, 3.2, 3.3, 3.4a3 2.2.0 x86,x86-64
Windows 7 Pro 2.7, 3.2, 3.3 3.4.1 x86-64
Windows Server 2008 R2 En- 3.3 x86-64
terprise
You can download old distributions from the release history at PyPI and by direct URL access eg. https://pypi.org/
project/Pillow/1.0/.
10 Chapter 1. Installation
CHAPTER 2
Handbook
2.1 Overview
The Python Imaging Library adds image processing capabilities to your Python interpreter.
This library provides extensive file format support, an efficient internal representation, and fairly powerful image
processing capabilities.
The core image library is designed for fast access to data stored in a few basic pixel formats. It should provide a solid
foundation for a general image processing tool.
Let’s look at a few possible uses of this library.
The Python Imaging Library is ideal for image archival and batch processing applications. You can use the library to
create thumbnails, convert between file formats, print images, etc.
The current version identifies and reads a large number of formats. Write support is intentionally restricted to the most
commonly used interchange and presentation formats.
The current release includes Tk PhotoImage and BitmapImage interfaces, as well as a Windows DIB
interface that can be used with PythonWin and other Windows-based toolkits. Many other GUI toolkits come
with some kind of PIL support.
For debugging, there’s also a show() method which saves an image to disk, and calls an external display utility.
11
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
The library contains basic image processing functionality, including point operations, filtering with a set of built-in
convolution kernels, and colour space conversions.
The library also supports image resizing, rotation and arbitrary affine transforms.
There’s a histogram method allowing you to pull some statistics out of an image. This can be used for automatic
contrast enhancement, and for global statistical analysis.
2.2 Tutorial
The most important class in the Python Imaging Library is the Image class, defined in the module with the same
name. You can create instances of this class in several ways; either by loading images from files, processing other
images, or creating images from scratch.
To load an image from a file, use the open() function in the Image module:
>>> from PIL import Image
>>> im = Image.open("hopper.ppm")
If successful, this function returns an Image object. You can now use instance attributes to examine the file contents:
>>> print(im.format, im.size, im.mode)
PPM (512, 512) RGB
The format attribute identifies the source of an image. If the image was not read from a file, it is set to None. The
size attribute is a 2-tuple containing width and height (in pixels). The mode attribute defines the number and names of
the bands in the image, and also the pixel type and depth. Common modes are “L” (luminance) for greyscale images,
“RGB” for true color images, and “CMYK” for pre-press images.
If the file cannot be opened, an OSError exception is raised.
Once you have an instance of the Image class, you can use the methods defined by this class to process and manipulate
the image. For example, let’s display the image we just loaded:
>>> im.show()
Note: The standard version of show() is not very efficient, since it saves the image to a temporary file and calls a
utility to display the image. If you don’t have an appropriate utility installed, it won’t even work. When it does work
though, it is very handy for debugging and tests.
The following sections provide an overview of the different functions provided in this library.
The Python Imaging Library supports a wide variety of image file formats. To read files from disk, use the open()
function in the Image module. You don’t have to know the file format to open a file. The library automatically
determines the format based on the contents of the file.
To save a file, use the save() method of the Image class. When saving files, the name becomes important. Unless
you specify the format, the library uses the filename extension to discover which file storage format to use.
12 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
A second argument can be supplied to the save() method which explicitly specifies a file format. If you use a
non-standard extension, you must always specify the format this way:
It is important to note that the library doesn’t decode or load the raster data unless it really has to. When you open a
file, the file header is read to determine the file format and extract things like mode, size, and other properties required
to decode the file, but the rest of the file is not processed until later.
This means that opening an image file is a fast operation, which is independent of the file size and compression type.
Here’s a simple script to quickly identify a set of image files:
import sys
from PIL import Image
2.2. Tutorial 13
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
The Image class contains methods allowing you to manipulate regions within an image. To extract a sub-rectangle
from an image, use the crop() method.
The region is defined by a 4-tuple, where coordinates are (left, upper, right, lower). The Python Imaging Library uses a
coordinate system with (0, 0) in the upper left corner. Also note that coordinates refer to positions between the pixels,
so the region in the above example is exactly 300x300 pixels.
The region could now be processed in a certain manner and pasted back.
region = region.transpose(Image.ROTATE_180)
im.paste(region, box)
When pasting regions back, the size of the region must match the given region exactly. In addition, the region cannot
extend outside the image. However, the modes of the original image and the region do not need to match. If they don’t,
the region is automatically converted before being pasted (see the section on Color transforms below for details).
Here’s an additional example:
Rolling an image
return image
For more advanced tricks, the paste method can also take a transparency mask as an optional argument. In this mask,
the value 255 indicates that the pasted image is opaque in that position (that is, the pasted image should be used as
is). The value 0 means that the pasted image is completely transparent. Values in-between indicate different levels of
transparency. For example, pasting an RGBA image and also using it as the mask would paste the opaque portion of
the image but not its transparent background.
The Python Imaging Library also allows you to work with the individual bands of an multi-band image, such as an
RGB image. The split method creates a set of new images, each containing one band from the original multi-band
image. The merge function takes a mode and a tuple of images, and combines them into a new image. The following
sample swaps the three bands of an RGB image:
14 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
r, g, b = im.split()
im = Image.merge("RGB", (b, g, r))
Note that for a single-band image, split() returns the image itself. To work with individual color bands, you may
want to convert the image to “RGB” first.
The PIL.Image.Image class contains methods to resize() and rotate() an image. The former takes a tuple
giving the new size, the latter the angle in degrees counter-clockwise.
To rotate the image in 90 degree steps, you can either use the rotate() method or the transpose() method. The
latter can also be used to flip an image around its horizontal or vertical axis.
Transposing an image
out = im.transpose(Image.FLIP_LEFT_RIGHT)
out = im.transpose(Image.FLIP_TOP_BOTTOM)
out = im.transpose(Image.ROTATE_90)
out = im.transpose(Image.ROTATE_180)
out = im.transpose(Image.ROTATE_270)
transpose(ROTATE) operations can also be performed identically with rotate() operations, provided the
expand flag is true, to provide for the same changes to the image’s size.
A more general form of image transformations can be carried out via the transform() method.
The Python Imaging Library allows you to convert images between different pixel representations using the
convert() method.
The library supports transformations between each supported mode and the “L” and “RGB” modes. To convert be-
tween other modes, you may have to use an intermediate image (typically an “RGB” image).
2.2. Tutorial 15
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
The Python Imaging Library provides a number of methods and modules that can be used to enhance images.
Filters
The ImageFilter module contains a number of pre-defined enhancement filters that can be used with the
filter() method.
Applying filters
Point Operations
The point() method can be used to translate the pixel values of an image (e.g. image contrast manipulation). In
most cases, a function object expecting one argument can be passed to this method. Each pixel is processed according
to that function:
Using the above technique, you can quickly apply any simple expression to an image. You can also combine the
point() and paste() methods to selectively modify an image:
R, G, B = 0, 1, 2
# paste the processed band back, but only where red was < 100
source[G].paste(out, None, mask)
16 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Python only evaluates the portion of a logical expression as is necessary to determine the outcome, and returns the
last value examined as the result of the expression. So if the expression above is false (0), Python does not look at the
second operand, and thus returns 0. Otherwise, it returns 255.
Enhancement
For more advanced image enhancement, you can use the classes in the ImageEnhance module. Once created from
an image, an enhancement object can be used to quickly try out different settings.
You can adjust contrast, brightness, color balance and sharpness in this way.
Enhancing images
enh = ImageEnhance.Contrast(im)
enh.enhance(1.3).show("30% more contrast")
The Python Imaging Library contains some basic support for image sequences (also called animation formats). Sup-
ported sequence formats include FLI/FLC, GIF, and a few experimental formats. TIFF files can also contain more than
one frame.
When you open a sequence file, PIL automatically loads the first frame in the sequence. You can use the seek and tell
methods to move between different frames:
Reading sequences
try:
while 1:
im.seek(im.tell()+1)
# do something to im
except EOFError:
pass # end of sequence
As seen in this example, you’ll get an EOFError exception when the sequence ends.
The following class lets you use the for-statement to loop over the sequence:
2.2. Tutorial 17
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
The Python Imaging Library includes functions to print images, text and graphics on Postscript printers. Here’s a
simple example:
Drawing Postscript
# draw title
ps.setfont("HelveticaNarrow-Bold", 36)
ps.text((3*72, 4*72), title)
ps.end_document()
As described earlier, the open() function of the Image module is used to open an image file. In most cases, you
simply pass it the filename as an argument. Image.open() can be used as a context manager:
If everything goes well, the result is an PIL.Image.Image object. Otherwise, an OSError exception is raised.
You can use a file-like object instead of the filename. The object must implement read(), seek() and tell()
methods, and be opened in binary mode.
18 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Note that the library rewinds the file (using seek(0)) before reading the image header. In addition, seek will also be
used when the image data is read (by the load method). If the image file is embedded in a larger file, such as a tar file,
you can use the ContainerIO or TarIO modules to access it.
fp = TarIO.TarIO("Tests/images/hopper.tar", "hopper.jpg")
im = Image.open(fp)
Some decoders allow you to manipulate the image while reading it from a file. This can often be used to speed up
decoding when creating thumbnails (when speed is usually more important than quality) and printing to a monochrome
laser printer (when only a greyscale version of the image is needed).
The draft() method manipulates an opened but not yet loaded image so it as closely as possible matches the given
mode and size. This is done by reconfiguring the image decoder.
Note that the resulting image may not exactly match the requested mode and size. To make sure that the image is not
larger than the given size, use the thumbnail method instead.
2.3 Concepts
The Python Imaging Library handles raster images; that is, rectangles of pixel data.
2.3. Concepts 19
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
2.3.1 Bands
An image can consist of one or more bands of data. The Python Imaging Library allows you to store several bands in
a single image, provided they all have the same dimensions and depth. For example, a PNG image might have ‘R’,
‘G’, ‘B’, and ‘A’ bands for the red, green, blue, and alpha transparency values. Many operations act on each band
separately, e.g., histograms. It is often useful to think of each pixel as having one value per band.
To get the number and names of bands in an image, use the getbands() method.
2.3.2 Modes
The mode of an image defines the type and depth of a pixel in the image. Each pixel uses the full range of the bit
depth. So a 1-bit pixel has a range of 0-1, an 8-bit pixel has a range of 0-255 and so on. The current release supports
the following standard modes:
• 1 (1-bit pixels, black and white, stored with one pixel per byte)
• L (8-bit pixels, black and white)
• P (8-bit pixels, mapped to any other mode using a color palette)
• RGB (3x8-bit pixels, true color)
• RGBA (4x8-bit pixels, true color with transparency mask)
• CMYK (4x8-bit pixels, color separation)
• YCbCr (3x8-bit pixels, color video format)
– Note that this refers to the JPEG, and not the ITU-R BT.2020, standard
• LAB (3x8-bit pixels, the L*a*b color space)
• HSV (3x8-bit pixels, Hue, Saturation, Value color space)
• I (32-bit signed integer pixels)
• F (32-bit floating point pixels)
Pillow also provides limited support for a few special modes, including:
• LA (L with alpha)
• PA (P with alpha)
• RGBX (true color with padding)
• RGBa (true color with premultiplied alpha)
• La (L with premultiplied alpha)
• I;16 (16-bit unsigned integer pixels)
• I;16L (16-bit little endian unsigned integer pixels)
• I;16B (16-bit big endian unsigned integer pixels)
• I;16N (16-bit native endian unsigned integer pixels)
• BGR;15 (15-bit reversed true colour)
• BGR;16 (16-bit reversed true colour)
• BGR;24 (24-bit reversed true colour)
• BGR;32 (32-bit reversed true colour)
20 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
However, Pillow doesn’t support user-defined modes; if you need to handle band combinations that are not listed
above, use a sequence of Image objects.
You can read the mode of an image through the mode attribute. This is a string containing one of the above values.
2.3.3 Size
You can read the image size through the size attribute. This is a 2-tuple, containing the horizontal and vertical size
in pixels.
The Python Imaging Library uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner. Note that
the coordinates refer to the implied pixel corners; the centre of a pixel addressed as (0, 0) actually lies at (0.5, 0.5).
Coordinates are usually passed to the library as 2-tuples (x, y). Rectangles are represented as 4-tuples, with the upper
left corner given first. For example, a rectangle covering all of an 800x600 pixel image is written as (0, 0, 800, 600).
2.3.5 Palette
The palette mode (P) uses a color palette to define the actual color for each pixel.
2.3.6 Info
You can attach auxiliary information to an image using the info attribute. This is a dictionary object.
How such information is handled when loading and saving image files is up to the file format handler (see the chapter
on Image file formats). Most handlers add properties to the info attribute when loading an image, but ignore it when
saving images.
2.3.7 Orientation
A common element of the info attribute for JPG and TIFF images is the EXIF orientation tag. This is an instruction
for how the image data should be oriented. For example, it may instruct an image to be rotated by 90 degrees, or to be
mirrored. To apply this information to an image, exif_transpose() can be used.
2.3.8 Filters
For geometry operations that may map multiple input pixels to a single output pixel, the Python Imaging Library
provides different resampling filters.
NEAREST Pick one nearest pixel from the input image. Ignore all other input pixels.
BOX Each pixel of source image contributes to one pixel of the destination image with identical weights. For upscaling
is equivalent of NEAREST. This filter can only be used with the resize() and thumbnail() methods.
New in version 3.4.0.
BILINEAR For resize calculate the output pixel value using linear interpolation on all pixels that may contribute to
the output value. For other transformations linear interpolation over a 2x2 environment in the input image is
used.
2.3. Concepts 21
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
HAMMING Produces a sharper image than BILINEAR, doesn’t have dislocations on local level like with BOX. This
filter can only be used with the resize() and thumbnail() methods.
New in version 3.4.0.
BICUBIC For resize calculate the output pixel value using cubic interpolation on all pixels that may contribute to the
output value. For other transformations cubic interpolation over a 4x4 environment in the input image is used.
LANCZOS Calculate the output pixel value using a high-quality Lanczos filter (a truncated sinc) on all pixels that may
contribute to the output value. This filter can only be used with the resize() and thumbnail() methods.
New in version 1.1.3.
2.4 Appendices
Note: Contributors please include appendices as needed or appropriate with your bug fixes, feature additions and
tests.
The Python Imaging Library supports a wide variety of raster file formats. Over 30 different file formats can be
identified and read by the library. Write support is less extensive, but most common interchange and presentation
formats are supported.
The open() function identifies files from their contents, not their names, but the save() method looks at the name
to determine which format to use, unless the format is given explicitly.
Contents
* BMP
* DIB
* EPS
22 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
* GIF
· Reading sequences
· Saving
· Reading local images
* ICNS
* ICO
* IM
* JPEG
* JPEG 2000
* MSP
* PCX
* PNG
· APNG sequences
· Saving
* PPM
* SGI
* SPIDER
· Writing files in SPIDER format
* TGA
* TIFF
· Reading Multi-frame TIFF Images
· Saving Tiff Images
* WebP
· Saving sequences
* XBM
– Read-only formats
* BLP
* CUR
* DCX
* DDS
* FLI, FLC
* FPX
* FTEX
* GBR
* GD
2.4. Appendices 23
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
* IMT
* IPTC/NAA
* MCIDAS
* MIC
* MPO
* PCD
* PIXAR
* PSD
* WAL
* WMF
* XPM
– Write-only formats
* PALM
* PDF
* XV Thumbnails
– Identify-only formats
* BUFR
* FITS
* GRIB
* HDF5
* MPEG
BMP
Pillow reads and writes Windows and OS/2 BMP files containing 1, L, P, or RGB data. 16-colour images are read as
P images. Run-length encoding is not supported.
The open() method sets the following info properties:
compression Set to bmp_rle if the file is run-length encoded.
DIB
Pillow reads and writes DIB files. DIB files are similar to BMP files, so see above for more information.
New in version 6.0.0.
EPS
Pillow identifies EPS files containing image data, and can read files that contain embedded raster images (ImageData
descriptors). If Ghostscript is available, other EPS files can be read as well. The EPS driver can also write EPS images.
The EPS driver can read EPS images in L, LAB, RGB and CMYK mode, but Ghostscript may convert the images to
24 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
RGB mode rather than leaving them in the original color space. The EPS driver can write images in L, RGB and CMYK
modes.
If Ghostscript is available, you can call the load() method with the following parameter to affect how Ghostscript
renders the EPS
scale Affects the scale of the resultant rasterized image. If the EPS suggests that the image be rendered at 100px x
100px, setting this parameter to 2 will make the Ghostscript render a 200px x 200px image instead. The relative
position of the bounding box is maintained:
im = Image.open(...)
im.size #(100,100)
im.load(scale=2)
im.size #(200,200)
GIF
Pillow reads GIF87a and GIF89a versions of the GIF file format. The library writes run-length encoded files in GIF87a
by default, unless GIF89a features are used or GIF89a is already in use.
Note that GIF files are always read as grayscale (L) or palette mode (P) images.
The open() method sets the following info properties:
background Default background color (a palette color index).
transparency Transparency color index. This key is omitted if the image is not transparent.
version Version (either GIF87a or GIF89a).
duration May not be present. The time to display the current frame of the GIF, in milliseconds.
loop May not be present. The number of times the GIF should loop. 0 means that it will loop forever.
comment May not be present. A comment about the image.
extension May not be present. Contains application specific information.
Reading sequences
The GIF loader supports the seek() and tell() methods. You can combine these methods to seek to the next
frame (im.seek(im.tell() + 1)).
im.seek() raises an EOFError if you try to seek after the last frame.
Saving
When calling save() to write a GIF file, the following options are available:
save_all If present and true, all frames of the image will be saved. If not, then only the first frame of a multiframe
image will be saved.
append_images A list of images to append as additional frames. Each of the images in the list can be single or
multiframe images. This is currently supported for GIF, PDF, TIFF, and WebP.
2.4. Appendices 25
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
It is also supported for ICNS. If images are passed in of relevant sizes, they will be used instead of scaling down
the main image.
include_color_table Whether or not to include local color table.
interlace Whether or not the image is interlaced. By default, it is, unless the image is less than 16 pixels in width or
height.
disposal Indicates the way in which the graphic is to be treated after being displayed.
• 0 - No disposal specified.
• 1 - Do not dispose.
• 2 - Restore to background color.
• 3 - Restore to previous content.
Pass a single integer for a constant disposal, or a list or tuple to set the disposal for each frame
separately.
palette Use the specified palette for the saved image. The palette should be a bytes or bytearray object containing the
palette entries in RGBRGB. . . form. It should be no more than 768 bytes. Alternately, the palette can be passed
in as an PIL.ImagePalette.ImagePalette object.
optimize If present and true, attempt to compress the palette by eliminating unused colors. This is only useful if the
palette can be compressed to the next smaller power of 2 elements.
Note that if the image you are saving comes from an existing GIF, it may have the following properties in its info
dictionary. For these options, if you do not pass them in, they will default to their info values.
transparency Transparency color index.
duration The display duration of each frame of the multiframe gif, in milliseconds. Pass a single integer for a constant
duration, or a list or tuple to set the duration for each frame separately.
loop Integer number of times the GIF should loop. 0 means that it will loop forever. By default, the image will not
loop.
comment A comment about the image.
The GIF loader creates an image memory the same size as the GIF file’s logical screen size, and pastes the actual pixel
data (the local image) into this image. If you only want the actual pixel rectangle, you can manipulate the size and
tile attributes before loading the file:
im = Image.open(...)
if im.tile[0][0] == "gif":
# only read the first "local image" from this GIF file
tag, (x0, y0, x1, y1), offset, extra = im.tile[0]
im.size = (x1 - x0, y1 - y0)
im.tile = [(tag, (0, 0) + im.size, offset, extra)]
ICNS
Pillow reads and (macOS only) writes macOS .icns files. By default, the largest available icon is read, though you
can override this by setting the size property before calling load(). The open() method sets the following info
property:
26 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
sizes A list of supported sizes found in this icon file; these are a 3-tuple, (width, height, scale), where
scale is 2 for a retina icon and 1 for a standard icon. You are permitted to use this 3-tuple format for the size
property if you set it before calling load(); after loading, the size will be reset to a 2-tuple containing pixel
dimensions (so, e.g. if you ask for (512, 512, 2), the final value of size will be (1024, 1024)).
The save() method can take the following keyword arguments:
append_images A list of images to replace the scaled down versions of the image. The order of the images does not
matter, as their use is determined by the size of each image.
New in version 5.1.0.
ICO
ICO is used to store icons on Windows. The largest available icon is read.
The save() method supports the following options:
sizes A list of sizes including in this ico file; these are a 2-tuple, (width, height); Default to [(16, 16),
(24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)]. Any sizes big-
ger than the original size or 256 will be ignored.
IM
IM is a format used by LabEye and other applications based on the IFUNC image processing library. The library reads
and writes most uncompressed interchange versions of this format.
IM is the only format that can store all internal Pillow formats.
JPEG
Pillow reads JPEG, JFIF, and Adobe JPEG files containing L, RGB, or CMYK data. It writes standard and progressive
JFIF files.
Using the draft() method, you can speed things up by converting RGB images to L, and resize images to 1/2, 1/4
or 1/8 of their original size while loading them.
The open() method may set the following info properties if available:
jfif JFIF application marker found. If the file is not a JFIF file, this key is not present.
jfif_version A tuple representing the jfif version, (major version, minor version).
jfif_density A tuple representing the pixel density of the image, in units specified by jfif_unit.
jfif_unit Units for the jfif_density:
• 0 - No Units
• 1 - Pixels per Inch
• 2 - Pixels per Centimeter
dpi A tuple representing the reported pixel density in pixels per inch, if the file is a jfif file and the units are in inches.
adobe Adobe application marker found. If the file is not an Adobe JPEG file, this key is not present.
adobe_transform Vendor Specific Tag.
progression Indicates that this is a progressive JPEG file.
2.4. Appendices 27
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
exif If present, the image will be stored with the provided raw EXIF data.
subsampling If present, sets the subsampling for the encoder.
• keep: Only valid for JPEG files, will retain the original image setting.
• 4:4:4, 4:2:2, 4:2:0: Specific sampling values
• -1: equivalent to keep
• 0: equivalent to 4:4:4
• 1: equivalent to 4:2:2
• 2: equivalent to 4:2:0
qtables If present, sets the qtables for the encoder. This is listed as an advanced option for wizards in the JPEG
documentation. Use with caution. qtables can be one of several types of values:
• a string, naming a preset, e.g. keep, web_low, or web_high
• a list, tuple, or dictionary (with integer keys = range(len(keys))) of lists of 64 integers. There must be
between 2 and 4 tables.
New in version 2.5.0.
Note: To enable JPEG support, you need to build and install the IJG JPEG library before building the Python Imaging
Library. See the distribution README for details.
JPEG 2000
28 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
supports JPEG 2000 raw codestreams (.j2k files), as well as boxed JPEG 2000 files (.j2p or .jpx files). Pillow
does not support files whose components have different sampling frequencies.
When loading, if you set the mode on the image prior to the load() method being invoked, you can ask Pillow
to convert the image to either RGB or RGBA rather than choosing for itself. It is also possible to set reduce to the
number of resolutions to discard (each one reduces the size of the resulting image by a factor of 2), and layers to
specify the number of quality layers to load.
The save() method supports the following options:
offset The image offset, as a tuple of integers, e.g. (16, 16)
tile_offset The tile offset, again as a 2-tuple of integers.
tile_size The tile size as a 2-tuple. If not specified, or if set to None, the image will be saved without tiling.
quality_mode Either "rates" or "dB" depending on the units you want to use to specify image quality.
quality_layers A sequence of numbers, each of which represents either an approximate size reduction (if quality
mode is "rates") or a signal to noise ratio value in decibels. If not specified, defaults to a single layer of full
quality.
num_resolutions The number of different image resolutions to be stored (which corresponds to the number of Dis-
crete Wavelet Transform decompositions plus one).
codeblock_size The code-block size as a 2-tuple. Minimum size is 4 x 4, maximum is 1024 x 1024, with the additional
restriction that no code-block may have more than 4096 coefficients (i.e. the product of the two numbers must
be no greater than 4096).
precinct_size The precinct size as a 2-tuple. Must be a power of two along both axes, and must be greater than the
code-block size.
irreversible If True, use the lossy Irreversible Color Transformation followed by DWT 9-7. Defaults to False,
which means to use the Reversible Color Transformation with DWT 5-3.
progression Controls the progression order; must be one of "LRCP", "RLCP", "RPCL", "PCRL", "CPRL". The
letters stand for Component, Position, Resolution and Layer respectively and control the order of encoding, the
idea being that e.g. an image encoded using LRCP mode can have its quality layers decoded as they arrive at
the decoder, while one encoded using RLCP mode will have increasing resolutions decoded as they arrive, and
so on.
cinema_mode Set the encoder to produce output compliant with the digital cinema specifications. The op-
tions here are "no" (the default), "cinema2k-24" for 24fps 2K, "cinema2k-48" for 48fps 2K, and
"cinema4k-24" for 24fps 4K. Note that for compliant 2K files, at least one of your image dimensions must
match 2048 x 1080, while for compliant 4K files, at least one of the dimensions must match 4096 x 2160.
Note: To enable JPEG 2000 support, you need to build and install the OpenJPEG library, version 2.0.0 or higher,
before building the Python Imaging Library.
Windows users can install the OpenJPEG binaries available on the OpenJPEG website, but must add them to their
PATH in order to use Pillow (if you fail to do this, you will get errors about not being able to load the _imaging
DLL).
MSP
Pillow identifies and reads MSP files from Windows 1 and 2. The library writes uncompressed (Windows 1) versions
of this format.
2.4. Appendices 29
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
PCX
PNG
Pillow identifies, reads, and writes PNG files containing 1, L, LA, I, P, RGB or RGBA data. Interlaced files are
supported as of v1.1.7.
As of Pillow 6.0, EXIF data can be read from PNG images. However, unlike other image formats, EXIF data is not
guaranteed to be present in info until load() has been called.
The open() method sets the following info properties, when appropriate:
chromaticity The chromaticity points, as an 8 tuple of floats. (White Point X, White Point Y, Red X, Red
Y, Green X, Green Y, Blue X, Blue Y)
gamma Gamma, given as a floating point number.
srgb The sRGB rendering intent as an integer.
• 0 Perceptual
• 1 Relative Colorimetric
• 2 Saturation
• 3 Absolute Colorimetric
transparency For P images: Either the palette index for full transparent pixels, or a byte string with alpha values for
each palette entry.
For 1, L, I and RGB images, the color that represents full transparent pixels in this image.
This key is omitted if the image is not a transparent palette image.
open also sets Image.text to a dictionary of the values of the tEXt, zTXt, and iTXt chunks of the PNG image.
Individual compressed chunks are limited to a decompressed size of PngImagePlugin.MAX_TEXT_CHUNK, by
default 1MB, to prevent decompression bombs. Additionally, the total size of all of the text chunks is limited to
PngImagePlugin.MAX_TEXT_MEMORY, defaulting to 64MB.
The save() method supports the following options:
optimize If present and true, instructs the PNG writer to make the output file as small as possible. This includes extra
processing in order to find optimal encoder settings.
transparency For P, 1, L, I, and RGB images, this option controls what color from the image to mark as transparent.
For P images, this can be a either the palette index, or a byte string with alpha values for each palette entry.
dpi A tuple of two numbers corresponding to the desired dpi in each direction.
pnginfo A PIL.PngImagePlugin.PngInfo instance containing text tags.
compress_level ZLIB compression level, a number between 0 and 9: 1 gives best speed, 9 gives best compression, 0
gives no compression at all. Default is 6. When optimize option is True compress_level has no effect
(it is set to 9 regardless of a value passed).
icc_profile The ICC Profile to include in the saved file.
exif The exif data to include in the saved file.
New in version 6.0.0.
30 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
bits (experimental) For P images, this option controls how many bits to store. If omitted, the PNG writer uses 8 bits
(256 colors).
dictionary (experimental) Set the ZLIB encoder dictionary.
Note: To enable PNG support, you need to build and install the ZLIB compression library before building the Python
Imaging Library. See the installation documentation for details.
APNG sequences
The PNG loader includes limited support for reading and writing Animated Portable Network Graphics (APNG)
files. When an APNG file is loaded, get_format_mimetype() will return "image/apng". The value of
the is_animated property will be True when the n_frames property is greater than 1. For APNG files, the
n_frames property depends on both the animation frame count as well as the presence or absence of a default image.
See the default_image property documentation below for more details. The seek() and tell() methods are
supported.
im.seek() raises an EOFError if you try to seek after the last frame.
These info properties will be set for APNG frames, where applicable:
default_image Specifies whether or not this APNG file contains a separate default image, which is not a part of the
actual APNG animation.
When an APNG file contains a default image, the initially loaded image (i.e. the result of seek(0)) will be
the default image. To account for the presence of the default image, the n_frames property will be set to
frame_count + 1, where frame_count is the actual APNG animation frame count. To load the first
APNG animation frame, seek(1) must be called.
• True - The APNG contains default image, which is not an animation frame.
• False - The APNG does not contain a default image. The n_frames property will be set to the ac-
tual APNG animation frame count. The initially loaded image (i.e. seek(0)) will be the first APNG
animation frame.
loop The number of times to loop this APNG, 0 indicates infinite looping.
duration The time to display this APNG frame (in milliseconds).
Note: The APNG loader returns images the same size as the APNG file’s logical screen size. The returned image
contains the pixel data for a given frame, after applying any APNG frame disposal and frame blend operations (i.e. it
contains what a web browser would render for this frame - the composite of all previous frames and this frame).
Any APNG file containing sequence errors is treated as an invalid image. The APNG loader will not attempt to repair
and reorder files containing sequence errors.
Saving
When calling save(), by default only a single frame PNG file will be saved. To save an APNG file (including a
single frame APNG), the save_all parameter must be set to True. The following parameters can also be set:
default_image Boolean value, specifying whether or not the base image is a default image. If True, the base image
will be used as the default image, and the first image from the append_images sequence will be the first
2.4. Appendices 31
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
APNG animation frame. If False, the base image will be used as the first APNG animation frame. Defaults to
False.
append_images A list or tuple of images to append as additional frames. Each of the images in the list can be single
or multiframe images. The size of each frame should match the size of the base image. Also note that if a
frame’s mode does not match that of the base image, the frame will be converted to the base image mode.
loop Integer number of times to loop this APNG, 0 indicates infinite looping. Defaults to 0.
duration Integer (or list or tuple of integers) length of time to display this APNG frame (in milliseconds). Defaults
to 0.
disposal An integer (or list or tuple of integers) specifying the APNG disposal operation to be used for this frame
before rendering the next frame. Defaults to 0.
• 0 (APNG_DISPOSE_OP_NONE, default) - No disposal is done on this frame before rendering the next
frame.
• 1 (PIL.PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND) - This frame’s modified region is
cleared to fully transparent black before rendering the next frame.
• 2 (APNG_DISPOSE_OP_PREVIOUS) - This frame’s modified region is reverted to the previous frame’s
contents before rendering the next frame.
blend An integer (or list or tuple of integers) specifying the APNG blend operation to be used for this frame before
rendering the next frame. Defaults to 0.
• 0 (APNG_BLEND_OP_SOURCE) - All color components of this frame, including alpha, overwrite the
previous output image contents.
• 1 (APNG_BLEND_OP_OVER) - This frame should be alpha composited with the previous output image
contents.
Note: The duration, disposal and blend parameters can be set to lists or tuples to specify values for each
individual frame in the animation. The length of the list or tuple must be identical to the total number of actual frames
in the APNG animation. If the APNG contains a default image (i.e. default_image is set to True), these list or
tuple parameters should not include an entry for the default image.
PPM
Pillow reads and writes PBM, PGM, PPM and PNM files containing 1, L or RGB data.
SGI
SPIDER
Pillow reads and writes SPIDER image files of 32-bit floating point data (“F;32F”).
Pillow also reads SPIDER stack files containing sequences of SPIDER images. The seek() and tell() methods
are supported, and random access is allowed.
The open() method sets the following attributes:
format Set to SPIDER
32 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
The extension of SPIDER files may be any 3 alphanumeric characters. Therefore the output format must be specified
explicitly:
im.save('newimage.spi', format='SPIDER')
For more information about the SPIDER image processing package, see the SPIDER homepage at Wadsworth Center.
TGA
Pillow reads and writes TGA images containing L, LA, P, RGB, and RGBA data. Pillow can read and write both
uncompressed and run-length encoded TGAs.
TIFF
Pillow reads and writes TIFF files. It can read both striped and tiled images, pixel and plane interleaved multi-band
images. If you have libtiff and its headers installed, Pillow can read and write many kinds of compressed TIFF files.
If not, Pillow will only read and write uncompressed files.
Note: Beginning in version 5.0.0, Pillow requires libtiff to read or write compressed files. Prior to that release, Pillow
had buggy support for reading Packbits, LZW and JPEG compressed TIFFs without using libtiff.
2.4. Appendices 33
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
The TIFF loader supports the seek() and tell() methods, taking and returning frame numbers within the im-
age file. You can combine these methods to seek to the next frame (im.seek(im.tell() + 1)). Frames are
numbered from 0 to im.num_frames - 1, and can be accessed in any order.
im.seek() raises an EOFError if you try to seek after the last frame.
34 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
date_time
artist
copyright Strings
resolution_unit An integer. 1 for no unit, 2 for inches and 3 for centimeters.
resolution Either an integer or a float, used for both the x and y resolution.
x_resolution Either an integer or a float.
y_resolution Either an integer or a float.
dpi A tuple of (x_resolution, y_resolution), with inches as the resolution unit. For consistency with other image
formats, the x and y resolutions of the dpi will be rounded to the nearest integer.
WebP
Pillow reads and writes WebP files. The specifics of Pillow’s capabilities with this format are currently undocumented.
The save() method supports the following options:
lossless If present and true, instructs the WebP writer to use lossless compression.
quality Integer, 1-100, Defaults to 80. For lossy, 0 gives the smallest size and 100 the largest. For lossless, this
parameter is the amount of effort put into the compression: 0 is the fastest, but gives larger files compared to the
slowest, but best, 100.
method Quality/speed trade-off (0=fast, 6=slower-better). Defaults to 0.
icc_profile The ICC Profile to include in the saved file. Only supported if the system WebP library was built with
webpmux support.
exif The exif data to include in the saved file. Only supported if the system WebP library was built with webpmux
support.
Saving sequences
Note: Support for animated WebP files will only be enabled if the system WebP library is v0.5.0 or later. You can
check webp animation support at runtime by calling features.check("webp_anim").
When calling save() to write a WebP file, the following options are available when the save_all argument is
present and true.
append_images A list of images to append as additional frames. Each of the images in the list can be single or
multiframe images.
duration The display duration of each frame, in milliseconds. Pass a single integer for a constant duration, or a list
or tuple to set the duration for each frame separately.
loop Number of times to repeat the animation. Defaults to [0 = infinite].
background Background color of the canvas, as an RGBA tuple with values in the range of (0-255).
minimize_size If true, minimize the output size (slow). Implicitly disables key-frame insertion.
kmin, kmax Minimum and maximum distance between consecutive key frames in the output. The library may insert
some key frames as needed to satisfy this criteria. Note that these conditions should hold: kmax > kmin and
2.4. Appendices 35
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
kmin >= kmax / 2 + 1. Also, if kmax <= 0, then key-frame insertion is disabled; and if kmax == 1, then all
frames will be key-frames (kmin value does not matter for these special cases).
allow_mixed If true, use mixed compression mode; the encoder heuristically chooses between lossy and lossless for
each frame.
XBM
Read-only formats
BLP
BLP is the Blizzard Mipmap Format, a texture format used in World of Warcraft. Pillow supports reading JPEG
Compressed or raw BLP1 images, and all types of BLP2 images.
CUR
CUR is used to store cursors on Windows. The CUR decoder reads the largest available cursor. Animated cursors are
not supported.
DCX
DCX is a container file format for PCX files, defined by Intel. The DCX format is commonly used in fax applications.
The DCX decoder can read files containing 1, L, P, or RGB data.
When the file is opened, only the first image is read. You can use seek() or ImageSequence to read other images.
DDS
DDS is a popular container texture format used in video games and natively supported by DirectX. Currently, uncom-
pressed RGB data and DXT1, DXT3, and DXT5 pixel formats are supported, and only in RGBA mode.
New in version 3.4.0: DXT3
FLI, FLC
FPX
Pillow reads Kodak FlashPix files. In the current version, only the highest resolution image is read from the file, and
the viewing transform is not taken into account.
36 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Note: To enable full FlashPix support, you need to build and install the IJG JPEG library before building the Python
Imaging Library. See the distribution README for details.
FTEX
GBR
GD
Pillow reads uncompressed GD2 files. Note that you must use PIL.GdImageFile.open() to read such a file.
The open() method sets the following info properties:
transparency Transparency color index. This key is omitted if the image is not transparent.
IMT
IPTC/NAA
MCIDAS
MIC
Pillow identifies and reads Microsoft Image Composer (MIC) files. When opened, the first sprite in the file is loaded.
You can use seek() and tell() to read other sprites from the file.
Note that there may be an embedded gamma of 2.2 in MIC files.
2.4. Appendices 37
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
MPO
Pillow identifies and reads Multi Picture Object (MPO) files, loading the primary image when first opened. The
seek() and tell() methods may be used to read other pictures from the file. The pictures are zero-indexed and
random access is supported.
PCD
Pillow reads PhotoCD files containing RGB data. This only reads the 768x512 resolution image from the file. Higher
resolutions are encoded in a proprietary encoding.
PIXAR
Pillow provides limited support for PIXAR raster files. The library can identify and read “dumped” RGB files.
The format code is PIXAR.
PSD
Pillow identifies and reads PSD files written by Adobe Photoshop 2.5 and 3.0.
WAL
WMF
class WmfHandler:
def open(self, im):
...
def load(self, im):
(continues on next page)
38 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
wmf_handler = WmfHandler()
WmfImagePlugin.register_handler(wmf_handler)
im = Image.open("sample.wmf")
XPM
Write-only formats
PALM
Pillow can write PDF (Acrobat) images. Such images are written as binary PDF 1.4 files, using either JPEG or HEX
encoding depending on the image mode (and whether JPEG support is available or not).
The save() method can take the following keyword arguments:
save_all If a multiframe image is used, by default, only the first image will be saved. To save all frames, each frame
to a separate page of the PDF, the save_all parameter must be present and set to True.
New in version 3.0.0.
append_images A list of images to append as additional pages. Each of the images in the list can be single or
multiframe images.
New in version 4.2.0.
append Set to True to append pages to an existing PDF file. If the file doesn’t exist, an OSError will be raised.
New in version 5.1.0.
resolution Image resolution in DPI. This, together with the number of pixels in the image, will determine the physical
dimensions of the page that will be saved in the PDF.
title The document’s title. If not appending to an existing PDF file, this will default to the filename.
New in version 5.1.0.
author The name of the person who created the document.
New in version 5.1.0.
2.4. Appendices 39
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
XV Thumbnails
Identify-only formats
BUFR
FITS
GRIB
40 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
HDF5
MPEG
The Pillow uses a plug-in model which allows you to add your own decoders to the library, without any changes to the
library itself. Such plug-ins usually have names like XxxImagePlugin.py, where Xxx is a unique format name
(usually an abbreviation).
Warning: Pillow >= 2.1.0 no longer automatically imports any file in the Python path with a name ending in
ImagePlugin.py. You will need to import your image plugin manually.
Note: For performance reasons, it is important that the _open() method quickly rejects files that do not have the
appropriate contents.
Example
The following plug-in supports a simple format, which has a 128-byte header consisting of the words “SPAM” fol-
lowed by the width, height, and pixel size in bits. The header fields are separated by spaces. The image data follows
directly after the header, and can be either bi-level, greyscale, or 24-bit true color.
SpamImagePlugin.py:
2.4. Appendices 41
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
def _accept(prefix):
return prefix[:4] == b"SPAM"
class SpamImageFile(ImageFile.ImageFile):
format = "SPAM"
format_description = "Spam raster image"
def _open(self):
header = self.fp.read(128).split()
# mode setting
bits = int(header[3])
if bits == 1:
self.mode = "1"
elif bits == 8:
self.mode = "L"
elif bits == 24:
self.mode = "RGB"
else:
raise SyntaxError("unknown number of bits")
# data descriptor
self.tile = [
("raw", (0, 0) + self.size, 128, (self.mode, 0, 1))
]
Image.register_extension(SpamImageFile.format, ".spam")
Image.register_extension(SpamImageFile.format, ".spa") # dos version
The format handler must always set the size and mode attributes. If these are not set, the file cannot be opened.
To simplify the plugin, the calling code considers exceptions like SyntaxError, KeyError, IndexError,
EOFError and struct.error as a failure to identify the file.
Note that the image plugin must be explicitly registered using PIL.Image.register_open(). Although not
required, it is also a good idea to register any extensions used by this format.
To be able to read the file as well as just identifying it, the tile attribute must also be set. This attribute consists of
a list of tile descriptors, where each descriptor specifies how data should be loaded to a given region in the image. In
most cases, only a single descriptor is used, covering the full image.
The tile descriptor is a 4-tuple with the following contents:
42 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
2.4.3 Decoders
The raw decoder is used to read uncompressed data from an image file. It can be used with most uncompressed file
formats, such as PPM, BMP, uncompressed TIFF, and many others. To use the raw decoder with the PIL.Image.
frombytes() function, use the following syntax:
image = Image.frombytes(
mode, size, data, "raw",
raw mode, stride, orientation
)
When used in a tile descriptor, the parameter field should look like:
2.4. Appendices 43
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
mode description
1 1-bit bilevel, stored with the leftmost pixel in the most significant bit. 0 means black, 1 means white.
1;I 1-bit inverted bilevel, stored with the leftmost pixel in the most significant bit. 0 means white, 1 means
black.
1;R 1-bit reversed bilevel, stored with the leftmost pixel in the least significant bit. 0 means black, 1 means
white.
L 8-bit greyscale. 0 means black, 255 means white.
L;I 8-bit inverted greyscale. 0 means white, 255 means black.
P 8-bit palette-mapped image.
RGB 24-bit true colour, stored as (red, green, blue).
BGR 24-bit true colour, stored as (blue, green, red).
RGBX 24-bit true colour, stored as (red, green, blue, pad). The pad pixels may vary.
RGB; 24-bit true colour, line interleaved (first all red pixels, then all green pixels, finally all blue pixels).
L
Note that for the most common cases, the raw mode is simply the same as the mode.
The Python Imaging Library supports many other decoders, including JPEG, PNG, and PackBits. For details, see the
decode.c source file, and the standard plug-in implementations provided with the library.
PIL provides some special mechanisms to allow you to load a wide variety of formats into a mode F (floating point)
image memory.
You can use the raw decoder to read images where data is packed in any standard machine data type, using one of the
following raw modes:
mode description
F 32-bit native floating point.
F;8 8-bit unsigned integer.
F;8S 8-bit signed integer.
F;16 16-bit little endian unsigned integer.
F;16S 16-bit little endian signed integer.
F;16B 16-bit big endian unsigned integer.
F;16BS 16-bit big endian signed integer.
F;16N 16-bit native unsigned integer.
F;16NS 16-bit native signed integer.
F;32 32-bit little endian unsigned integer.
F;32S 32-bit little endian signed integer.
F;32B 32-bit big endian unsigned integer.
F;32BS 32-bit big endian signed integer.
F;32N 32-bit native unsigned integer.
F;32NS 32-bit native signed integer.
F;32F 32-bit little endian floating point.
F;32BF 32-bit big endian floating point.
F;32NF 32-bit native floating point.
F;64F 64-bit little endian floating point.
F;64BF 64-bit big endian floating point.
F;64NF 64-bit native floating point.
44 Chapter 2. Handbook
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
If the raw decoder cannot handle your format, PIL also provides a special “bit” decoder that can be used to read various
packed formats into a floating point image memory.
To use the bit decoder with the PIL.Image.frombytes() function, use the following syntax:
image = Image.frombytes(
mode, size, data, "bit",
bits, pad, fill, sign, orientation
)
When used in a tile descriptor, the parameter field should look like:
Setup
The current conventions are that the decoder setup function is named PyImaging_[Decodername]DecoderNew
and defined in decode.c. The python binding for it is named [decodername]_decoder and is setup from
within the _imaging.c file in the codecs section of the function array.
The setup function needs to call PyImaging_DecoderNew and at the very least, set the decode function pointer.
The fields of interest in this object are:
2.4. Appendices 45
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
decode Function pointer to the decode function, which has access to im, state, and the buffer of data to be added
to the image.
cleanup Function pointer to the cleanup function, has access to state.
im The target image, will be set by Pillow.
state An ImagingCodecStateInstance, will be set by Pillow. The context member is an opaque struct that can be used
by the decoder to store any format specific state or options.
pulls_fd EXPERIMENTAL – WARNING, interface may change. If set to 1, state->fd will be a pointer to the
Python file like object. The decoder may use the functions in codec_fd.c to read directly from the file like
object rather than have the data pushed through a buffer. Note that this implementation may be refactored until
this warning is removed.
New in version 3.3.0.
Decoding
The decode function is called with the target (core) image, the decoder state structure, and a buffer of data to be
decoded.
Experimental – If pulls_fd is set, then the decode function is called once, with an empty buffer. It is the decoder’s
responsibility to decode the entire tile in that one call. The rest of this section only applies if pulls_fd is not set.
It is the decoder’s responsibility to pull as much data as possible out of the buffer and return the number of bytes
consumed. The next call to the decoder will include the previous unconsumed tail. The decoder function will be called
multiple times as the data is read from the file like object.
If an error occurs, set state->errcode and return -1.
Return -1 on success, without setting the errcode.
Cleanup
The cleanup function is called after the decoder returns a negative value, or if there is a read error from the file. This
function should free any allocated memory and release any resources from external libraries.
Python file decoders should derive from PIL.ImageFile.PyDecoder and should at least override the decode
method. File decoders should be registered using PIL.Image.register_decoder(). As in the C implementa-
tion of the file decoders, there are three stages in the lifetime of a Python-based file decoder:
1. Setup: Pillow looks for the decoder in the registry, then instantiates the class.
2. Decoding: The decoder instance’s decode method is repeatedly called with a buffer of data to be interpreted.
3. Cleanup: The decoder instance’s cleanup method is called.
46 Chapter 2. Handbook
CHAPTER 3
Reference
The Image module provides a class with the same name which is used to represent a PIL image. The module also
provides a number of factory functions, including functions to load images from files, and to create new images.
3.1.1 Examples
The following script loads an image, rotates it 45 degrees, and displays it using an external viewer (usually xv on Unix,
and the Paint program on Windows).
Create thumbnails
The following script creates nice thumbnails of all JPEG images in the current directory preserving aspect ratios with
128x128 max resolution.
47
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
3.1.2 Functions
PIL.Image.open(fp, mode=’r’)
Opens and identifies the given image file.
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 load() method). See new(). See File Handling
in Pillow.
Parameters
• fp – A filename (string), pathlib.Path object or a file object. The file object must implement
read(), seek(), and tell() methods, and be opened in binary mode.
• mode – The mode. If given, this argument must be “r”.
Returns An Image object.
Raises
• FileNotFoundError – If the file cannot be found.
• PIL.UnidentifiedImageError – If the image cannot be opened and identified.
• ValueError – If the mode is not “r”, or if a StringIO instance is used for fp.
Warning: To protect against potential DOS attacks caused by “decompression bombs” (i.e. mali-
cious files which decompress into a huge amount of data and are designed to crash or cause disrup-
tion by using up a lot of memory), Pillow will issue a DecompressionBombWarning if the im-
age is over a certain limit. If desired, the warning can be turned into an error with warnings.
simplefilter('error', Image.DecompressionBombWarning) or suppressed entirely with
warnings.simplefilter('ignore', Image.DecompressionBombWarning). See also the
logging documentation to have warnings output to the logging facility instead of stderr.
Image processing
PIL.Image.alpha_composite(im1, im2)
Alpha composite im2 over im1.
Parameters
• im1 – The first image. Must have mode RGBA.
• im2 – The second image. Must have mode RGBA, and the same size as the first image.
Returns An Image object.
PIL.Image.blend(im1, im2, alpha)
Creates a new image by interpolating between two input images, using a constant alpha.:
Parameters
48 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Constructing images
PIL.Image.fromarray(obj, mode=None)
Creates an image memory from an object exporting the array interface (using the buffer protocol).
If obj is not contiguous, then the tobytes method is called and frombuffer() is used.
If you have an image in NumPy:
im = Image.fromarray(a)
Parameters
• obj – Object with array interface
• mode – Mode to use (will be determined from type if None) See: Modes.
Returns An image object.
50 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
warning if you do this; to disable the warning, you should provide the full set of parameters. See below for
details.
Parameters
• mode – The image mode. See: Modes.
• size – The image size.
• data – A bytes or other buffer object containing raw data for the given mode.
• decoder_name – What decoder to use.
• args – Additional parameters for the given decoder. For the default encoder (“raw”), it’s
recommended that you provide the full set of parameters:
Registering plugins
Note: These functions are for use by plugin authors. Application authors can ignore them.
class PIL.Image.Image
This class represents an image object. To create Image objects, use the appropriate factory functions. There’s
hardly ever any reason to call the Image constructor directly.
• open()
• new()
• frombytes()
An instance of the Image class has the following methods. Unless otherwise stated, all methods return a new instance
of the Image class, holding the resulting image.
Image.alpha_composite(im, dest=(0, 0), source=(0, 0))
‘In-place’ analog of Image.alpha_composite. Composites an image onto this image.
Parameters
• im – image to composite over this one
• dest – Optional 2 tuple (left, top) specifying the upper left corner in this (destination)
image.
• source – Optional 2 (left, top) tuple for the upper left corner in the overlay source image,
or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle
Performance Note: Not currently implemented in-place in the core layer.
Image.convert(mode=None, matrix=None, dither=None, palette=0, colors=256)
Returns a converted copy of this image. For the “P” mode, this method translates pixels through the palette. If
mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without
a palette.
The current version supports all possible conversions between “L”, “RGB” and “CMYK.” The matrix argument
only supports “L” and “RGB”.
When translating a color image to greyscale (mode “L”), the library uses the ITU-R 601-2 luma transform:
52 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
The default method of converting a greyscale (“L”) or “RGB” image into a bilevel (mode “1”) image uses Floyd-
Steinberg dither to approximate the original image luminosity levels. If dither is NONE, all values larger than
128 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the point() method.
When converting from “RGBA” to “P” without a matrix argument, this passes the operation to quantize(),
and dither and palette are ignored.
Parameters
• mode – The requested mode. See: Modes.
• matrix – An optional conversion matrix. If given, this should be 4- or 12-tuple containing
floating point values.
• dither – Dithering method, used when converting from mode “RGB” to “P” or from
“RGB” or “L” to “1”. Available methods are NONE or FLOYDSTEINBERG (default).
Note that this is not used when matrix is supplied.
• palette – Palette to use when converting from mode “RGB” to “P”. Available palettes
are WEB or ADAPTIVE.
• colors – Number of colors to use for the ADAPTIVE palette. Defaults to 256.
Return type Image
Returns An Image object.
The following example converts an RGB image (linearly calibrated according to ITU-R 709, using the D65 luminant)
to the CIE XYZ color space:
rgb2xyz = (
0.412453, 0.357580, 0.180423, 0,
0.212671, 0.715160, 0.072169, 0,
0.019334, 0.119193, 0.950227, 0)
out = im.convert("RGB", rgb2xyz)
Image.copy()
Copies this image. Use this method if you wish to paste things into an image, but still retain the original.
Return type Image
Returns An Image object.
Image.crop(box=None)
Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel
coordinate. See Coordinate System.
Note: Prior to Pillow 3.4.0, this was a lazy operation.
Parameters box – The crop rectangle, as a (left, upper, right, lower)-tuple.
Return type Image
Returns An Image object.
This crops the input image with the provided coordinates:
from PIL import Image
im = Image.open("hopper.jpg")
# Here the image "im" is cropped and assigned to new variable im_crop
im_crop = im.crop((left, upper, right, lower))
Image.draft(mode, size)
Configures the image file loader so it returns a version of the image that as closely as possible matches the given
mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it.
If any changes are made, returns a tuple with the chosen mode and box with coordinates of the original image
within the altered one.
Note that this method modifies the Image object in place. If the image has already been loaded, this method
has no effect.
Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO
images.
Parameters
• mode – The requested mode.
• size – The requested size.
Image.filter(filter)
Filters this image using the given filter. For a list of available filters, see the ImageFilter module.
Parameters filter – Filter kernel.
Returns An Image object.
This blurs the input image using a filter from the ImageFilter module:
im = Image.open("hopper.jpg")
Image.getbands()
Returns a tuple containing the name of each band in this image. For example, getbands on an RGB image
returns (“R”, “G”, “B”).
Returns A tuple containing band names.
Return type tuple
This helps to get the bands of the input image:
im = Image.open("hopper.jpg")
print(im.getbands()) # Returns ('R', 'G', 'B')
Image.getbbox()
Calculates the bounding box of the non-zero regions in the image.
54 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Returns The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel
coordinate. See Coordinate System. If the image is completely empty, this method returns None.
This helps to get the bounding box coordinates of the input image:
from PIL import Image
im = Image.open("hopper.jpg")
print(im.getbbox())
# Returns four coordinates in the format (left, upper, right, lower)
Image.getcolors(maxcolors=256)
Returns a list of colors used in this image.
Parameters 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.
Image.getdata(band=None)
Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened,
so that values for line one follow directly after the values of line zero, and so on.
Note that the sequence object returned by this method is an internal PIL data type, which only supports certain
sequence operations. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata()).
Parameters 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.
Image.getextrema()
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.
Image.getexif()
Image.getpalette()
Returns the image palette as a list.
Returns A list of color values [r, g, b, . . . ], or None if the image has no palette.
Image.getpixel(xy)
Returns the pixel value at a given position.
Parameters xy – The coordinate, given as (x, y). See Coordinate System.
Returns The pixel value. If the image is a multi-layer image, this method returns a tuple.
Image.histogram(mask=None, extrema=None)
Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value
in the source image. If the image has more than one band, the histograms for all bands are concatenated (for
example, the histogram for an “RGB” image contains 768 values).
A bilevel image (mode “1”) is treated as a greyscale (“L”) image by this method.
If a mask is provided, the method returns a histogram for those parts of the image where the mask image is
non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode “1”) or
a greyscale image (“L”).
Parameters
• mask – An optional mask.
56 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
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.
Parameters
• data – A sequence object.
• scale – An optional scale value. The default is 1.0.
• offset – An optional offset value. The default is 0.0.
Image.putpalette(data, rawmode=’RGB’)
Attaches a palette to this image. The image must be a “P”, “PA”, “L” or “LA” 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.
Parameters
• data – A palette sequence (either a list or a string).
• rawmode – The raw mode of the palette.
Image.putpixel(xy, value)
Modifies the pixel at the given position. The color is given as a single numerical value for single-band images,
and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P images.
Note that this method is relatively slow. For more extensive changes, use paste() or the ImageDraw module
instead.
See:
• paste()
• putdata()
• ImageDraw
Parameters
• xy – The pixel coordinate, given as (x, y). See Coordinate System.
• value – The pixel value.
im = Image.open("hopper.jpg")
Image.remap_palette(dest_map, source_palette=None)
Rewrites the image to reorder the palette.
Parameters
• dest_map – A list of indexes into the original palette. e.g. [1,0] would swap a two item
palette, and list(range(256)) is the identity transform.
• source_palette – Bytes or None.
Returns An Image object.
Image.rotate(angle, resample=0, expand=0, center=None, translate=None, fillcolor=None)
Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of
degrees counter clockwise around its centre.
Parameters
• angle – In degrees counter clockwise.
• resample – An optional resampling filter. This can be one of PIL.Image.NEAREST
(use nearest neighbour), PIL.Image.BILINEAR (linear interpolation in a 2x2 environ-
ment), or PIL.Image.BICUBIC (cubic spline interpolation in a 4x4 environment). If
omitted, or if the image has mode “1” or “P”, it is set to PIL.Image.NEAREST. See
Filters.
• expand – Optional expansion flag. If true, expands the output image to make it large
enough to hold the entire rotated image. If false or omitted, make the output image the same
size as the input image. Note that the expand flag assumes rotation around the center and no
translation.
58 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
• center – Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is
the center of the image.
• translate – An optional post-rotate translation (a 2-tuple).
• fillcolor – An optional color for area outside the rotated image.
Returns An Image object.
This rotates the input image by theta degrees counter clockwise:
im = Image.open("hopper.jpg")
On Unix, the image is then opened using the display, eog or xv utility, depending on which one can be found.
On macOS, the image is opened with the native Preview application.
On Windows, the image is opened with the standard PNG display utility.
Parameters
• title – Optional title to use for the image window, where possible.
• command – command used to show the image
Image.split()
Split this image into individual bands. This method returns a tuple of individual image bands from an image.
For example, splitting an “RGB” image creates three new images each containing a copy of one of the original
bands (red, green, blue).
If you need only one band, getchannel() method can be more convenient and faster.
Returns A tuple containing bands.
Image.getchannel(channel)
Returns an image containing a single channel of the source image.
Parameters channel – What channel to return. Could be index (0 for “R” channel of “RGB”) or
channel name (“A” for alpha channel of “RGBA”).
Returns An image in “L” mode.
New in version 4.3.0.
Image.tell()
Returns the current frame number. See seek().
Returns Frame number, starting with 0.
Image.thumbnail(size, resample=3, reducing_gap=2.0)
Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no
larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the
image, calls the draft() method to configure the file reader (where applicable), and finally resizes the image.
Note that this function modifies the Image object in place. If you need to use the full resolution image as well,
apply this method to a copy() of the original image.
Parameters
• size – Requested size.
• resample – Optional resampling filter. This can be one of PIL.Image.NEAREST,
PIL.Image.BILINEAR, PIL.Image.BICUBIC, or PIL.Image.LANCZOS. If
omitted, it defaults to PIL.Image.BICUBIC. (was PIL.Image.NEAREST prior to ver-
sion 2.5.0). See: Filters.
• reducing_gap – Apply optimization by resizing the image in two steps. First, reducing
the image by integer times using reduce() or draft() for JPEG images. Second, resiz-
ing using regular resampling. The last step changes size no less than by reducing_gap
times. reducing_gap may be None (no first step is performed) or should be greater than
1.0. The bigger reducing_gap, the closer the result to the fair resampling. The smaller
reducing_gap, the faster resizing. With reducing_gap greater or equal to 3.0, the
result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very
close to fair resampling while still being faster in many cases).
Returns None
60 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Image.tobitmap(name=’image’)
Returns the image converted to an X11 bitmap.
Parameters 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”
Image.tobytes(encoder_name=’raw’, *args)
Return image as a bytes object.
Warning: This method returns the raw image data from the internal storage. For compressed image data
(e.g. PNG, JPEG) use save(), with a BytesIO parameter for in-memory data.
Parameters
• encoder_name – What encoder to use. The default is to use the standard “raw” encoder.
• args – Extra arguments to the encoder.
Return type A bytes object.
Image.tostring(*args, **kw)
Image.transform(size, method, data=None, resample=0, fill=1, fillcolor=None)
Transforms this image. This method creates a new image with the given size, and the same mode as the original,
and copies data to the new image using the given transform.
Parameters
• size – The output size.
• method – The transformation method. This is one of PIL.Image.EXTENT (cut
out a rectangular subregion), PIL.Image.AFFINE (affine transform), PIL.Image.
PERSPECTIVE (perspective transform), PIL.Image.QUAD (map a quadrilateral to a
rectangle), or PIL.Image.MESH (map a number of source quadrilaterals in one opera-
tion).
It may also be an ImageTransformHandler object:
class Example(Image.ImageTransformHandler):
def transform(size, method, data, resample, fill=1):
# Return result
It may also be an object with a getdata() method that returns a tuple supplying new
method and data values:
class Example:
def getdata(self):
method = Image.EXTENT
data = (0, 0, 100, 100)
return method, data
im = Image.open("hopper.jpg")
Image.verify()
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.
Image.fromstring(*args, **kw)
Image.load()
Allocates storage for the image and loads the pixel data. In normal cases, you don’t need to call this method,
since the Image class automatically loads an opened image when it is accessed for the first time.
If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is
if the image has multiple frames, in which case the file will be left open for seek operations. See File Handling
in Pillow for more information.
Returns An image access object.
Return type PixelAccess Class or PIL.PyAccess
Image.close()
Closes the file pointer, if possible.
This operation will destroy the image core and release its memory. The image data will be unusable afterward.
This function is only required to close images that have not had their file read and closed by the load()
method. See File Handling in Pillow for more information.
3.1.4 Attributes
62 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
PIL.Image.filename
The filename or path of the source file. Only images created with the factory function open have a filename
attribute. If the input is a file like object, the filename attribute is set to an empty string.
Type string
PIL.Image.format
The file format of the source file. For images created by the library itself (via a factory function, or by running
a method on an existing image), this attribute is set to None.
Type string or None
PIL.Image.mode
Image mode. This is a string specifying the pixel format used by the image. Typical values are “1”, “L”, “RGB”,
or “CMYK.” See Modes for a full list.
Type string
PIL.Image.size
Image size, in pixels. The size is given as a 2-tuple (width, height).
Type (width, height)
PIL.Image.width
Image width, in pixels.
Type int
PIL.Image.height
Image height, in pixels.
Type int
PIL.Image.palette
Colour palette table, if any. If mode is “P” or “PA”, this should be an instance of the ImagePalette class.
Otherwise, it should be set to None.
Type ImagePalette or None
PIL.Image.info
A dictionary holding data associated with the image. This dictionary is used by file handlers to pass on various
non-image information read from the file. See documentation for the various file handlers for details.
Most methods ignore the dictionary when returning new images; since the keys are not standardized, it’s not
possible for a method to know if the operation affects the dictionary. If you need the information later on, keep
a reference to the info dictionary returned from the open method.
Unless noted elsewhere, this dictionary does not affect saving files.
Type dict
The ImageChops module contains a number of arithmetical image operations, called channel operations (“chops”).
These can be used for various purposes, including special effects, image compositions, algorithmic painting, and more.
For more pre-made operations, see ImageOps.
At this time, most channel operations are only implemented for 8-bit images (e.g. “L” and “RGB”).
3.2.1 Functions
Most channel operations take one or two image arguments and returns a new image. Unless otherwise noted, the
result of a channel operation is always clipped to the range 0 to MAX (which is 255 for all modes supported by the
operations in this module).
PIL.ImageChops.add(image1, image2, scale=1.0, offset=0)
Adds two images, dividing the result by scale and adding the offset. If omitted, scale defaults to 1.0, and offset
to 0.0.
PIL.ImageChops.add_modulo(image1, image2)
Add two images, without clipping the result.
PIL.ImageChops.difference(image1, image2)
Returns the absolute value of the pixel-by-pixel difference between the two images.
PIL.ImageChops.duplicate(image)
Copy a channel. Alias for PIL.Image.Image.copy().
Return type Image
PIL.ImageChops.invert(image)
Invert an image (channel).
64 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
PIL.ImageChops.lighter(image1, image2)
Compares the two images, pixel by pixel, and returns a new image containing the lighter values.
PIL.ImageChops.logical_and(image1, image2)
Logical AND between two images.
Both of the images must have mode “1”. If you would like to perform a logical AND on an image with a mode
other than “1”, try multiply() instead, using a black-and-white mask as the second image.
PIL.ImageChops.logical_or(image1, image2)
Logical OR between two images.
Both of the images must have mode “1”.
PIL.ImageChops.logical_xor(image1, image2)
Logical XOR between two images.
Both of the images must have mode “1”.
PIL.ImageChops.multiply(image1, image2)
Superimposes two images on top of each other.
If you multiply an image with a solid black image, the result is black. If you multiply with a solid white image,
the image is unaffected.
PIL.ImageChops.soft_light(image1, image2)
Superimposes two images on top of each other using the Soft Light algorithm
Return type Image
PIL.ImageChops.hard_light(image1, image2)
Superimposes two images on top of each other using the Hard Light algorithm
Return type Image
PIL.ImageChops.overlay(image1, image2)
Superimposes two images on top of each other using the Overlay algorithm
Return type Image
PIL.ImageChops.offset(image, xoffset, yoffset=None)
Returns a copy of the image where data has been offset by the given distances. Data wraps around the edges. If
yoffset is omitted, it is assumed to be equal to xoffset.
PIL.ImageChops.screen(image1, image2)
Superimposes two inverted images on top of each other.
PIL.ImageChops.subtract_modulo(image1, image2)
Subtract two images, without clipping the result.
The ImageColor module contains color tables and converters from CSS3-style color specifiers to RGB tuples. This
module is used by PIL.Image.new() and the ImageDraw module, among others.
66 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
between 0% and 100% (gray=0%, full color=100%), and lightness is a value between 0% and 100% (black=0%,
normal=50%, white=100%). For example, hsl(0,100%,50%) is pure red.
• Hue-Saturation-Value (HSV) functions, given as hsv(hue, saturation%, value%) where hue and sat-
uration are the same as HSL, and value is between 0% and 100% (black=0%, normal=100%). For example,
hsv(0,100%,100%) is pure red. This format is also known as Hue-Saturation-Brightness (HSB), and can
be given as hsb(hue, saturation%, brightness%), where each of the values are used as they are in
HSV.
• Common HTML color names. The ImageColor module provides some 140 standard color names, based on
the colors supported by the X Window system and most web browsers. color names are case insensitive. For
example, red and Red both specify pure red.
3.3.2 Functions
PIL.ImageColor.getrgb(color)
Convert a color string to an RGB tuple. If the string cannot be parsed, this function raises a ValueError
exception.
New in version 1.1.4.
PIL.ImageColor.getcolor(color, mode)
Same as getrgb(), but converts the RGB value to a greyscale value if the mode is not color or a palette image.
If the string cannot be parsed, this function raises a ValueError exception.
New in version 1.1.4.
The ImageCms module provides color profile management support using the LittleCMS2 color management engine,
based on Kevin Cazabon’s PyCMS library.
class PIL.ImageCms.ImageCmsTransform(input, output, input_mode, output_mode, intent=0,
proof=None, proof_intent=3, flags=0)
Transform. This can be used with the procedural API, or with the standard Image.point() method.
Will return the output profile in the output.info[‘icc_profile’].
exception PIL.ImageCms.PyCMSError
(pyCMS) Exception class. This is used for all errors in the pyCMS API.
PIL.ImageCms.applyTransform(im, transform, inPlace=False)
(pyCMS) Applies a transform to a given image.
If im.mode != transform.inMode, a PyCMSError is raised.
If inPlace is True and transform.inMode != transform.outMode, a PyCMSError is raised.
If im.mode, transform.inMode, or transform.outMode is not supported by pyCMSdll or the profiles you used for
the transform, a PyCMSError is raised.
If an error occurs while the transform is being applied, a PyCMSError is raised.
This function applies a pre-calculated transform (from ImageCms.buildTransform() or Im-
ageCms.buildTransformFromOpenProfiles()) to an image. The transform can be used for multiple images,
saving considerable calculation time if doing the same conversion multiple times.
If you want to modify im in-place instead of receiving a new image as the return value, set inPlace to True. This
can only be done if transform.inMode and transform.outMode are the same, because we can’t change the mode
in-place (the buffer sizes for some modes are different). The default behavior is to return a new Image object of
the same dimensions in mode transform.outMode.
Parameters
• im – A PIL Image object, and im.mode must be the same as the inMode supported by the
transform.
• transform – A valid CmsTransform class object
• inPlace – Bool. If True, im is modified in place and None is returned, if False, a new
Image object with the transform applied is returned (and im is not changed). The default is
False.
Returns Either None, or a new PIL Image object, depending on the value of inPlace. The profile
will be returned in the image’s info[‘icc_profile’].
Raises PyCMSError –
PIL.ImageCms.buildProofTransform(inputProfile, outputProfile, proofProfile, inMode, outMode,
renderingIntent=0, proofRenderingIntent=3, flags=16384)
(pyCMS) Builds an ICC transform mapping from the inputProfile to the outputProfile, but tries to simulate the
result that would be obtained on the proofProfile device.
If the input, output, or proof profiles specified are not valid filenames, a PyCMSError will be raised.
If an error occurs during creation of the transform, a PyCMSError will be raised.
If inMode or outMode are not a mode supported by the outputProfile (or by pyCMS), a PyCMSError will be
raised.
This function builds and returns an ICC transform from the inputProfile to the outputProfile, but tries to simulate
the result that would be obtained on the proofProfile device using renderingIntent and proofRenderingIntent to
determine what to do with out-of-gamut colors. This is known as “soft-proofing”. It will ONLY work for
converting images that are in inMode to images that are in outMode color format (PIL mode, i.e. “RGB”,
“RGBA”, “CMYK”, etc.).
Usage of the resulting transform object is exactly the same as with ImageCms.buildTransform().
Proof profiling is generally used when using an output device to get a good idea of what the final
printed/displayed image would look like on the proofProfile device when it’s quicker and easier to use the output
device for judging color. Generally, this means that the output device is a monitor, or a dye-sub printer (etc.),
and the simulated device is something more expensive, complicated, or time consuming (making it difficult to
make a real print for color judgement purposes).
Soft-proofing basically functions by adjusting the colors on the output device to match the colors of the device
being simulated. However, when the simulated device has a much wider gamut than the output device, you may
obtain marginal results.
Parameters
• inputProfile – String, as a valid filename path to the ICC input profile you wish to use
for this transform, or a profile object
• outputProfile – String, as a valid filename path to the ICC output (monitor, usually)
profile you wish to use for this transform, or a profile object
• proofProfile – String, as a valid filename path to the ICC proof profile you wish to use
for this transform, or a profile object
• inMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”,
“RGBA”, “CMYK”, etc.)
68 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
• outMode – String, as a valid PIL mode that the appropriate profile also supports (i.e.
“RGB”, “RGBA”, “CMYK”, etc.)
• renderingIntent – Integer (0-3) specifying the rendering intent you wish to use for the
input->proof (simulated) transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC =
1 ImageCms.INTENT_SATURATION = 2 Im-
ageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what they do.
• proofRenderingIntent – Integer (0-3) specifying the rendering intent you wish to
use for proof->output transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC =
1 ImageCms.INTENT_SATURATION = 2 Im-
ageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what they do.
• flags – Integer (0-. . . ) specifying additional flags
Returns A CmsTransform class object.
Raises PyCMSError –
PIL.ImageCms.buildProofTransformFromOpenProfiles(inputProfile, outputProfile, proofPro-
file, inMode, outMode, rendering-
Intent=0, proofRenderingIntent=3,
flags=16384)
(pyCMS) Builds an ICC transform mapping from the inputProfile to the outputProfile, but tries to simulate the
result that would be obtained on the proofProfile device.
If the input, output, or proof profiles specified are not valid filenames, a PyCMSError will be raised.
If an error occurs during creation of the transform, a PyCMSError will be raised.
If inMode or outMode are not a mode supported by the outputProfile (or by pyCMS), a PyCMSError will be
raised.
This function builds and returns an ICC transform from the inputProfile to the outputProfile, but tries to simulate
the result that would be obtained on the proofProfile device using renderingIntent and proofRenderingIntent to
determine what to do with out-of-gamut colors. This is known as “soft-proofing”. It will ONLY work for
converting images that are in inMode to images that are in outMode color format (PIL mode, i.e. “RGB”,
“RGBA”, “CMYK”, etc.).
Usage of the resulting transform object is exactly the same as with ImageCms.buildTransform().
Proof profiling is generally used when using an output device to get a good idea of what the final
printed/displayed image would look like on the proofProfile device when it’s quicker and easier to use the output
device for judging color. Generally, this means that the output device is a monitor, or a dye-sub printer (etc.),
and the simulated device is something more expensive, complicated, or time consuming (making it difficult to
make a real print for color judgement purposes).
Soft-proofing basically functions by adjusting the colors on the output device to match the colors of the device
being simulated. However, when the simulated device has a much wider gamut than the output device, you may
obtain marginal results.
Parameters
• inputProfile – String, as a valid filename path to the ICC input profile you wish to use
for this transform, or a profile object
• outputProfile – String, as a valid filename path to the ICC output (monitor, usually)
profile you wish to use for this transform, or a profile object
• proofProfile – String, as a valid filename path to the ICC proof profile you wish to use
for this transform, or a profile object
• inMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”,
“RGBA”, “CMYK”, etc.)
• outMode – String, as a valid PIL mode that the appropriate profile also supports (i.e.
“RGB”, “RGBA”, “CMYK”, etc.)
• renderingIntent – Integer (0-3) specifying the rendering intent you wish to use for the
input->proof (simulated) transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC =
1 ImageCms.INTENT_SATURATION = 2 Im-
ageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what they do.
• proofRenderingIntent – Integer (0-3) specifying the rendering intent you wish to
use for proof->output transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC =
1 ImageCms.INTENT_SATURATION = 2 Im-
ageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what they do.
• flags – Integer (0-. . . ) specifying additional flags
Returns A CmsTransform class object.
Raises PyCMSError –
PIL.ImageCms.buildTransform(inputProfile, outputProfile, inMode, outMode, renderingIntent=0,
flags=0)
(pyCMS) Builds an ICC transform mapping from the inputProfile to the outputProfile. Use applyTransform to
apply the transform to a given image.
If the input or output profiles specified are not valid filenames, a PyCMSError will be raised. If an error occurs
during creation of the transform, a PyCMSError will be raised.
If inMode or outMode are not a mode supported by the outputProfile (or by pyCMS), a PyCMSError will be
raised.
This function builds and returns an ICC transform from the inputProfile to the outputProfile using the rendering-
Intent to determine what to do with out-of-gamut colors. It will ONLY work for converting images that are in
inMode to images that are in outMode color format (PIL mode, i.e. “RGB”, “RGBA”, “CMYK”, etc.).
Building the transform is a fair part of the overhead in ImageCms.profileToProfile(), so if you’re planning
on converting multiple images using the same input/output settings, this can save you time. Once you have a
transform object, it can be used with ImageCms.applyProfile() to convert images without the need to re-compute
the lookup table for the transform.
The reason pyCMS returns a class object rather than a handle directly to the transform is that it needs to keep
track of the PIL input/output modes that the transform is meant for. These attributes are stored in the “inMode”
70 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
and “outMode” attributes of the object (which can be manually overridden if you really want to, but I don’t
know of any time that would be of use, or would even work).
Parameters
• inputProfile – String, as a valid filename path to the ICC input profile you wish to use
for this transform, or a profile object
• outputProfile – String, as a valid filename path to the ICC output profile you wish to
use for this transform, or a profile object
• inMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”,
“RGBA”, “CMYK”, etc.)
• outMode – String, as a valid PIL mode that the appropriate profile also supports (i.e.
“RGB”, “RGBA”, “CMYK”, etc.)
• renderingIntent – Integer (0-3) specifying the rendering intent you wish to use for the
transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC =
1 ImageCms.INTENT_SATURATION = 2 Im-
ageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what they do.
• flags – Integer (0-. . . ) specifying additional flags
Returns A CmsTransform class object.
Raises PyCMSError –
PIL.ImageCms.buildTransformFromOpenProfiles(inputProfile, outputProfile, inMode, out-
Mode, renderingIntent=0, flags=0)
(pyCMS) Builds an ICC transform mapping from the inputProfile to the outputProfile. Use applyTransform to
apply the transform to a given image.
If the input or output profiles specified are not valid filenames, a PyCMSError will be raised. If an error occurs
during creation of the transform, a PyCMSError will be raised.
If inMode or outMode are not a mode supported by the outputProfile (or by pyCMS), a PyCMSError will be
raised.
This function builds and returns an ICC transform from the inputProfile to the outputProfile using the rendering-
Intent to determine what to do with out-of-gamut colors. It will ONLY work for converting images that are in
inMode to images that are in outMode color format (PIL mode, i.e. “RGB”, “RGBA”, “CMYK”, etc.).
Building the transform is a fair part of the overhead in ImageCms.profileToProfile(), so if you’re planning
on converting multiple images using the same input/output settings, this can save you time. Once you have a
transform object, it can be used with ImageCms.applyProfile() to convert images without the need to re-compute
the lookup table for the transform.
The reason pyCMS returns a class object rather than a handle directly to the transform is that it needs to keep
track of the PIL input/output modes that the transform is meant for. These attributes are stored in the “inMode”
and “outMode” attributes of the object (which can be manually overridden if you really want to, but I don’t
know of any time that would be of use, or would even work).
Parameters
• inputProfile – String, as a valid filename path to the ICC input profile you wish to use
for this transform, or a profile object
• outputProfile – String, as a valid filename path to the ICC output profile you wish to
use for this transform, or a profile object
• inMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”,
“RGBA”, “CMYK”, etc.)
• outMode – String, as a valid PIL mode that the appropriate profile also supports (i.e.
“RGB”, “RGBA”, “CMYK”, etc.)
• renderingIntent – Integer (0-3) specifying the rendering intent you wish to use for the
transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC =
1 ImageCms.INTENT_SATURATION = 2 Im-
ageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what they do.
• flags – Integer (0-. . . ) specifying additional flags
Returns A CmsTransform class object.
Raises PyCMSError –
PIL.ImageCms.createProfile(colorSpace, colorTemp=-1)
(pyCMS) Creates a profile.
If colorSpace not in [“LAB”, “XYZ”, “sRGB”], a PyCMSError is raised
If using LAB and colorTemp != a positive integer, a PyCMSError is raised.
If an error occurs while creating the profile, a PyCMSError is raised.
Use this function to create common profiles on-the-fly instead of having to supply a profile on disk
and knowing the path to it. It returns a normal CmsProfile object that can be passed to Im-
ageCms.buildTransformFromOpenProfiles() to create a transform to apply to images.
Parameters
• colorSpace – String, the color space of the profile you wish to create. Currently only
“LAB”, “XYZ”, and “sRGB” are supported.
• colorTemp – Positive integer for the white point for the profile, in degrees Kelvin (i.e.
5000, 6500, 9600, etc.). The default is for D50 illuminant if omitted (5000k). colorTemp is
ONLY applied to LAB profiles, and is ignored for XYZ and sRGB.
Returns A CmsProfile class object
Raises PyCMSError –
PIL.ImageCms.getDefaultIntent(profile)
(pyCMS) Gets the default intent name for the given profile.
If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.
If an error occurs while trying to obtain the default intent, a PyCMSError is raised.
Use this function to determine the default (and usually best optimized) rendering intent for this profile. Most
profiles support multiple rendering intents, but are intended mostly for one type of conversion. If you wish to
use a different intent than returned, use ImageCms.isIntentSupported() to verify it will work first.
Parameters profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC
profile.
72 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Returns
Integer 0-3 specifying the default rendering intent for this profile.
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT) Im-
ageCms.INTENT_RELATIVE_COLORIMETRIC = 1 Im-
ageCms.INTENT_SATURATION = 2 ImageCms.INTENT_ABSOLUTE_COLORIMETRIC
=3
see the pyCMS documentation for details on rendering intents and what they do.
Raises PyCMSError –
PIL.ImageCms.getOpenProfile(profileFilename)
(pyCMS) Opens an ICC profile file.
The PyCMSProfile object can be passed back into pyCMS for use in creating transforms and such (as in Im-
ageCms.buildTransformFromOpenProfiles()).
If profileFilename is not a valid filename for an ICC profile, a PyCMSError will be raised.
Parameters profileFilename – String, as a valid filename path to the ICC profile you wish to
open, or a file-like object.
Returns A CmsProfile class object.
Raises PyCMSError –
PIL.ImageCms.getProfileCopyright(profile)
(pyCMS) Gets the copyright for the given profile.
If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.
If an error occurs while trying to obtain the copyright tag, a PyCMSError is raised
Use this function to obtain the information stored in the profile’s copyright tag.
Parameters profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC
profile.
Returns A string containing the internal profile information stored in an ICC tag.
Raises PyCMSError –
PIL.ImageCms.getProfileDescription(profile)
(pyCMS) Gets the description for the given profile.
If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.
If an error occurs while trying to obtain the description tag, a PyCMSError is raised
Use this function to obtain the information stored in the profile’s description tag.
Parameters profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC
profile.
Returns A string containing the internal profile information stored in an ICC tag.
Raises PyCMSError –
PIL.ImageCms.getProfileInfo(profile)
(pyCMS) Gets the internal product information for the given profile.
If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.
If an error occurs while trying to obtain the info tag, a PyCMSError is raised
Use this function to obtain the information stored in the profile’s info tag. This often contains details about the
profile, and how it was created, as supplied by the creator.
Parameters profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC
profile.
Returns A string containing the internal profile information stored in an ICC tag.
Raises PyCMSError –
PIL.ImageCms.getProfileManufacturer(profile)
(pyCMS) Gets the manufacturer for the given profile.
If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.
If an error occurs while trying to obtain the manufacturer tag, a PyCMSError is raised
Use this function to obtain the information stored in the profile’s manufacturer tag.
Parameters profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC
profile.
Returns A string containing the internal profile information stored in an ICC tag.
Raises PyCMSError –
PIL.ImageCms.getProfileModel(profile)
(pyCMS) Gets the model for the given profile.
If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.
If an error occurs while trying to obtain the model tag, a PyCMSError is raised
Use this function to obtain the information stored in the profile’s model tag.
Parameters profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC
profile.
Returns A string containing the internal profile information stored in an ICC tag.
Raises PyCMSError –
PIL.ImageCms.getProfileName(profile)
(pyCMS) Gets the internal product name for the given profile.
If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised If an error occurs while
trying to obtain the name tag, a PyCMSError is raised.
Use this function to obtain the INTERNAL name of the profile (stored in an ICC tag in the profile itself), usually
the one used when the profile was originally created. Sometimes this tag also contains additional information
supplied by the creator.
Parameters profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC
profile.
Returns A string containing the internal name of the profile as stored in an ICC tag.
Raises PyCMSError –
PIL.ImageCms.get_display_profile(handle=None)
(experimental) Fetches the profile for the current display device. :returns: None if the profile is not known.
PIL.ImageCms.isIntentSupported(profile, intent, direction)
(pyCMS) Checks if a given intent is supported.
Use this function to verify that you can use your desired renderingIntent with profile, and that profile can be
used for the input/output/proof profile as you desire.
74 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Some profiles are created specifically for one “direction”, can cannot be used for others. Some profiles can only
be used for certain rendering intents. . . so it’s best to either verify this before trying to create a transform with
them (using this function), or catch the potential PyCMSError that will occur if they don’t support the modes
you select.
Parameters
• profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC
profile.
• intent – Integer (0-3) specifying the rendering intent you wish to use with this profile
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC =
1 ImageCms.INTENT_SATURATION = 2 Im-
ageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what they do.
• direction – Integer specifying if the profile is to be used for input, output, or proof
INPUT = 0 (or use ImageCms.DIRECTION_INPUT) OUTPUT = 1
(or use ImageCms.DIRECTION_OUTPUT) PROOF = 2 (or use Im-
ageCms.DIRECTION_PROOF)
Returns 1 if the intent/direction are supported, -1 if they are not.
Raises PyCMSError –
PIL.ImageCms.profileToProfile(im, inputProfile, outputProfile, renderingIntent=0, output-
Mode=None, inPlace=False, flags=0)
(pyCMS) Applies an ICC transformation to a given image, mapping from inputProfile to outputProfile.
If the input or output profiles specified are not valid filenames, a PyCMSError will be raised. If inPlace is True
and outputMode != im.mode, a PyCMSError will be raised. If an error occurs during application of the profiles,
a PyCMSError will be raised. If outputMode is not a mode supported by the outputProfile (or by pyCMS), a
PyCMSError will be raised.
This function applies an ICC transformation to im from inputProfile’s color space to outputProfile’s color space
using the specified rendering intent to decide how to handle out-of-gamut colors.
OutputMode can be used to specify that a color mode conversion is to be done using these profiles, but the
specified profiles must be able to handle that mode. I.e., if converting im from RGB to CMYK using profiles,
the input profile must handle RGB data, and the output profile must handle CMYK data.
Parameters
• im – An open PIL image object (i.e. Image.new(. . . ) or Image.open(. . . ), etc.)
• inputProfile – String, as a valid filename path to the ICC input profile you wish to use
for this image, or a profile object
• outputProfile – String, as a valid filename path to the ICC output profile you wish to
use for this image, or a profile object
• renderingIntent – Integer (0-3) specifying the rendering intent you wish to use for the
transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC =
1 ImageCms.INTENT_SATURATION = 2 Im-
ageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what they do.
• outputMode – A valid PIL mode for the output image (i.e. “RGB”, “CMYK”, etc.).
Note: if rendering the image “inPlace”, outputMode MUST be the same mode as the input,
or omitted completely. If omitted, the outputMode will be the same as the mode of the input
image (im.mode)
• inPlace – Boolean. If True, the original image is modified in-place, and None is returned.
If False (default), a new Image object is returned with the transform applied.
• flags – Integer (0-. . . ) specifying additional flags
Returns Either None or a new PIL image object, depending on value of inPlace
Raises PyCMSError –
PIL.ImageCms.versions()
(pyCMS) Fetches versions.
3.4.1 CmsProfile
The ICC color profiles are wrapped in an instance of the class CmsProfile. The specification ICC.1:2010 contains
more information about the meaning of the values in ICC profiles.
For convenience, all XYZ-values are also given as xyY-values (so they can be easily displayed in a chromaticity
diagram, for example).
class PIL.ImageCms.CmsProfile
creation_date
Date and time this profile was first created (see 7.2.1 of ICC.1:2010).
Type datetime.datetime or None
version
The version number of the ICC standard that this profile follows (e.g. 2.0).
Type float
icc_version
Same as version, but in encoded format (see 7.2.4 of ICC.1:2010).
device_class
4-character string identifying the profile class. One of scnr, mntr, prtr, link, spac, abst, nmcl
(see 7.2.5 of ICC.1:2010 for details).
Type string
xcolor_space
4-character string (padded with whitespace) identifying the color space, e.g. XYZ , RGB or CMYK (see
7.2.6 of ICC.1:2010 for details).
Note that the deprecated attribute color_space contains an interpreted (non-padded) variant of this (but
can be empty on unknown input).
Type string
connection_space
4-character string (padded with whitespace) identifying the color space on the B-side of the transform (see
7.2.7 of ICC.1:2010 for details).
76 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Note that the deprecated attribute pcs contains an interpreted (non-padded) variant of this (but can be
empty on unknown input).
Type string
header_flags
The encoded header flags of the profile (see 7.2.11 of ICC.1:2010 for details).
Type int
header_manufacturer
4-character string (padded with whitespace) identifying the device manufacturer, which shall match the
signature contained in the appropriate section of the ICC signature registry found at www.color.org (see
7.2.12 of ICC.1:2010).
Type string
header_model
4-character string (padded with whitespace) identifying the device model, which shall match the signature
contained in the appropriate section of the ICC signature registry found at www.color.org (see 7.2.13 of
ICC.1:2010).
Type string
attributes
Flags used to identify attributes unique to the particular device setup for which the profile is applicable
(see 7.2.14 of ICC.1:2010 for details).
Type int
rendering_intent
The rendering intent to use when combining this profile with another profile (usually overridden at run-
time, but provided here for DeviceLink and embedded source profiles, see 7.2.15 of ICC.1:2010).
One of ImageCms.INTENT_ABSOLUTE_COLORIMETRIC, ImageCms.INTENT_PERCEPTUAL,
ImageCms.INTENT_RELATIVE_COLORIMETRIC and ImageCms.INTENT_SATURATION.
Type int
profile_id
A sequence of 16 bytes identifying the profile (via a specially constructed MD5 sum), or 16 binary zeroes
if the profile ID has not been calculated (see 7.2.18 of ICC.1:2010).
Type bytes
copyright
The text copyright information for the profile (see 9.2.21 of ICC.1:2010).
Type unicode or None
manufacturer
The (English) display string for the device manufacturer (see 9.2.22 of ICC.1:2010).
Type unicode or None
model
The (English) display string for the device model of the device for which this profile is created (see 9.2.23
of ICC.1:2010).
Type unicode or None
profile_description
The (English) display string for the profile description (see 9.2.41 of ICC.1:2010).
Type unicode or None
target
The name of the registered characterization data set, or the measurement data for a characterization target
(see 9.2.14 of ICC.1:2010).
Type unicode or None
red_colorant
The first column in the matrix used in matrix/TRC transforms (see 9.2.44 of ICC.1:2010).
Type ((X, Y, Z), (x, y, Y)) or None
green_colorant
The second column in the matrix used in matrix/TRC transforms (see 9.2.30 of ICC.1:2010).
Type ((X, Y, Z), (x, y, Y)) or None
blue_colorant
The third column in the matrix used in matrix/TRC transforms (see 9.2.4 of ICC.1:2010).
Type ((X, Y, Z), (x, y, Y)) or None
luminance
The absolute luminance of emissive devices in candelas per square metre as described by the Y channel
(see 9.2.32 of ICC.1:2010).
Type ((X, Y, Z), (x, y, Y)) or None
chromaticity
The data of the phosphor/colorant chromaticity set used (red, green and blue channels, see 9.2.16 of
ICC.1:2010).
Type ((x, y, Y), (x, y, Y), (x, y, Y)) or None
chromatic_adaption
The chromatic adaption matrix converts a color measured using the actual illumination conditions and
relative to the actual adopted white, to an color relative to the PCS adopted white, with complete adap-
tation from the actual adopted white chromaticity to the PCS adopted white chromaticity (see 9.2.15 of
ICC.1:2010).
Two matrices are returned, one in (X, Y, Z) space and one in (x, y, Y) space.
Type 2-tuple of 3-tuple, the first with (X, Y, Z) and the second with (x, y, Y) values
colorant_table
This tag identifies the colorants used in the profile by a unique name and set of PCSXYZ or PCSLAB
values (see 9.2.19 of ICC.1:2010).
Type list of strings
colorant_table_out
This tag identifies the colorants used in the profile by a unique name and set of PCSLAB values (for
DeviceLink profiles only, see 9.2.19 of ICC.1:2010).
Type list of strings
colorimetric_intent
4-character string (padded with whitespace) identifying the image state of PCS colorimetry produced using
the colorimetric intent transforms (see 9.2.20 of ICC.1:2010 for details).
Type string or None
perceptual_rendering_intent_gamut
4-character string (padded with whitespace) identifying the (one) standard reference medium gamut (see
9.2.37 of ICC.1:2010 for details).
78 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
80 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
is_intent_supported(intent, direction)
Returns if the intent is supported for the given direction.
Note that you can also get this information for all intents and directions with intent_supported.
Parameters
• intent – One of ImageCms.INTENT_ABSOLUTE_COLORIMETRIC, ImageCms.
INTENT_PERCEPTUAL, ImageCms.INTENT_RELATIVE_COLORIMETRIC and
ImageCms.INTENT_SATURATION.
• direction – One of ImageCms.DIRECTION_INPUT, ImageCms.
DIRECTION_OUTPUT and ImageCms.DIRECTION_PROOF
Returns Boolean if the intent and direction is supported.
The ImageDraw module provides simple 2D graphics for Image objects. You can use this module to create new
images, annotate or retouch existing images, and to generate graphics on the fly for web use.
For a more advanced drawing library for PIL, see the aggdraw module.
draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=128)
draw.line((0, im.size[1], im.size[0], 0), fill=128)
# write to stdout
im.save(sys.stdout, "PNG")
3.5.2 Concepts
Coordinates
The graphics interface uses the same coordinate system as PIL itself, with (0, 0) in the upper left corner. Any pixels
drawn outside of the image bounds will be discarded.
Colors
To specify colors, you can use numbers or tuples just as you would use with PIL.Image.new() or PIL.Image.
Image.putpixel(). For “1”, “L”, and “I” images, use integers. For “RGB” images, use a 3-tuple containing
integer values. For “F” images, use integer or floating point values.
For palette images (mode “P”), use integers as color indexes. In 1.1.4 and later, you can also use RGB 3-tuples or
color names (see below). The drawing layer will automatically assign color indexes, as long as you don’t draw with
more than 256 colors.
Color Names
Fonts
# make a blank image for the text, initialized to transparent text color
txt = Image.new('RGBA', base.size, (255,255,255,0))
# get a font
fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 40)
# get a drawing context
d = ImageDraw.Draw(txt)
out.show()
# create an image
out = Image.new("RGB", (150, 100), (255, 255, 255))
# get a font
fnt = ImageFont.truetype("Pillow/Tests/fonts/FreeMono.ttf", 40)
# get a drawing context
d = ImageDraw.Draw(out)
82 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
out.show()
3.5.5 Functions
3.5.6 Methods
PIL.ImageDraw.ImageDraw.getfont()
Get the current default font.
Returns An image font.
PIL.ImageDraw.ImageDraw.arc(xy, start, end, fill=None, width=0)
Draws an arc (a portion of a circle outline) between the start and end angles, inside the given bounding box.
Parameters
• xy – Two points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or
[x0, y0, x1, y1], where x1 >= x0 and y1 >= y0.
• start – Starting angle, in degrees. Angles are measured from 3 o’clock, increasing clock-
wise.
• end – Ending angle, in degrees.
• fill – Color to use for the arc.
• width – The line width, in pixels.
New in version 5.3.0.
PIL.ImageDraw.ImageDraw.bitmap(xy, bitmap, fill=None)
Draws a bitmap (mask) at the given position, using the current fill color for the non-zero portions. The bitmap
should be a valid transparency mask (mode “1”) or matte (mode “L” or “RGBA”).
This is equivalent to doing image.paste(xy, color, bitmap).
To paste pixel data into an image, use the paste() method on the image itself.
PIL.ImageDraw.ImageDraw.chord(xy, start, end, fill=None, outline=None, width=1)
Same as arc(), but connects the end points with a straight line.
Parameters
• xy – Two points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or
[x0, y0, x1, y1], where x1 >= x0 and y1 >= y0.
• outline – Color to use for the outline.
• joint –
Joint type between a sequence of lines. It can be “curve”, for rounded edges, or None.
New in version 5.3.0.
PIL.ImageDraw.ImageDraw.pieslice(xy, start, end, fill=None, outline=None, width=1)
Same as arc, but also draws straight lines between the end points and the center of the bounding box.
Parameters
• xy – Two points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or
[x0, y0, x1, y1], where x1 >= x0 and y1 >= y0.
• start – Starting angle, in degrees. Angles are measured from 3 o’clock, increasing clock-
wise.
• end – Ending angle, in degrees.
• fill – Color to use for the fill.
• outline – Color to use for the outline.
• width – The line width, in pixels.
New in version 5.3.0.
84 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
PIL.ImageDraw.ImageDraw.point(xy, fill=None)
Draws points (individual pixels) at the given coordinates.
Parameters
• xy – Sequence of either 2-tuples like [(x, y), (x, y), ...] or numeric values like
[x, y, x, y, ...].
• fill – Color to use for the point.
PIL.ImageDraw.ImageDraw.polygon(xy, fill=None, outline=None)
Draws a polygon.
The polygon outline consists of straight lines between the given coordinates, plus a straight line between the last
and the first coordinate.
Parameters
• xy – Sequence of either 2-tuples like [(x, y), (x, y), ...] or numeric values like
[x, y, x, y, ...].
• outline – Color to use for the outline.
• fill – Color to use for the fill.
PIL.ImageDraw.ImageDraw.rectangle(xy, fill=None, outline=None, width=1)
Draws a rectangle.
Parameters
• xy – Two points to define the bounding box. Sequence of either [(x0, y0), (x1,
y1)] or [x0, y0, x1, y1]. The second point is just outside the drawn rectangle.
• outline – Color to use for the outline.
• fill – Color to use for the fill.
• width – The line width, in pixels.
New in version 5.3.0.
PIL.ImageDraw.ImageDraw.shape(shape, fill=None, outline=None)
Draw a shape.
PIL.ImageDraw.ImageDraw.text(xy, text, fill=None, font=None, anchor=None, spacing=4,
align="left", direction=None, features=None, language=None,
stroke_width=0, stroke_fill=None)
Draws the string at the given position.
Parameters
• xy – Top left corner of the text.
• text – Text to be drawn. If it contains any newline characters, the text is passed on to
multiline_text()
• fill – Color to use for the text.
• font – An ImageFont instance.
• spacing – If the text is passed on to multiline_text(), the number of pixels between lines.
86 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
• language – Language of the text. Different languages may use different glyph shapes
or ligatures. This parameter tells the font which language the text is in, and to apply the
correct substitutions as appropriate, if available. It should be a BCP 47 language code
<https://www.w3.org/International/articles/language-tags/> Requires libraqm.
New in version 6.0.0.
PIL.ImageDraw.ImageDraw.textsize(text, font=None, spacing=4, direction=None, features=None,
language=None, stroke_width=0)
Return the size of the given string, in pixels.
Parameters
• text – Text to be measured. If it contains any newline characters, the text is passed on to
multiline_textsize()
• font – An ImageFont instance.
• spacing – If the text is passed on to multiline_textsize(), the number of pixels between
lines.
• direction – Direction of the text. It can be ‘rtl’ (right to left), ‘ltr’ (left to right) or ‘ttb’
(top to bottom). Requires libraqm.
New in version 4.2.0.
• features – A list of OpenType font features to be used during text layout. This is
usually used to turn on optional font features that are not enabled by default, for exam-
ple ‘dlig’ or ‘ss01’, but can be also used to turn off default font features for example ‘-
liga’ to disable ligatures or ‘-kern’ to disable kerning. To get all supported features, see
https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm.
New in version 4.2.0.
• language – Language of the text. Different languages may use different glyph shapes
or ligatures. This parameter tells the font which language the text is in, and to apply the
correct substitutions as appropriate, if available. It should be a BCP 47 language code
<https://www.w3.org/International/articles/language-tags/> Requires libraqm.
New in version 6.0.0.
• stroke_width – The width of the text stroke.
New in version 6.2.0.
PIL.ImageDraw.ImageDraw.multiline_textsize(text, font=None, spacing=4, direc-
tion=None, features=None, language=None,
stroke_width=0)
Return the size of the given string, in pixels.
Parameters
• text – Text to be measured.
• font – An ImageFont instance.
• spacing – The number of pixels between lines.
• direction – Direction of the text. It can be ‘rtl’ (right to left), ‘ltr’ (left to right) or ‘ttb’
(top to bottom). Requires libraqm.
New in version 4.2.0.
• features – A list of OpenType font features to be used during text layout. This is
usually used to turn on optional font features that are not enabled by default, for exam-
ple ‘dlig’ or ‘ss01’, but can be also used to turn off default font features for example ‘-
liga’ to disable ligatures or ‘-kern’ to disable kerning. To get all supported features, see
https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm.
New in version 4.2.0.
• language – Language of the text. Different languages may use different glyph shapes
or ligatures. This parameter tells the font which language the text is in, and to apply the
correct substitutions as appropriate, if available. It should be a BCP 47 language code
<https://www.w3.org/International/articles/language-tags/> Requires libraqm.
New in version 6.0.0.
• stroke_width – The width of the text stroke.
New in version 6.2.0.
PIL.ImageDraw.getdraw(im=None, hints=None)
A more advanced 2D drawing interface for PIL images, based on the WCK interface.
Parameters
• im – The image to draw in.
• hints – An optional list of hints.
Returns A (drawing context, drawing resource factory) tuple.
PIL.ImageDraw.floodfill(image, xy, value, border=None, thresh=0)
88 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
The ImageEnhance module contains a number of classes that can be used for image enhancement.
enhancer = ImageEnhance.Sharpness(image)
for i in range(8):
factor = i / 4.0
enhancer.enhance(factor).show("Sharpness %f" % factor)
3.6.2 Classes
The ImageFile module provides support functions for the image open and save functions.
In addition, it provides a Parser class which can be used to decode an image piece by piece (e.g. while receiving it
over a network connection). This class implements the same consumer interface as the standard sgmllib and xmllib
modules.
fp = open("hopper.pgm", "rb")
p = ImageFile.Parser()
while 1:
s = fp.read(1024)
if not s:
break
p.feed(s)
im = p.close()
im.save("copy.jpg")
3.7.2 Parser
class PIL.ImageFile.Parser
Incremental image parser. This class implements the standard feed/close consumer interface.
close()
(Consumer) Close the stream.
Returns An image object.
Raises OSError – If the parser failed to parse the image file either because it cannot be identi-
fied or cannot be decoded.
feed(data)
(Consumer) Feed data to the parser.
Parameters data – A string buffer.
Raises OSError – If the parser failed to parse the image file.
reset()
(Consumer) Reset the parser. Note that you can only call this method immediately after you’ve created a
parser; parser instances cannot be reused.
3.7.3 PyDecoder
class PIL.ImageFile.PyDecoder
Python implementation of a format decoder. Override this class and add the decoding logic in the decode
method.
See Writing Your Own File Decoder in Python
cleanup()
Override to perform decoder specific cleanup
90 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Returns None
decode(buffer)
Override to perform the decoding process.
Parameters buffer – A bytes object with the data to be decoded.
Returns A tuple of (bytes consumed, errcode). If finished with decoding return <0 for the bytes
consumed. Err codes are from ERRORS
init(args)
Override to perform decoder specific initialization
Parameters args – Array of args items from the tile entry
Returns None
set_as_raw(data, rawmode=None)
Convenience method to set the internal image from a stream of raw data
Parameters
• data – Bytes to be set
• rawmode – The rawmode to be used for the decoder. If not specified, it will default to the
mode of the image
Returns None
setfd(fd)
Called from ImageFile to set the python file-like object
Parameters fd – A python file-like object
Returns None
setimage(im, extents=None)
Called from ImageFile to set the core output image for the decoder
Parameters
• im – A core image object
• extents – a 4 tuple of (x0, y0, x1, y1) defining the rectangle for this tile
Returns None
The ImageFilter module contains definitions for a pre-defined set of filters, which can be be used with the Image.
filter() method.
im1 = im.filter(ImageFilter.BLUR)
im2 = im.filter(ImageFilter.MinFilter(3))
im3 = im.filter(ImageFilter.MinFilter) # same as MinFilter(3)
3.8.2 Filters
The current version of the library provides the following set of predefined image enhancement filters:
• BLUR
• CONTOUR
• DETAIL
• EDGE_ENHANCE
• EDGE_ENHANCE_MORE
• EMBOSS
• FIND_EDGES
• SHARPEN
• SMOOTH
• SMOOTH_MORE
class PIL.ImageFilter.Color3DLUT(size, table, channels=3, target_mode=None, **kwargs)
Three-dimensional color lookup table.
Transforms 3-channel pixels using the values of the channels as coordinates in the 3D lookup table and interpo-
lating the nearest elements.
This method allows you to apply almost any color transformation in constant time by using pre-calculated
decimated tables.
New in version 5.2.0.
Parameters
• size – Size of the table. One int or tuple of (int, int, int). Minimal size in any dimension is
2, maximum is 65.
• table – Flat lookup table. A list of channels * size**3 float elements or a list of
size**3 channels-sized tuples with floats. Channels are changed first, then first dimen-
sion, then second, then third. Value 0.0 corresponds lowest value of output, 1.0 highest.
• channels – Number of channels in the table. Could be 3 or 4. Default is 3.
• target_mode – A mode for the result image. Should have not less than channels
channels. Default is None, which means that mode wouldn’t be changed.
classmethod generate(size, callback, channels=3, target_mode=None)
Generates new LUT using provided callback.
Parameters
• size – Size of the table. Passed to the constructor.
• callback – Function with three parameters which correspond three color channels. Will
be called size**3 times with values from 0.0 to 1.0 and should return a tuple with
channels elements.
• channels – The number of channels which should return callback.
• target_mode – Passed to the constructor of the resulting lookup table.
transform(callback, with_normals=False, channels=None, target_mode=None)
Transforms the table values using provided callback and returns a new LUT with altered values.
92 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Parameters
• callback – A function which takes old lookup table values and returns a new set of
values. The number of arguments which function should take is self.channels or 3
+ self.channels if with_normals flag is set. Should return a tuple of self.
channels or channels elements if it is set.
• with_normals – If true, callback will be called with coordinates in the color cube
as the first three arguments. Otherwise, callback will be called only with actual color
values.
• channels – The number of channels in the resulting lookup table.
• target_mode – Passed to the constructor of the resulting lookup table.
class PIL.ImageFilter.BoxBlur(radius)
Blurs the image by setting each pixel to the average value of the pixels in a square box extending radius pixels
in each direction. Supports float radius of arbitrary size. Uses an optimized implementation which runs in linear
time relative to the size of the image for any radius value.
Parameters radius – Size of the box in one direction. Radius 0 does not blur, returns an identical
image. Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total.
class PIL.ImageFilter.GaussianBlur(radius=2)
Gaussian blur filter.
Parameters radius – Blur radius.
class PIL.ImageFilter.UnsharpMask(radius=2, percent=150, threshold=3)
Unsharp mask filter.
See Wikipedia’s entry on digital unsharp masking for an explanation of the parameters.
Parameters
• radius – Blur Radius
• percent – Unsharp strength, in percent
• threshold – Threshold controls the minimum brightness change that will be sharpened
class PIL.ImageFilter.Kernel(size, kernel, scale=None, offset=0)
Create a convolution kernel. The current version only supports 3x3 and 5x5 integer and floating point kernels.
In the current version, kernels can only be applied to “L” and “RGB” images.
Parameters
• size – Kernel size, given as (width, height). In the current version, this must be (3,3) or
(5,5).
• kernel – A sequence containing kernel weights.
• scale – Scale factor. If given, the result for each pixel is divided by this value. the default
is the sum of the kernel weights.
• offset – Offset. If given, this value is added to the result, after it has been divided by the
scale factor.
class PIL.ImageFilter.RankFilter(size, rank)
Create a rank filter. The rank filter sorts all pixels in a window of the given size, and returns the rank’th value.
Parameters
• size – The kernel size, in pixels.
• rank – What pixel value to pick. Use 0 for a min filter, size * size / 2 for a median
filter, size * size - 1 for a max filter, etc.
class PIL.ImageFilter.MedianFilter(size=3)
Create a median filter. Picks the median pixel value in a window with the given size.
Parameters size – The kernel size, in pixels.
class PIL.ImageFilter.MinFilter(size=3)
Create a min filter. Picks the lowest pixel value in a window with the given size.
Parameters size – The kernel size, in pixels.
class PIL.ImageFilter.MaxFilter(size=3)
Create a max filter. Picks the largest pixel value in a window with the given size.
Parameters size – The kernel size, in pixels.
class PIL.ImageFilter.ModeFilter(size=3)
Create a mode filter. Picks the most frequent pixel value in a box with the given size. Pixel values that occur
only once or twice are ignored; if no pixel value occurs more than twice, the original pixel value is preserved.
Parameters size – The kernel size, in pixels.
The ImageFont module defines a class with the same name. Instances of this class store bitmap fonts, and are used
with the PIL.ImageDraw.Draw.text() method.
PIL uses its own font file format to store bitmap fonts. You can use the pilfont utility from pillow-scripts to convert
BDF and PCF font descriptors (X window font formats) to this format.
Starting with version 1.1.4, PIL can be configured to support TrueType and OpenType fonts (as well as other font
formats supported by the FreeType library). For earlier versions, TrueType support is only available as part of the
imToolkit package.
3.9.1 Example
draw = ImageDraw.Draw(image)
3.9.2 Functions
PIL.ImageFont.load(filename)
Load a font file. This function loads a font object from the given bitmap font file, and returns the corresponding
94 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
font object.
Parameters filename – Name of font file.
Returns A font object.
Raises OSError – If the file could not be read.
PIL.ImageFont.load_path(filename)
Load font file. Same as load(), but searches for a bitmap font along the Python path.
Parameters filename – Name of font file.
Returns A font object.
Raises OSError – If the file could not be read.
PIL.ImageFont.truetype(font=None, size=10, index=0, encoding=”, layout_engine=None)
Load a TrueType or OpenType font from a file or file-like object, and create a font object. This function loads a
font object from the given file or file-like object, and creates a font object for a font of the given size.
Pillow uses FreeType to open font files. If you are opening many fonts simultaneously on Windows, be aware
that Windows limits the number of files that can be open in C at once to 512. If you approach that limit, an
OSError may be thrown, reporting that FreeType “cannot open resource”.
This function requires the _imagingft service.
Parameters
• font – A filename or file-like object containing a TrueType font. If the file is not found
in this filename, the loader may also search in other directories, such as the fonts/ di-
rectory on Windows or /Library/Fonts/, /System/Library/Fonts/ and ~/
Library/Fonts/ on macOS.
• size – The requested size, in points.
• index – Which font face to load (default is first available face).
• encoding – Which font encoding to use (default is Unicode). Possible encodings include
(see the FreeType documentation for more information):
– ”unic” (Unicode)
– ”symb” (Microsoft Symbol)
– ”ADOB” (Adobe Standard)
– ”ADBE” (Adobe Expert)
– ”ADBC” (Adobe Custom)
– ”armn” (Apple Roman)
– ”sjis” (Shift JIS)
– ”gb ” (PRC)
– ”big5”
– ”wans” (Extended Wansung)
– ”joha” (Johab)
– ”lat1” (Latin-1)
This specifies the character set to use. It does not alter the encoding of any text provided in
subsequent operations.
3.9.3 Methods
class PIL.ImageFont.ImageFont
PIL font wrapper
getmask(text, mode=”, *args, **kwargs)
Create a bitmap for the text.
If the font uses antialiasing, the bitmap should have mode L and use a maximum value of 255. Otherwise,
it should have mode 1.
Parameters
• text – Text to render.
• mode – Used by some graphics drivers to indicate what mode the driver prefers; if empty,
the renderer may return either mode. Note that the mode is always a string, to simplify
C-level implementations.
New in version 1.1.5.
Returns An internal PIL storage memory instance as defined by the PIL.Image.core inter-
face module.
getsize(text, *args, **kwargs)
Returns width and height (in pixels) of given text.
Parameters text – Text to measure.
Returns (width, height)
class PIL.ImageFont.FreeTypeFont(font=None, size=10, index=0, encoding=”, lay-
out_engine=None)
FreeType font wrapper (requires _imagingft service)
font_variant(font=None, size=None, index=None, encoding=None, layout_engine=None)
Create a copy of this FreeTypeFont object, using any specified arguments to override the settings.
Parameters are identical to the parameters used to initialize this object.
Returns A FreeTypeFont object.
get_variation_axes()
Returns A list of the axes in a variation font.
Raises OSError – If the font is not a variation font.
get_variation_names()
Returns A list of the named styles in a variation font.
96 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
• features – A list of OpenType font features to be used during text layout. This is
usually used to turn on optional font features that are not enabled by default, for example
‘dlig’ or ‘ss01’, but can be also used to turn off default font features for example ‘-liga’
to disable ligatures or ‘-kern’ to disable kerning. To get all supported features, see https:
//docs.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm.
New in version 4.2.0.
• language – Language of the text. Different languages may use different glyph shapes
or ligatures. This parameter tells the font which language the text is in, and to apply the
correct substitutions as appropriate, if available. It should be a BCP 47 language code
<https://www.w3.org/International/articles/language-tags/> Requires libraqm.
New in version 6.0.0.
• stroke_width – The width of the text stroke.
New in version 6.2.0.
Returns A tuple of an internal PIL storage memory instance as defined by the PIL.Image.
core interface module, and the text offset, the gap between the starting coordinate and the
first marking
getmetrics()
Returns A tuple of the font ascent (the distance from the baseline to the highest outline point)
and descent (the distance from the baseline to the lowest outline point, a negative value)
getname()
Returns A tuple of the font family (e.g. Helvetica) and the font style (e.g. Bold)
getoffset(text)
Returns the offset of given text. This is the gap between the starting coordinate and the first marking. Note
that this gap is included in the result of getsize().
Parameters text – Text to measure.
Returns A tuple of the x and y offset
getsize(text, direction=None, features=None, language=None, stroke_width=0)
Returns width and height (in pixels) of given text if rendered in font with provided direction, features, and
language.
Parameters
• text – Text to measure.
• direction – Direction of the text. It can be ‘rtl’ (right to left), ‘ltr’ (left to right) or ‘ttb’
(top to bottom). Requires libraqm.
New in version 4.2.0.
• features – A list of OpenType font features to be used during text layout. This is
usually used to turn on optional font features that are not enabled by default, for example
‘dlig’ or ‘ss01’, but can be also used to turn off default font features for example ‘-liga’
to disable ligatures or ‘-kern’ to disable kerning. To get all supported features, see https:
//docs.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm.
New in version 4.2.0.
• language – Language of the text. Different languages may use different glyph shapes
or ligatures. This parameter tells the font which language the text is in, and to apply the
98 Chapter 3. Reference
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
The ImageGrab module can be used to copy the contents of the screen or the clipboard to a PIL image memory.
The ImageMath module can be used to evaluate “image expressions”. The module provides a single eval()
function, which takes an expression string and one or more images.
im1 = Image.open("image1.jpg")
im2 = Image.open("image2.jpg")
PIL.ImageMath.eval(expression, environment)
Evaluate expression in the given environment.
In the current version, ImageMath only supports single-layer images. To process multi-band images, use the
split() method or merge() function.
Parameters
• expression – A string which uses the standard Python expression syntax. In addition to
the standard operators, you can also use the functions described below.
• environment – A dictionary that maps image names to Image instances. You can use one
or more keyword arguments instead of a dictionary, as shown in the above example. Note
that the names must be valid Python identifiers.
Returns An image, an integer value, a floating point value, or a pixel tuple, depending on the ex-
pression.
Expressions are standard Python expressions, but they’re evaluated in a non-standard environment. You can use PIL
methods as usual, plus the following set of operators and functions:
Standard Operators
You can use standard arithmetical operators for addition (+), subtraction (-), multiplication (*), and division (/).
The module also supports unary minus (-), modulo (%), and power (**) operators.
Note that all operations are done with 32-bit integers or 32-bit floating point values, as necessary. For example, if you
add two 8-bit images, the result will be a 32-bit integer image. If you add a floating point constant to an 8-bit image,
the result will be a 32-bit floating point image.
You can force conversion using the convert(), float(), and int() functions described below.
Bitwise Operators
The module also provides operations that operate on individual bits. This includes and (&), or (|), and exclusive or (^).
You can also invert (~) all pixel bits.
Note that the operands are converted to 32-bit signed integers before the bitwise operation is applied. This means that
you’ll get negative values if you invert an ordinary greyscale image. You can use the and (&) operator to mask off
unwanted bits.
Bitwise operators don’t work on floating point images.
Logical Operators
Logical operators like and, or, and not work on entire images, rather than individual pixels.
An empty image (all pixels zero) is treated as false. All other images are treated as true.
Note that and and or return the last evaluated operand, while not always returns a boolean value.
Built-in Functions
4:(...
.1.
111)->1
(whitespaces including linebreaks are ignored). The option 4 describes a series of symmetry operations (in this
case a 4-rotation), the pattern is described by:
• . or X - Ignore
• 1 - Pixel is on
• 0 - Pixel is off
The result of the operation is described after “->” string.
The default is to return the current pixel value, which is returned if no other match is found.
Operations:
• 4 - 4 way rotation
• N - Negate
• 1 - Dummy op for no other operation (an op must always be given)
• M - Mirroring
Example:
add_patterns(patterns)
build_default_lut()
build_lut()
Compile all patterns into a morphology lut.
TBD :Build based on (file) morphlut:modify_lut
get_lut()
class PIL.ImageMorph.MorphOp(lut=None, op_name=None, patterns=None)
Bases: object
A class for binary morphological operators
apply(image)
Run a single morphological operation on an image
Returns a tuple of the number of changed pixels and the morphed image
get_on_pixels(image)
Get a list of all turned on pixels in a binary image
Returns a list of tuples of (x,y) coordinates of all matching pixels. See Coordinate System.
load_lut(filename)
Load an operator from an mrl file
match(image)
Get a list of coordinates matching the morphological operation on an image.
Returns a list of tuples of (x,y) coordinates of all matching pixels. See Coordinate System.
save_lut(filename)
Save an operator to an mrl file
set_lut(lut)
Set the lut from an external source
The ImageOps module contains a number of ‘ready-made’ image processing operations. This module is somewhat
experimental, and most operators only work on L and RGB images.
New in version 1.1.3.
PIL.ImageOps.autocontrast(image, cutoff=0, ignore=None)
Maximize (normalize) image contrast. This function calculates a histogram of the input image, removes cutoff
percent of the lightest and darkest pixels from the histogram, and remaps the image so that the darkest pixel
becomes black (0), and the lightest becomes white (255).
Parameters
• image – The image to process.
• cutoff – How many percent to cut off from the histogram.
• ignore – The background pixel value (use None for no background).
Returns An image.
PIL.ImageOps.colorize(image, black, white, mid=None, blackpoint=0, whitepoint=255, mid-
point=127)
Colorize grayscale image. This function calculates a color wedge which maps all black pixels in the source
image to the first color and all white pixels to the second color. If mid is specified, it uses three-color mapping.
The black and white arguments should be RGB tuples or color names; optionally you can use three-color map-
ping by also specifying mid. Mapping positions for any of the colors can be specified (e.g. blackpoint), where
these parameters are the integer value corresponding to where the corresponding color should be mapped. These
parameters must have logical order, such that blackpoint <= midpoint <= whitepoint (if mid is specified).
Parameters
• image – The image to colorize.
• black – The color to use for black input pixels.
• white – The color to use for white input pixels.
• mid – The color to use for midtone input pixels.
• blackpoint – an int value [0, 255] for the black mapping.
• whitepoint – an int value [0, 255] for the white mapping.
• midpoint – an int value [0, 255] for the midtone mapping.
Returns An image.
PIL.ImageOps.pad(image, size, method=3, color=None, centering=(0.5, 0.5))
Returns a sized and padded version of the image, expanded to fill the requested aspect ratio and size.
Parameters
• image – The image to size and crop.
• size – The requested output size in pixels, given as a (width, height) tuple.
• method – What resampling method to use. Default is PIL.Image.BICUBIC. See Fil-
ters.
• color – The background color of the padded image.
• centering – Control the position of the original image within the padded version.
(0.5, 0.5) will keep the image centered (0, 0) will keep the image aligned to the top left
(1, 1) will keep the image aligned to the bottom right
Returns An image.
PIL.ImageOps.crop(image, border=0)
Remove border from image. The same amount of pixels are removed from all four sides. This function works
on all image modes.
See also:
crop()
Parameters
• image – The image to crop.
• border – The number of pixels to remove.
Returns An image.
PIL.ImageOps.exif_transpose(image)
If an image has an EXIF Orientation tag, return a new image that is transposed accordingly. Otherwise, return a
copy of the image.
Parameters image – The image to transpose.
Returns An image.
The ImagePalette module contains a class of the same name to represent the color palette of palette mapped
images.
Note: This module was never well-documented. It hasn’t changed since 2001, though, so it’s probably safe for you
to read the source code and puzzle out the internals if you need to.
The ImagePalette class has several methods, but they are all marked as “experimental.” Read that as you will.
The [source] link is there for a reason.
getdata()
Get palette contents in format suitable for the low-level im.putpalette primitive.
save(fp)
Save palette to text file.
tobytes()
Convert palette to bytes.
tostring()
Convert palette to bytes.
The ImagePath module is used to store and manipulate 2-dimensional vector data. Path objects can be passed to the
methods on the ImageDraw module.
class PIL.ImagePath.Path
A path object. The coordinate list can be any sequence object containing either 2-tuples [(x, y), . . . ] or numeric
values [x, y, . . . ].
You can also create a path object from another path object.
In 1.1.6 and later, you can also pass in any object that implements Python’s buffer API. The buffer should
provide read access, and contain C floats in machine byte order.
The path object implements most parts of the Python sequence interface, and behaves like a list of (x, y) pairs.
You can use len(), item access, and slicing as usual. However, the current version does not support slice assign-
ment, or item and slice deletion.
Parameters xy – A sequence. The sequence can contain 2-tuples [(x, y), . . . ] or a flat list of
numbers [x, y, . . . ].
PIL.ImagePath.Path.compact(distance=2)
Compacts the path, by removing points that are close to each other. This method modifies the path in place, and
returns the number of points left in the path.
distance is measured as Manhattan distance and defaults to two pixels.
PIL.ImagePath.Path.getbbox()
Gets the bounding box of the path.
Returns (x0, y0, x1, y1)
PIL.ImagePath.Path.map(function)
Maps the path through a function.
PIL.ImagePath.Path.tolist(flat=0)
Converts the path to a Python list [(x, y), . . . ].
Parameters flat – By default, this function returns a list of 2-tuples [(x, y), . . . ]. If this argument
is True, it returns a flat list [x, y, . . . ] instead.
Returns A list of coordinates. See flat.
PIL.ImagePath.Path.transform(matrix)
Transforms the path in place, using an affine transform. The matrix is a 6-tuple (a, b, c, d, e, f), and each point
is mapped as follows:
The ImageQt module contains support for creating PyQt5 or PySide2 QImage objects from PIL images.
New in version 1.1.6.
class ImageQt.ImageQt(image)
Creates an ImageQt object from a PIL Image object. This class is a subclass of QtGui.QImage, which means
that you can pass the resulting objects directly to PyQt5/PySide2 API functions and methods.
This operation is currently supported for mode 1, L, P, RGB, and RGBA images. To handle other modes, you
need to convert the image first.
The ImageSequence module contains a wrapper class that lets you iterate over the frames of an image sequence.
class PIL.ImageSequence.Iterator(im)
This class implements an iterator object that can be used to loop over an image sequence.
You can use the [] operator to access elements by index. This operator will raise an IndexError if you try
to access a nonexistent frame.
Parameters im – An image object.
The ImageStat module calculates global statistics for an image, or for a region of an image.
class PIL.ImageStat.Stat(image_or_list, mask=None)
Calculate statistics for the given image. If a mask is included, only the regions covered by that mask are included
in the statistics. You can also pass in a previously calculated histogram.
Parameters
• image – A PIL image, or a precalculated histogram.
• mask – An optional mask.
extrema
Min/max values for each band in the image.
Note: This relies on the histogram() method, and simply returns the low and high bins used. This
is correct for images with 8 bits per channel, but fails for other modes such as I or F. Instead, use
getextrema() to return per-band extrema for the image. This is more correct and efficient because, for
non-8-bit modes, the histogram method uses getextrema() to determine the bins used.
count
Total number of pixels for each band in the image.
sum
Sum of all pixels for each band in the image.
sum2
Squared sum of all pixels for each band in the image.
mean
Average (arithmetic mean) pixel level for each band in the image.
median
Median pixel level for each band in the image.
rms
RMS (root-mean-square) for each band in the image.
var
Variance for each band in the image.
stddev
Standard deviation for each band in the image.
The ImageTk module contains support to create and modify Tkinter BitmapImage and PhotoImage objects from PIL
images.
For examples, see the demo programs in the Scripts directory.
class PIL.ImageTk.BitmapImage(image=None, **kw)
A Tkinter-compatible bitmap image. This can be used everywhere Tkinter expects an image object.
The given image must have mode “1”. Pixels having value 0 are treated as transparent. Options, if any, are
passed on to Tkinter. The most commonly used option is foreground, which is used to specify the color for the
non-transparent parts. See the Tkinter documentation for information on how to specify colours.
Parameters image – A PIL image.
height()
Get the height of the image.
Returns The height, in pixels.
width()
Get the width of the image.
Returns The width, in pixels.
The ImageWin module contains support to create and display images on Windows.
ImageWin can be used with PythonWin and other user interface toolkits that provide access to Windows device con-
texts or window handles. For example, Tkinter makes the window handle available via the winfo_id method:
from PIL import ImageWin
dib = ImageWin.Dib(...)
hwnd = ImageWin.HWND(widget.winfo_id())
dib.draw(hwnd, xy)
Parameters
• image – Either a PIL image, or a mode string. If a mode string is used, a size must also be
given. The mode can be one of “1”, “L”, “P”, or “RGB”.
• size – If the first argument is a mode string, this defines the size of the image.
draw(handle, dst, src=None)
Same as expose, but allows you to specify where to draw the image, and what part of it to draw.
The destination and source areas are given as 4-tuple rectangles. If the source is omitted, the entire image
is copied. If the source and the destination have different sizes, the image is resized as necessary.
expose(handle)
Copy the bitmap contents to a device context.
Parameters handle – Device context (HDC), cast to a Python integer, or an HDC or HWND
instance. In PythonWin, you can use the CDC.GetHandleAttrib() to get a suitable
handle.
frombytes(buffer)
Load display memory contents from byte data.
Parameters buffer – A buffer containing display data (usually data returned from
<b>tobytes</b>)
paste(im, box=None)
Paste a PIL image into the bitmap image.
Parameters
• im – A PIL image. The size must match the target region. If the mode does not match, the
image is converted to the mode of the bitmap image.
• box – A 4-tuple defining the left, upper, right, and lower pixel coordinate. See Coordinate
System. If None is given instead of a tuple, all of the image is assumed.
query_palette(handle)
Installs the palette associated with the image in the given device context.
This method should be called upon QUERYNEWPALETTE and PALETTECHANGED events from
Windows. If this method returns a non-zero value, one or more display palette entries were changed, and
the image should be redrawn.
Parameters handle – Device context (HDC), cast to a Python integer, or an HDC or HWND
instance.
Returns A true value if one or more entries were changed (this indicates that the image should
be redrawn).
tobytes()
Copy display memory contents to bytes object.
Returns A bytes object containing display data.
class PIL.ImageWin.HDC(dc)
Wraps an HDC integer. The resulting object can be passed to the draw() and expose() methods.
class PIL.ImageWin.HWND(wnd)
Wraps an HWND integer. The resulting object can be passed to the draw() and expose() methods, instead
of a DC.
The ExifTags module exposes two dictionaries which provide constants and clear-text names for various well-
known EXIF tags.
class PIL.ExifTags.TAGS
The TAG dictionary maps 16-bit integer EXIF tag enumerations to descriptive string names. For instance:
class PIL.ExifTags.GPSTAGS
The GPSTAGS dictionary maps 8-bit integer EXIF gps enumerations to descriptive string names. For instance:
The TiffTags module exposes many of the standard TIFF metadata tag numbers, names, and type information.
PIL.TiffTags.lookup(tag)
Parameters tag – Integer tag number
Returns Taginfo namedtuple, From the TAGS_V2 info if possible, otherwise just populating the
value and name from TAGS. If the tag is not recognized, “unknown” is returned for the name
New in version 3.1.0.
class PIL.TiffTags.TagInfo
This dictionary contains a superset of the tags in TAGS_V2, common EXIF tags, and other well known metadata
tags.
PIL.TiffTags.TYPES
The TYPES dictionary maps the TIFF type short integer to a human readable type name.
The PSDraw module provides simple print support for Postscript printers. You can print text, graphics and images
through this module.
class PIL.PSDraw.PSDraw(fp=None)
Sets up printing to the given file. If fp is omitted, sys.stdout is assumed.
begin_document(id=None)
Set up printing of a document. (Write Postscript DSC header.)
end_document()
Ends printing. (Write Postscript DSC footer.)
image(box, im, dpi=None)
Draw a PIL image, centered in the given box.
line(xy0, xy1)
Draws a line between the two points. Coordinates are given in Postscript point coordinates (72 points per
inch, (0, 0) is the lower left corner of the page).
rectangle(box)
Draws a rectangle.
Parameters box – A 4-tuple of integers whose order and function is currently undocumented.
Hint: the tuple is passed into this format string:
%d %d M %d %d 0 Vr
setfont(font, size)
Selects which font to use.
Parameters
• font – A Postscript font name
• size – Size in points.
text(xy, text)
Draws text at the given position. You must use setfont() before calling this method.
The PixelAccess class provides read and write access to PIL.Image data at a pixel level.
Note: Accessing individual pixels is fairly slow. If you are looping over all of the pixels in an image, there is likely a
faster way using other parts of the Pillow API.
3.24.1 Example
The following script loads an image, accesses one pixel from it, then changes it.
px[-1,-1] = (0,0,0)
print (px[-1,-1])
class PixelAccess
Parameters
• xy – The pixel coordinate, given as (x, y).
• color – The pixel value according to its mode. e.g. tuple (r, g, b) for RGB mode)
getpixel(self, xy):
Returns the pixel at x,y. The pixel is returned as a single value for single band images or a tuple for
multiple band images
param xy The pixel coordinate, given as (x, y).
returns a pixel value for single band images, a tuple of pixel values for multiband images.
The PyAccess module provides a CFFI/Python implementation of the PixelAccess Class. This implementation is
far faster on PyPy than the PixelAccess version.
Note: Accessing individual pixels is fairly slow. If you are looping over all of the pixels in an image, there is likely a
faster way using other parts of the Pillow API.
3.25.1 Example
The following script loads an image, accesses one pixel from it, then changes it.
px[-1,-1] = (0,0,0)
print (px[-1,-1])
Reference for modules whose documentation has not yet been ported or written can be found here.
class PIL.BdfFontFile.BdfFontFile(fp)
Bases: PIL.FontFile.FontFile
PIL.BdfFontFile.bdf_char(f )
class PIL.FontFile.FontFile
Bases: object
bitmap = None
compile()
Create metrics and bitmap
save(filename)
Save font
PIL.FontFile.puti16(fp, values)
class PIL.GimpGradientFile.GimpGradientFile(fp)
Bases: PIL.GimpGradientFile.GradientFile
class PIL.GimpGradientFile.GradientFile
Bases: object
getpalette(entries=256)
gradient = None
PIL.GimpGradientFile.curved(middle, pos)
PIL.GimpGradientFile.linear(middle, pos)
PIL.GimpGradientFile.sine(middle, pos)
PIL.GimpGradientFile.sphere_decreasing(middle, pos)
PIL.GimpGradientFile.sphere_increasing(middle, pos)
class PIL.GimpPaletteFile.GimpPaletteFile(fp)
Bases: object
getpalette()
rawmode = 'RGB'
class PIL.ImageShow.DisplayViewer
Bases: PIL.ImageShow.UnixViewer
get_command_ex(file, **options)
class PIL.ImageShow.EogViewer
Bases: PIL.ImageShow.UnixViewer
get_command_ex(file, **options)
class PIL.ImageShow.UnixViewer
Bases: PIL.ImageShow.Viewer
format = 'PNG'
get_command(file, **options)
options = {'compress_level': 1}
show_file(file, **options)
Display given file
class PIL.ImageShow.Viewer
Bases: object
Base class for viewers.
format = None
get_command(file, **options)
get_format(image)
Return format name, or None to save as PGM/PPM
options = {}
save_image(image)
Save to temporary file, and return filename
show(image, **options)
show_file(file, **options)
Display given file
show_image(image, **options)
Display given image
class PIL.ImageShow.XVViewer
Bases: PIL.ImageShow.UnixViewer
get_command_ex(file, title=None, **options)
PIL.ImageShow.register(viewer, order=1)
PIL.ImageShow.show(image, title=None, **options)
Display a given image.
Parameters
• image – An image object.
• title – Optional title. Not all viewers can display the title.
• **options – Additional viewer options.
Returns True if a suitable viewer was found, false otherwise.
class PIL.ImageTransform.AffineTransform(data)
Bases: PIL.ImageTransform.Transform
Define an affine image transform.
This function takes a 6-tuple (a, b, c, d, e, f) which contain the first two rows from an affine transform matrix.
For each pixel (x, y) in the output image, the new value is taken from a position (a x + b y + c, d x + e y + f) in
the input image, rounded to nearest pixel.
This function can be used to scale, translate, rotate, and shear the original image.
See transform()
Parameters matrix – A 6-tuple (a, b, c, d, e, f) containing the first two rows from an affine
transform matrix.
method = 0
class PIL.ImageTransform.ExtentTransform(data)
Bases: PIL.ImageTransform.Transform
Define a transform to extract a subregion from an image.
Maps a rectangle (defined by two corners) from the image to a rectangle of the given size. The resulting image
will contain data sampled from between the corners, such that (x0, y0) in the input image will end up at (0,0) in
the output image, and (x1, y1) at size.
This method can be used to crop, stretch, shrink, or mirror an arbitrary rectangle in the current image. It is
slightly slower than crop, but about as fast as a corresponding resize operation.
See transform()
Parameters bbox – A 4-tuple (x0, y0, x1, y1) which specifies two points in the input image’s
coordinate system. See Coordinate System.
method = 1
class PIL.ImageTransform.MeshTransform(data)
Bases: PIL.ImageTransform.Transform
Define a mesh image transform. A mesh transform consists of one or more individual quad transforms.
See transform()
Parameters data – A list of (bbox, quad) tuples.
method = 4
class PIL.ImageTransform.QuadTransform(data)
Bases: PIL.ImageTransform.Transform
Define a quad image transform.
Maps a quadrilateral (a region defined by four corners) from the image to a rectangle of the given size.
See transform()
Parameters xy – An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain the upper left, lower left,
lower right, and upper right corner of the source quadrilateral.
method = 3
class PIL.ImageTransform.Transform(data)
Bases: PIL.Image.ImageTransformHandler
getdata()
transform(size, image, **options)
quality="preset_name"
qtables="preset_name"
subsampling="preset_name"
Example:
im.save("image_name.jpg", quality="web_high")
Subsampling
Subsampling is the practice of encoding images by implementing less resolution for chroma information than for luma
information. (ref.: https://en.wikipedia.org/wiki/Chroma_subsampling)
Possible subsampling values are 0, 1 and 2 that correspond to 4:4:4, 4:2:2 and 4:2:0.
You can get the subsampling of a JPEG with the JpegImagePlugin.get_sampling(im) function.
In JPEG compressed data a JPEG marker is used instead of an EXIF tag. (ref.: https://www.exiv2.org/tags.html)
Quantization tables
They are values use by the DCT (Discrete cosine transform) to remove unnecessary information from the image
(the lossy part of the compression). (ref.: https://en.wikipedia.org/wiki/Quantization_matrix#Quantization_matrices,
https://en.wikipedia.org/wiki/JPEG#Quantization)
You can get the quantization tables of a JPEG with:
im.quantization
This will return a dict with a number of arrays. You can pass this dict directly as the qtables argument when saving a
JPEG.
The tables format between im.quantization and quantization in presets differ in 3 ways:
1. The base container of the preset is a list with sublists instead of dict. dict[0] -> list[0], dict[1] -> list[1], . . .
2. Each table in a preset is a list instead of an array.
3. The zigzag order is remove in the preset (needed by libjpeg >= 6a).
You can convert the dict format to the preset format with the JpegImagePlugin.convert_dict_qtables(dict_qtables)
function.
Libjpeg ref.: https://web.archive.org/web/20120328125543/http://www.jpegcameras.com/libjpeg/libjpeg-3.html
class PIL.PaletteFile.PaletteFile(fp)
Bases: object
getpalette()
rawmode = 'RGB'
class PIL.PngImagePlugin.iTXt
Bases: str
Subclass of string to allow iTXt chunks to look like strings while keeping their extra information
__new__(cls, text, lang, tkey)
Parameters
• value – value for this key
• lang – language code
• tkey – UTF-8 version of the key name
class PIL.PngImagePlugin.PngInfo
Bases: object
PNG chunk container (for use with save(pnginfo=))
add(cid, data)
Appends an arbitrary chunk. Use with caution.
Parameters
• cid – a byte string, 4 bytes long.
• data – a byte string of the encoded data
add_itxt(key, value, lang=”, tkey=”, zip=False)
Appends an iTXt chunk.
Parameters
• key – latin-1 encodable text key name
• value – value for this key
• lang – language code
• tkey – UTF-8 version of the key name
• zip – compression flag
add_text(key, value, zip=False)
Appends a text chunk.
Parameters
• key – latin-1 encodable text key name
• value – value for this key, text or an PIL.PngImagePlugin.iTXt instance
• zip – compression flag
close()
PIL.WalImageFile.open(filename)
Load texture from a Quake2 WAL texture file.
By default, a Quake2 standard palette is attached to the texture. To override the palette, use the
<b>putpalette</b> method.
Parameters filename – WAL file name, or an opened file handle.
Returns An image instance.
PIL._binary.i16be(c, o=0)
PIL._binary.i16le(c, o=0)
Converts a 2-bytes (16 bits) string to an unsigned integer.
Parameters
• c – string containing bytes to convert
• o – offset of bytes to convert in string
PIL._binary.i32be(c, o=0)
PIL._binary.i32le(c, o=0)
Converts a 4-bytes (32 bits) string to an unsigned integer.
Parameters
• c – string containing bytes to convert
• o – offset of bytes to convert in string
PIL._binary.i8(c)
PIL._binary.o16be(i)
PIL._binary.o16le(i)
PIL._binary.o32be(i)
PIL._binary.o32le(i)
PIL._binary.o8(i)
PIL._binary.si16le(c, o=0)
Converts a 2-bytes (16 bits) string to a signed integer.
Parameters
• c – string containing bytes to convert
• o – offset of bytes to convert in string
PIL._binary.si32le(c, o=0)
Converts a 4-bytes (32 bits) string to a signed integer.
Parameters
• c – string containing bytes to convert
load()
Load image data based on tile list
• info – encoderinfo
Returns tuple of(list of header items, optimized palette)
class PIL.IcnsImagePlugin.IcnsFile(fobj)
Bases: object
SIZES = {(16, 16, 1): [(b'icp4', <function read_png_or_jpeg2000>), (b'is32', <function
bestsize()
dataforsize(size)
Get an icon resource as {channel: array}. Note that the arrays are bottom-up like windows bitmaps and
will likely need to be flipped or transposed in some way.
getimage(size=None)
itersizes()
class PIL.IcnsImagePlugin.IcnsImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile
PIL image support for Mac OS .icns files. Chooses the best resolution, but will possibly load a different size
image if you mutate the size attribute before calling ‘load’.
The info dictionary has a key ‘sizes’ that is a list of sizes that the icns file has.
format = 'ICNS'
format_description = 'Mac OS icns resource'
load()
Load image data based on tile list
size
PIL.IcnsImagePlugin.nextheader(fobj)
PIL.IcnsImagePlugin.read_32(fobj, start_length, size)
Read a 32bit RGB icon resource. Seems to be either uncompressed or an RLE packbits-like scheme.
PIL.IcnsImagePlugin.read_32t(fobj, start_length, size)
PIL.IcnsImagePlugin.read_mk(fobj, start_length, size)
PIL.IcnsImagePlugin.read_png_or_jpeg2000(fobj, start_length, size)
class PIL.IcoImagePlugin.IcoFile(buf )
Bases: object
frame(idx)
Get an image from frame idx
getentryindex(size, bpp=False)
getimage(size, bpp=False)
Get an image from the icon
sizes()
Get a list of all available icon sizes and color depths.
class PIL.IcoImagePlugin.IcoImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile
PIL read-only image support for Microsoft Windows .ico files.
By default the largest resolution image in the file will be loaded. This can be changed by altering the ‘size’
attribute before calling ‘load’.
The info dictionary has a key ‘sizes’ that is a list of the sizes available in the icon file.
Handles classic, XP and Vista icon formats.
When saving, PNG compression is used. Support for this was only added in Windows Vista.
This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis <casadebender@gmail.com>.
https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
format = 'ICO'
format_description = 'Windows Icon'
load()
Load image data based on tile list
load_seek()
size
Returns A dictionary containing IPTC information, or None if no IPTC information block was
found.
PIL.IptcImagePlugin.i(c)
PIL.JpegImagePlugin.APP(self, marker)
PIL.JpegImagePlugin.COM(self, marker)
PIL.JpegImagePlugin.DQT(self, marker)
class PIL.JpegImagePlugin.JpegImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile
draft(mode, size)
Configures the image file loader so it returns a version of the image that as closely as possible matches the
given mode and size. For example, you can use this method to convert a color JPEG to greyscale while
loading it.
If any changes are made, returns a tuple with the chosen mode and box with coordinates of the original
image within the altered one.
Note that this method modifies the Image object in place. If the image has already been loaded, this
method has no effect.
Note: This method is not implemented for most images. It is currently implemented only for JPEG and
MPO images.
Parameters
• mode – The requested mode.
• size – The requested size.
format = 'JPEG'
format_description = 'JPEG (ISO 10918)'
load_djpeg()
load_read(read_bytes)
internal: read more image data For premature EOF and LOAD_TRUNCATED_IMAGES adds EOI marker
so libjpeg can finish decoding
PIL.JpegImagePlugin.SOF(self, marker)
PIL.JpegImagePlugin.Skip(self, marker)
PIL.JpegImagePlugin.convert_dict_qtables(qtables)
PIL.JpegImagePlugin.get_sampling(im)
PIL.JpegImagePlugin.jpeg_factory(fp=None, filename=None)
class PIL.MpegImagePlugin.BitStream(fp)
Bases: object
next()
peek(bits)
read(bits)
skip(bits)
class PIL.MpegImagePlugin.MpegImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile
format = 'MPEG'
format_description = 'MPEG'
PIL.PalmImagePlugin.build_prototype_image()
PIL.PngImagePlugin.getchunks(im, **params)
Return a list of PNG chunks representing this image.
PIL.PngImagePlugin.is_cid()
Matches zero or more characters at the beginning of the string.
PIL.PngImagePlugin.putchunk(fp, cid, *data)
Write a PNG chunk (including CRC field)
class PIL.PngImagePlugin.ChunkStream(fp)
Bases: object
call(cid, pos, length)
Call the appropriate chunk handler
close()
crc(cid, data)
Read and verify checksum
crc_skip(cid, data)
Read checksum. Used if the C module is not present
push(cid, pos, length)
read()
Fetch a new chunk. Returns header information.
verify(endchunk=b’IEND’)
class PIL.PngImagePlugin.PngImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile
format = 'PNG'
format_description = 'Portable network graphics'
getexif()
load_end()
internal: finished reading image data
load_prepare()
internal: prepare to read PNG file
load_read(read_bytes)
internal: read more image data
seek(frame)
Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method
raises an EOFError exception. When a sequence file is opened, the library automatically seeks to frame
0.
See tell().
Parameters frame – Frame number, starting at 0.
Raises EOFError – If the call attempts to seek beyond the end of the sequence.
tell()
Returns the current frame number. See seek().
Returns Frame number, starting with 0.
text
verify()
Verify PNG file
class PIL.PngImagePlugin.PngStream(fp)
Bases: PIL.PngImagePlugin.ChunkStream
check_text_memory(chunklen)
chunk_IDAT(pos, length)
chunk_IEND(pos, length)
chunk_IHDR(pos, length)
chunk_PLTE(pos, length)
chunk_acTL(pos, length)
chunk_cHRM(pos, length)
chunk_eXIf(pos, length)
chunk_fcTL(pos, length)
chunk_fdAT(pos, length)
chunk_gAMA(pos, length)
chunk_iCCP(pos, length)
chunk_iTXt(pos, length)
chunk_pHYs(pos, length)
chunk_sRGB(pos, length)
chunk_tEXt(pos, length)
chunk_tRNS(pos, length)
chunk_zTXt(pos, length)
rewind()
save_rewind()
load_prepare()
seek(layer)
Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method
raises an EOFError exception. When a sequence file is opened, the library automatically seeks to frame
0.
See tell().
Parameters frame – Frame number, starting at 0.
Raises EOFError – If the call attempts to seek beyond the end of the sequence.
tell()
Returns the current frame number. See seek().
Returns Frame number, starting with 0.
tell()
Returns the current frame number. See seek().
Returns Frame number, starting with 0.
tkPhotoImage()
PIL.SpiderImagePlugin.isInt(f )
PIL.SpiderImagePlugin.isSpiderHeader(t)
PIL.SpiderImagePlugin.isSpiderImage(filename)
PIL.SpiderImagePlugin.loadImageSeries(filelist=None)
create a list of Image objects for use in a montage
PIL.SpiderImagePlugin.makeSpiderHeader(im)
rewriteLastShort(value)
rewriteLastShortToLong(value)
seek(offset, whence=0)
setEndian(endian)
setup()
skipIFDs()
tell()
write(data)
writeLong(value)
writeShort(value)
class PIL.TiffImagePlugin.IFDRational(value, denominator=1)
Bases: numbers.Rational
Implements a rational class where 0/0 is a legal value to match the in the wild use of exif rationals.
e.g., DigitalZoomRatio - 0.00/0.00 indicates that no digital zoom was used
denominator
limit_rational(max_denominator)
Parameters max_denominator – Integer, the maximum denominator value
Returns Tuple of (numerator, denominator)
numerator
PIL.TiffImagePlugin.ImageFileDirectory
alias of PIL.TiffImagePlugin.ImageFileDirectory_v1
class PIL.TiffImagePlugin.ImageFileDirectory_v1(*args, **kwargs)
Bases: PIL.TiffImagePlugin.ImageFileDirectory_v2
This class represents the legacy interface to a TIFF tag directory.
Exposes a dictionary interface of the tags in the directory:
ifd = ImageFileDirectory_v1()
ifd[key] = 'Some Data'
ifd.tagtype[key] = TiffTags.ASCII
print(ifd[key])
('Some Data',)
Also contains a dictionary of tag types as read from the tiff image file,
~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype.
Values are returned as a tuple.
Deprecated since version 3.0.0.
classmethod from_v2(original)
Returns an ImageFileDirectory_v1 instance with the same data as is contained in the original
ImageFileDirectory_v2 instance.
Returns ImageFileDirectory_v1
tagdata
tags
to_v2()
Returns an ImageFileDirectory_v2 instance with the same data as is contained in the original
ImageFileDirectory_v1 instance.
Returns ImageFileDirectory_v2
class PIL.TiffImagePlugin.ImageFileDirectory_v2(ifh=b’II*x00x00x00x00x00’, pre-
fix=None)
Bases: collections.abc.MutableMapping
This class represents a TIFF tag directory. To speed things up, we don’t decode tags unless they’re asked for.
Exposes a dictionary interface of the tags in the directory:
ifd = ImageFileDirectory_v2()
ifd[key] = 'Some Data'
ifd.tagtype[key] = TiffTags.ASCII
print(ifd[key])
'Some Data'
Individual values are returned as the strings or numbers, sequences are returned as tuples of the values.
The tiff metadata type of each item is stored in a dictionary of tag types in
~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype. The types are read from a tiff file, guessed from
the type added, or added manually.
Data Structures:
• self.tagtype = {}
– Key: numerical tiff tag number
– Value: integer corresponding to the data type from ~PIL.TiffTags.TYPES‘
New in version 3.0.0.
legacy_api
load(fp)
load_byte(data, legacy_api=True)
load_double(data, legacy_api=True)
load_float(data, legacy_api=True)
load_long(data, legacy_api=True)
load_rational(data, legacy_api=True)
load_short(data, legacy_api=True)
load_signed_byte(data, legacy_api=True)
load_signed_long(data, legacy_api=True)
load_signed_rational(data, legacy_api=True)
load_signed_short(data, legacy_api=True)
load_string(data, legacy_api=True)
load_undefined(data, legacy_api=True)
named()
load()
Load image data based on tile list
seek(frame)
Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method
raises an EOFError exception. When a sequence file is opened, the library automatically seeks to frame
0.
See tell().
Parameters frame – Frame number, starting at 0.
Raises EOFError – If the call attempts to seek beyond the end of the sequence.
tell()
Returns the current frame number. See seek().
Returns Frame number, starting with 0.
When opening a file as an image, Pillow requires a filename, pathlib.Path object, or a file-like object. Pillow
uses the filename or Path to open a file, so for the rest of this article, they will all be treated as a file-like object.
The following are all equivalent:
If a filename or a path-like object is passed to Pillow, then the resulting file object opened by Pillow may also be closed
by Pillow after the Image.Image.load() method is called, provided the associated image does not have multiple
frames.
Pillow cannot in general close and reopen a file, so any access to that file needs to be prior to the close.
Image Lifecycle
• Image.open() Filenames and Path objects are opened as a file. Metadata is read from the open file. The
file is left open for further usage.
• Image.Image.load() When the pixel data from the image is required, load() is called. The current
frame is read into memory. The image can now be used independently of the underlying image file.
If a filename or a Path object was passed to Image.open(), then the file object was opened by Pillow and
is considered to be used exclusively by Pillow. So if the image is a single-frame image, the file will be closed
in this method after the frame is read. If the image is a multi-frame image, (e.g. multipage TIFF and animated
GIF) the image file is left open so that Image.Image.seek() can load the appropriate frame.
• Image.Image.close() Closes the file and destroys the core image object. This is used in the Pillow context
manager support. e.g.:
The lifecycle of a single-frame image is relatively simple. The file must remain open until the load() or close()
function is called or the context manager exits.
Multi-frame images are more complicated. The load() method is not a terminal method, so it should not close the
underlying file. In general, Pillow does not know if there are going to be any requests for additional data until the
caller has explicitly closed the image.
Complications
• TiffImagePlugin has some code to pass the underlying file descriptor into libtiff (if working on an actual
file). Since libtiff closes the file descriptor internally, it is duplicated prior to passing it into libtiff.
• After a file has been closed, operations that require file access will fail:
• Image.Image.load() should close the image file, unless there are multiple frames.
• Image.Image.seek() should never close the image file.
• Users of the library should use a context manager or call Image.Image.close() on any image opened with
a filename or Path object to ensure that the underlying file is closed.
3.28.2 Limits
This page is documentation to the various fundamental size limits in the Pillow implementation.
Internal Limits
• Image sizes cannot be negative. These are checked both in Storage.c and Image.py
• Image sizes may be 0. (Although not in 3.4)
• Maximum pixel dimensions are limited to INT32, or 2^31 by the sizes in the image header.
• Individual allocations are limited to 2GB in Storage.c
• The 2GB allocation puts an upper limit to the xsize of the image of either 2^31 for ‘L’ or 2^29 for ‘RGB’
• Individual memory mapped segments are limited to 2GB in map.c based on the overflow checks. This requires
that any memory mapped image is smaller than 2GB, as calculated by y*stride (so 2Gpx for ‘L’ images, and
.5Gpx for ‘RGB’
• Any call to internal python size functions for buffers or strings are currently returned as int32, not py_ssize_t.
This limits the maximum buffer to 2GB for operations like frombytes and frombuffer.
• This also limits the size of buffers converted using a decoder. (decode.c:127)
Previous Design
Historically there have been two image allocators in Pillow: ImagingAllocateBlock and
ImagingAllocateArray. The first works for images smaller than 16MB of data and allocates one large
chunk of memory of im->linesize * im->ysize bytes. The second works for large images and makes one
allocation for each scan line of size im->linesize bytes. This makes for a very sharp transition between one
allocation and potentially thousands of small allocations, leading to unpredictable performance penalties around the
transition.
New Design
ImagingAllocateArray now allocates space for images as a chain of blocks with a maximum size of 16MB. If
there is a memory allocation error, it falls back to allocating a 4KB block, or at least one scan line. This is now the
default for all internal allocations.
ImagingAllocateBlock is now only used for those cases when we are specifically requesting a single segment
of memory for sharing with other code.
Memory Pools
There is now a memory pool to contain a supply of recently freed blocks, which can then be reused without going
back to the OS for a fresh allocation. This caching of free blocks is currently disabled by default, but can be enabled
and tweaked using three environment variables:
• PILLOW_ALIGNMENT, in bytes. Specifies the alignment of memory allocations. Valid values are powers of 2
between 1 and 128, inclusive. Defaults to 1.
• PILLOW_BLOCK_SIZE, in bytes, K, or M. Specifies the maximum block size for
ImagingAllocateArray. Valid values are integers, with an optional k or m suffix. Defaults to
16M.
• PILLOW_BLOCKS_MAX Specifies the number of freed blocks to retain to fill future memory requests. Any
freed blocks over this threshold will be returned to the OS immediately. Defaults to 0.
Porting
import Image
to this:
The _imaging module has been moved. You can now import it like this:
The image plugin loading mechanism has changed. Pillow no longer automatically imports any file in the Python path
with a name ending in ImagePlugin.py. You will need to import your image plugin manually.
Pillow will raise an exception if the core extension can’t be loaded for any reason, including a version mismatch
between the Python and extension code. Previously PIL allowed Python only code to run if the core extension was not
available.
147
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
About
5.1 Goals
The fork author’s goal is to foster and support active development of PIL through:
• Continuous integration testing via Travis CI, AppVeyor and GitHub Actions
• Publicized development activity on GitHub
• Regular releases to the Python Package Index
5.2 License
Like PIL, Pillow is licensed under the open source PIL Software License
PIL is not setuptools compatible. Please see this Image-SIG post for a more detailed explanation. Also, PIL’s current
bi-yearly (or greater) release schedule is too infrequent to accommodate the large number and frequency of issues
reported.
Note: Prior to Pillow 2.0.0, very few image code changes were made. Pillow 2.0.0 added Python 3 support and
includes many bug fixes from many contributors.
149
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
As more time passes since the last PIL release (1.1.7 in 2009), the likelihood of a new PIL release decreases. However,
we’ve yet to hear an official “PIL is dead” announcement. So if you still want to support PIL, please report issues here
first, then open corresponding Pillow tickets here.
Please provide a link to the first ticket so we can track the issue(s) upstream.
Release Notes
Note: Contributors please include release notes as needed or appropriate with your bug fixes, feature additions and
tests.
6.1 7.1.2
This fixes a regression introduced in 7.1.0 when adding support for APNG files.
When calling seek(n) on a regular PNG where n > 0, it failed to raise an EOFError as it should have done,
resulting in:
AttributeError: 'NoneType' object has no attribute 'read'
6.2 7.1.1
This fixes a regression introduced in 7.1.0 when adding support for APNG files when calling seek and tell:
>>> from PIL import Image
>>> with Image.open("Tests/images/hopper.png") as im:
... im.seek(0)
...
Traceback (most recent call last):
(continues on next page)
151
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
if not self._seek_check(frame):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/
˓→PIL/ImageFile.py", line 306, in _seek_check
return self.__frame
AttributeError: 'PngImageFile' object has no attribute '_PngImageFile__frame'
>>>
6.3 7.1.0
If no quality was specified when saving a JPEG, Pillow internally used a value of zero to indicate that the default
quality should be used. However, this removed the ability to actually save a JPEG with zero quality. This has now
been resolved.
from PIL import Image
im = Image.open("hopper.jpg")
im.save("out.jpg", quality=0)
Three new channel operations have been added: soft_light(), hard_light() and overlay().
PILLOW_VERSION constant
PILLOW_VERSION has been re-added but is deprecated and will be removed in a future release. Use __version__
instead.
It was initially removed in Pillow 7.0.0, but brought back in 7.1.0 to give projects more time to upgrade.
When opening a JPEG image, the comment may now be read into info.
Previously PcfFontFile output only bitmap PIL fonts with ISO 8859-1 encoding, even though the PCF format
supports Unicode, making it hard to work with Pillow with bitmap fonts in languages which use different character
sets.
Now it’s possible to set a different charset encoding in PcfFontFile’s class constructor. By default, it generates
a PIL font file with ISO 8859-1 as before. The generated PIL font file still contains up to 256 characters, but the
character set is different depending on the selected encoding.
To use such a font with ImageDraw.text, call it with a bytes object with the same encoding as the font file.
X11 ImageGrab.grab()
Support has been added for ImageGrab.grab() on Linux using the X server with the XCB library.
An optional xdisplay parameter has been added to select the X server, with the default value of None using the
default X server.
Passing a different value on Windows or macOS will force taking a snapshot using the selected X server; pass an empty
string to use the default X server. XCB support is not included in pre-compiled wheels for Windows and macOS.
6.3.3 Security
When the getbbox() method calculates the bounding box, for an RGB image it trims black pixels. Similarly, for
an RGBA image it would trim black transparent pixels. This is now changed so that if an image has an alpha channel
(RGBA, RGBa, PA, LA, La), any transparent pixels are trimmed.
Added support for reading and writing Animated Portable Network Graphics (APNG) images. The PNG plugin now
supports using the seek() method and the Iterator class to read APNG frame sequences. The PNG plugin
also now supports using the append_images argument to write APNG frame sequences. See APNG sequences for
further details.
6.4 7.0.0
Python 2.7
Pillow has dropped support for Python 2.7, which reached end-of-life on 2020-01-01.
PILLOW_VERSION constant
PIL.*ImagePlugin.__version__ attributes
The version constants of individual plugins have been removed. Use PIL.__version__ instead.
Qt 4 reached end-of-life on 2015-12-19. Its Python bindings are also EOL: PyQt4 since 2018-08-31 and PySide since
2015-10-14.
Support for PyQt4 and PySide has been removed from ImageQt. Please upgrade to PyQt5 or PySide2.
Setting the size of a TIFF image directly (eg. im.size = (256, 256)) throws an error. Use Image.resize
instead.
The default resampling filter has been changed to the high-quality convolution Image.BICUBIC instead of Image.
NEAREST, for the resize() method and the pad(), scale() and fit() functions. Image.NEAREST is still
always used for images in “P” and “1” modes. See Filters to learn the difference. In short, Image.NEAREST is a
very fast filter, but simple and low-quality.
If the draft() method has no effect, it returns None. If it does have an effect, then it previously returned the
image itself. However, unlike other chain methods, draft() does not return a modified version of the image, but
modifies it in-place. So instead, if draft() has an effect, Pillow will now return a tuple of the image mode and
a co-ordinate box. The box is the original coordinates in the bounds of resulting image. This may be useful in a
subsequent resize() call.
Pillow will now throw a custom UnidentifiedImageError when an image cannot be identified. For backwards
compatibility, this will inherit from OSError.
Speeds up resizing by resizing the image in two steps. The bigger reducing_gap, the closer the result to the fair
resampling. The smaller reducing_gap, the faster resizing. With reducing_gap greater or equal to 3.0, the
result is indistinguishable from fair resampling.
The default value for resize() is None, which means that the optimization is turned off by default.
The default value for thumbnail() is 2.0, which is very close to fair resampling while still being faster in many
cases. In addition, the same gap is applied when thumbnail() calls draft(), which may greatly improve the
quality of JPEG thumbnails. As a result, thumbnail() in the new version provides equally high speed and high
quality from any source (JPEG or arbitrary images).
reduce() is a highly efficient operation to reduce an image by integer times. Normally, it shouldn’t be used
directly. Used internally by resize() and thumbnail() methods to speed up resize when a new argument
reducing_gap is set.
On Windows, Pillow can read WMF files, with a default DPI of 72. An image can now also be loaded at another
resolution:
Image.__del__
Implicitly closing the image’s underlying file in Image.__del__ has been removed. Use a context manager or call
close() instead to close the file in a deterministic way.
Previous method:
im = Image.open("hopper.png")
im.save("out.jpg")
Use instead:
When calculating the new dimensions in thumbnail(), round to the nearest integer, instead of always rounding
down. This better preserves the original aspect ratio.
When the image width or height is not divisible by 8 the last row and column in the image get the correct weight after
JPEG DCT scaling.
6.5 6.2.2
6.5.1 Security
6.6 6.2.1
Deprecations
Python 2.7
Pillow 7.0.0 will be released on 2020-01-01 and will drop support for Python 2.7, making Pillow 6.2.x the last release
series to support Python 2.
6.7 6.2.0
Text stroking
stroke_width and stroke_fill arguments have been added to text drawing operations. They allow text to be
outlined, setting the width of the stroke and and the color respectively. If not provided, stroke_fill will default
to the fill parameter.
For example,
An all_screens argument has been added to ImageGrab.grab. If True, all monitors will be included in the
created image.
Image.getexif
To allow for lazy loading of Exif data, Image.getexif() now returns a shared instance of Image.Exif.
Deprecations
Image.frombuffer
There has been a longstanding warning that the defaults of Image.frombuffer may change in the future for the
“raw” decoder. The change will now take place in Pillow 7.0.
6.7.3 Security
This release catches several buffer overruns, as well as addressing CVE-2019-16865. The CVE is regarding DOS
problems, such as consuming large amounts of memory, or taking a large amount of time to process an image.
In RawDecode.c, an error is now thrown if skip is calculated to be less than zero. It is intended to skip padding between
lines, not to go backwards.
In PsdImagePlugin, if the combined sizes of the individual parts is larger than the declared size of the extra data field,
then it looked for the next layer by seeking backwards. This is now corrected by seeking to (the start of the layer + the
size of the extra data field) instead of (the read parts of the layer + the rest of the layer).
Decompression bomb checks have been added to GIF and ICO formats.
An error is now raised if a TIFF dimension is a string, rather than trying to perform operations on it.
.exe installers fell out of favour with PEP 527, and will be deprecated in Python 3.8. Pillow will no longer be distribut-
ing them. Wheels should be used instead.
When building libwebp for inclusion in wheels, Pillow now adds the -O3 and -DNDEBUG CFLAGS. These flags
would be used by default if building libwebp without debugging, and using them fixes a significant decrease in speed
when a wheel-installed copy of Pillow performs libwebp operations.
6.8 6.1.0
6.8.1 Deprecations
Image.__del__
im = Image.open("hopper.png")
im.save("out.jpg")
Use instead:
Image.entropy
Calculates and returns the entropy for the image. A bilevel image (mode “1”) is treated as a greyscale (“L”) image by
this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask
image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode “1”)
or a greyscale image (“L”).
ImageGrab.grab
ImageSequence.all_frames
A new method to facilitate applying a given function to all frames in an image, or to all frames in a list of images. The
frames are returned as a list of separate images. For example, ImageSequence.all_frames(im, lambda
im_frame: im_frame.rotate(90)) could be used to return all frames from an image, each rotated 90 de-
grees.
Variation fonts
Variation fonts are now supported, allowing for different styles from the same font file. ImageFont.
FreeTypeFont has four new methods, PIL.ImageFont.FreeTypeFont.get_variation_names()
and PIL.ImageFont.FreeTypeFont.set_variation_by_name() for using named styles, and
PIL.ImageFont.FreeTypeFont.get_variation_axes() and PIL.ImageFont.FreeTypeFont.
set_variation_by_axes() for using font axes instead. An IOError will be raised if the font is not a variation
font. FreeType 2.9.1 or greater is required.
ImageTk.getimage
This function is now supported. It returns the contents of an ImageTk.PhotoImage as an RGBA Image.Image
instance.
The TIFF encoder accepts a quality parameter for jpeg compressed TIFF files. A value from 0 (worst) to 100
(best) controls the image quality, similar to the JPEG encoder. The default is 75. For example:
The TIFF encoder supports more types, especially arrays. This is required for the GeoTIFF format which encodes
geospatial information.
• Pass tagtype from v2 directory to libtiff encoder, instead of autodetecting type.
• Use explicit types eg. uint32_t for TIFF_LONG to fix issues on platforms with 64-bit longs.
• Add support for multiple values (arrays). Requires type in v2 directory and values must be passed as a tuple.
• Add support for signed types eg. TIFFTypes.TIFF_SIGNED_SHORT.
This variable is commonly used by other build systems and using it can help with cross-compiling. Falls back to
pkg-config as before.
Drawing text in the ‘ttb’ direction with ImageFont has been significantly improved and requires Raqm 0.7 or greater.
6.9 6.0.0
Python 3.4 is EOL since 2019-03-16 and no longer supported. We will not be creating binaries, testing, or retaining
compatibility with this version. The final version of Pillow for Python 3.4 is 5.4.1.
PIL.OleFileIO was removed as a vendored file and in Pillow 4.0.0 (2017-01) in favour of the upstream olefile Python
package, and replaced with an ImportError. The deprecated file has now been removed from Pillow. If needed,
install from PyPI (eg. pip install olefile).
Several undocumented functions in ImageOps were deprecated in Pillow 4.3.0 (2017-10) and have now been re-
moved: gaussian_blur, gblur, unsharp_mask, usm and box_blur. Use the equivalent operations in
ImageFilter instead.
VERSION (the old PIL version, always 1.1.7) has been removed. Use __version__ instead.
Deprecations
Python 2.7
Qt 4 reached end-of-life on 2015-12-19. Its Python bindings are also EOL: PyQt4 since 2018-08-31 and PySide since
2015-10-14.
Support for PyQt4 and PySide has been deprecated from ImageQt and will be removed in a future version. Please
upgrade to PyQt5 or PySide2.
PIL.*ImagePlugin.__version__ attributes
These version constants have been deprecated and will be removed in a future version.
• BmpImagePlugin.__version__
• CurImagePlugin.__version__
• DcxImagePlugin.__version__
• EpsImagePlugin.__version__
• FliImagePlugin.__version__
• FpxImagePlugin.__version__
• GdImageFile.__version__
• GifImagePlugin.__version__
• IcoImagePlugin.__version__
• ImImagePlugin.__version__
• ImtImagePlugin.__version__
• IptcImagePlugin.__version__
• Jpeg2KImagePlugin.__version__
• JpegImagePlugin.__version__
• McIdasImagePlugin.__version__
• MicImagePlugin.__version__
• MpegImagePlugin.__version__
• MpoImagePlugin.__version__
• MspImagePlugin.__version__
• PalmImagePlugin.__version__
• PcdImagePlugin.__version__
• PcxImagePlugin.__version__
• PdfImagePlugin.__version__
• PixarImagePlugin.__version__
• PngImagePlugin.__version__
• PpmImagePlugin.__version__
• PsdImagePlugin.__version__
• SgiImagePlugin.__version__
• SunImagePlugin.__version__
• TgaImagePlugin.__version__
• TiffImagePlugin.__version__
• WmfImagePlugin.__version__
• XbmImagePlugin.__version__
• XpmImagePlugin.__version__
• XVThumbImagePlugin.__version__
Use PIL.__version__ instead.
ImageCms.CmsProfile attributes
Some attributes in ImageCms.CmsProfile have been deprecated since Pillow 3.2.0. From 6.0.0, they issue a
DeprecationWarning:
Previously, all JPEG2000 images had the MIME type “image/jpx”. This has now been corrected. After the
file format drivers have been loaded, Image.MIME["JPEG2000"] will return “image/jp2”. ImageFile.
get_format_mimetype will return “image/jpx” if a JPX profile is present, or “image/jp2” otherwise.
Previously, all SGI images had the MIME type “image/rgb”. This has now been corrected. After the file format drivers
have been loaded, Image.MIME["SGI"] will return “image/sgi”. ImageFile.get_format_mimetype will
return “image/rgb” if RGB image data is present, or “image/sgi” otherwise.
MIME types have been added to the PPM format. After the file format drivers have been loaded, Image.
MIME["PPM"] will now return the generic “image/x-portable-anymap”. ImageFile.get_format_mimetype
will return a MIME type specific to the color type.
The TGA, PCX and ICO formats also now have MIME types: “image/x-tga”, “image/x-pcx” and “image/x-icon”
respectively.
Pillow now supports reading and writing the Device Independent Bitmap file format.
Image.quantize
The dither option is now a customisable parameter (was previously hardcoded to 1). This parameter takes the same
values used in convert().
These text-rendering functions now accept a language parameter to request language-specific glyphs and ligatures
from the font:
• ImageDraw.ImageDraw.multiline_text()
• ImageDraw.ImageDraw.multiline_textsize()
• ImageDraw.ImageDraw.text()
• ImageDraw.ImageDraw.textsize()
• ImageFont.ImageFont.getmask()
• ImageFont.ImageFont.getsize_multiline()
• ImageFont.ImageFont.getsize()
getexif() has been added, which returns an Exif instance. Values can be retrieved and set like a dictionary. When
saving JPEG, PNG or WEBP, the instance can be passed as an exif argument to include any changes in the output
image.
Added ImageOps.exif_transpose
exif_transpose() returns a copy of an image, transposed according to its EXIF Orientation tag.
EXIF data can now be read from and saved to PNG images. However, unlike other image formats, EXIF data is not
guaranteed to be present in info until load() has been called.
Pillow can now read uncompressed RGB data from DDS images.
Added support reading TIFF files with old-style JPEG compression through LibTIFF. All YCbCr TIFF images are
now always read as RGB.
Support has been added for the LZMA, Zstd and WebP TIFF compression codecs.
I;16, I;16L and I;16B are now supported image modes for all transpose() operations.
6.10 5.4.1
A change to the way Pillow detects libraries during installed prevented installation on Termux, which does not have
/sbin/ldconfig. This is now fixed.
Some PNG images have multiple IDAT chunks. In some cases, Pillow will stop reading image data before the IDAT
chunks finish. A regression caused an EOFError exception when previously there was none. This is now fixed, and
file reading continues in case there are subsequent text chunks.
The addition of limited APNG support to the PNG plugin also overwrote the MIME type for PNG files, causing
“image/apng” to be returned as the MIME type of both APNG and PNG files. This has been fixed so the MIME type
of PNG files is “image/png”.
A regression caused an unsupported image file to report a ValueError: seek of closed file exception
instead of an OSError. This has been fixed by ensuring that image plugins only close their internal __fp if they are
not the same as ImageFile’s fp, allowing each to manage their own file pointers.
6.11 5.4.0
Animated Portable Network Graphics (APNG) images are not fully supported but can be opened via the PNG plugin
to get some basic info:
im = Image.open("image.apng")
print(im.mode) # "RGBA"
print(im.size) # (245, 245)
im.show() # Shows a single frame
You can check if Pillow has been built against the libjpeg-turbo version of the libjpeg library:
When accessing individual image pixels, negative indexes are now also accepted. For example, to get or set the farthest
pixel in the lower right of an image:
px = im.load()
print(px[-1, -1])
px[-1, -1] = (0, 0, 0)
TIFF images can now be saved with custom integer, float and string TIFF tags:
im2 = Image.open("output.tif")
print(im2.tag_v2[37000]) # 4
print(im2.tag_v2[37002]) # "custom tag value"
print(im2.tag_v2[37004]) # b"custom tag value"
ImageOps.fit
Now uses one resize operation with box parameter internally instead of a crop and scale operations sequence. This
improves the performance and accuracy of cropping since the box parameter accepts float values.
6.12 5.3.0
Image size
If you attempt to set the size of an image directly, e.g. im.size = (100, 100), you will now receive an
AttributeError. This is not about removing existing functionality, but instead about raising an explicit error
to prevent later consequences. The resize method is the correct way to change an image’s size.
The exceptions to this are:
• The ICO and ICNS image formats, which use im.size = (100, 100) to select a subimage.
• The TIFF image format, which now has a DeprecationWarning for this action, as direct image size setting
was previously necessary to work around an issue with tile extents.
An optional line width parameter has been added to ImageDraw.Draw.arc, chord, ellipse, pieslice
and rectangle.
ImageDraw.Draw.line draws a line, or lines, between points. Previously, when multiple points are given, for a
larger width, the joints between these lines looked unsightly. There is now an additional optional argument, joint,
defaulting to None. When it is set to curved, the joints between the lines will become rounded.
ImageOps.colorize
Previously ImageOps.colorize only supported two-color mapping with black and white arguments being
mapped to 0 and 255 respectively. Now it supports three-color mapping with the optional mid parameter, and the po-
sitions for all three color arguments can each be optionally specified (blackpoint, whitepoint and midpoint).
For example, with all optional arguments:
ImageOps.pad
While ImageOps.fit allows users to crop images to a requested aspect ratio and size, new method ImageOps.
pad pads images to fill a requested aspect ratio and size, filling new space with a provided color and positioning the
image within the new area through a centering argument.
Added support for reading tiled TIFF images through LibTIFF. Compressed TIFF images are now read through
LibTIFF.
RGB WebP images are now read as RGB mode, rather than RGBX.
6.13 5.2.0
Deprecations
These version constants have been deprecated. VERSION will be removed in Pillow 6.0.0, and PILLOW_VERSION
will be removed after that.
• PIL.VERSION (old PIL version 1.1.7)
• PIL.PILLOW_VERSION
• PIL.Image.VERSION
• PIL.Image.PILLOW_VERSION
Use PIL.__version__ instead.
ImageColor.getrgb
Previously Image.rotate only supported HSL color strings. Now HSB and HSV strings are also supported, as
well as float values. For example, ImageColor.getrgb("hsv(180,100%,99.5%)").
ImageFile.get_format_mimetype
ImageFile.get_format_mimetype has been added to return the MIME type of an image file, where available.
For example, Image.open("hopper.jpg").get_format_mimetype() returns "image/jpeg".
ImageFont.getsize_multiline
A new method to return the size of multiline text, for example font.getsize_multiline("ABC\nAaaa")
Image.rotate
A new named parameter, fillcolor, has been added to Image.rotate. This color specifies the background
color to use in the area outside the rotated image. This parameter takes the same color specifications as used in
Image.new.
Pillow can now read and write LA data (in addition to L, P, RGB and RGBA), and write RLE data (in addition to
uncompressed).
Build macOS wheels with Xcode 6.4, supporting older macOS versions
The macOS wheels for Pillow 5.1.0 were built with Xcode 9.2, meaning 10.12 Sierra was the lowest supported version.
Prior to Pillow 5.1.0, Xcode 8 was used, supporting El Capitan 10.11.
Instead, Pillow 5.2.0 is built with the oldest available Xcode 6.4 to support at least 10.10 Yosemite.
Re: “version constants deprecated” listed above, as user gnbl notes in #3082:
• it’s confusing that PIL.VERSION returns the version string of the former PIL instead of Pillow’s
• there does not seem to be documentation on this version number (why this, will it ever change, ..) e.g. at
https://pillow.readthedocs.io/en/5.1.x/about.html#why-a-fork
• it’s confusing that PIL.version is a module and does not return the version information directly or hints on how
to get it
• the package information header is essentially useless (placeholder, does not even mention Pillow, nor the ver-
sion)
• PIL._version module documentation comment could explain how to access the version information
We have attempted to resolve these issues in #3083, #3090 and #3218.
6.14 5.1.0
Pillow now supports reading the BLP “Blizzard Mipmap” file format used for tiles in Blizzard’s engine.
Pillow can now open TIFF files with base modes of RGB, YCbCr, and CMYK with up to 6 8-bit channels, discarding
any extra channels if the content is tagged as UNSPECIFIED. Pillow still does not store more than 4 8-bit channels of
image data.
Images can now be appended to PDF files in place by passing in append=True when saving the image.
6.15 5.0.0
Python 3.3 is EOL and no longer supported due to moving testing from nose, which is deprecated, to pytest, which
doesn’t support Python 3.3. We will not be creating binaries, testing, or retaining compatibility with this version. The
final version of Pillow for Python 3.3 is 4.3.0.
Pillow has previously emitted warnings for images that are unexpectedly large and may be a denial of service. These
warnings are now upgraded to DecompressionBombErrors for images that are twice the size of images that
trigger the DecompressionBombWarning. The default threshold is 128Mpx, or 0.5GB for an RGB or RGBA
image. This can be disabled or changed by setting Image.MAX_IMAGE_PIXELS = None.
Scripts
The scripts formerly installed by Pillow have been split into a separate package, pillow-scripts, living at https://github.
com/python-pillow/pillow-scripts .
OleFileIO.py
The olefile module is no longer a required dependency when installing Pillow. Support for plugins requiring olefile
will not be loaded if it is not installed. This allows library consumers to avoid installing this dependency if they choose.
Some library consumers have little interest in the format support and would like to keep dependencies to a minimum.
Further, the vendored version was removed in Pillow 4.0.0 and replaced with a deprecation warning that PIL.OleFileIO
would be removed in a future version. This warning has been upgraded to an import error pending future removal.
Several image plugins supported a named check parameter on their nominally private _save method to preflight if
the image could be saved in that format. That parameter has been removed.
Image.transform
A new named parameter, fillcolor, has been added to Image.transform. This color specifies the background
color to use in the area outside the transformed area in the output image. This parameter takes the same color specifi-
cations as used in Image.new.
GIF Disposal
Multiframe GIF images now take an optional disposal parameter to specify the disposal option for changed pixels.
Previously, there were some compression modes (JPEG, Packbits, and LZW) that were supported with Pillow’s internal
TIFF decoder. All compressed TIFFs are now read using the libtiff decoder, as it implements the compression
schemes more correctly.
The libraqm dependency for complex text scripts is now linked dynamically at runtime rather than at packaging time.
This allows us to release binaries with support for libraqm if it is installed on the user’s machine.
The Pillow source is now stored within the src directory of the distribution. This prevents accidental imports of the
PIL directory when running Python from the project directory.
Setup.py Changes
Multiarch support on Linux should be more robust, especially on Debian derivatives on ARM platforms. Debian’s
multiarch platform configuration is run in preference to the sniffing of machine platform and architecture.
6.16 4.3.0
Deprecations
Several undocumented functions in ImageOps have been deprecated: gaussian_blur, gblur, unsharp_mask,
usm and box_blur. Use the equivalent operations in ImageFilter instead. These functions will be removed in
a future release.
• TIFF tags with unknown type/quantity now default to being bare values if they are 1 element, where previously
they would be a single element tuple. This is only with the new api, not the legacy api. This normalizes the
handling of fields, so that the metadata with inferred or image specified counts are handled the same as metadata
with count specified in the TIFF spec.
• The PhotoshopInfo, XMP, and JPEGTables tags now have a defined type (bytes) and a count of 1.
• The ImageJMetaDataByteCounts tag now has an arbitrary number of items, as there can be multiple
items, one for UTF-8, and one for UTF-16.
These are internal functions that should not have been used by user code, but they were accessible from the python
layer.
Debugging code within Image.core.grabclipboard was removed. It had been marked as will be
removed in future versions since PIL. When enabled, it identified the format of the clipboard data.
The PIL.Image.core.copy and PIL.Image.Image.im.copy2 methods have been removed.
The PIL.Image.core.getcount methods have been removed, use PIL.Image.core.
get_stats()['new_count'] property instead.
A new method PIL.Image.Image.getchannel() has been added to return a single channel by index or name.
For example, image.getchannel("A") will return alpha channel as separate image. getchannel should work
up to 6 times faster than image.split()[0] in previous Pillow versions.
Box Blur
A new filter, PIL.ImageFilter.BoxBlur, has been added. This is a filter with similar results to a Gaussian blur,
but is much faster.
Partial Resampling
Added new argument box for PIL.Image.Image.resize(). This argument defines a source rectangle from
within the source image to be resized. This is very similar to the image.crop(box).resize(size) sequence
except that box can be specified with subpixel accuracy.
Multiband Filters
There is a new PIL.ImageFilter.MultibandFilter base class for image filters that can run on all channels
of an image in one operation. The original PIL.ImageFilter.Filter class remains for image filters that can
process only single band images, or require splitting of channels prior to filtering.
Pillow now can read 16-bit multichannel TIFF files including files with alpha transparency. The image data is truncated
to 8-bit precision.
Pillow now can read 16-bit signed integer single channel TIFF files. The image data is promoted to 32-bit for storage
and processing.
SGI Images
Pillow can now read and write uncompressed 16-bit multichannel SGI images to and from RGB and RGBA formats.
The image data is truncated to 8-bit precision.
Pillow can now read RLE encoded SGI images in both 8 and 16-bit precision.
Performance
CMYK Conversion
The basic CMYK->RGB conversion has been tweaked to match the formula from Google Chrome. This produces
an image that is generally lighter than the previous formula, and more in line with what color managed applications
produce.
6.17 4.2.1
A change in the 4.2.0 cycle broke the Windows PyPy build. This has been fixed, and PyPy is now part of the Windows
CI matrix.
6.18 4.2.0
Pillow now supports complex text rendering for scripts requiring glyph composition and bidirectional flow. This
optional feature adds three dependencies: harfbuzz, fribidi, and raqm. See the install documentation for further details.
This feature is tested and works on Unix and Mac, but has not yet been built on Windows platforms.
• PIL.ImageDraw.floodfill() has a new optional parameter: threshold. This specifies a tolerance for the
color to replace with the flood fill.
• The TIFF and PDF image writers now support the append_images optional parameter for specifying addi-
tional images to create multipage outputs.
PIL.Image.Image.crop() now may raise a DecompressionBomb warning if the crop region enlarges the image
over the threshold specified by PIL.Image.MAX_PIXELS.
The unused function Image.core.new_array was removed. This is an internal function that should not have
been used by user code, but it was accessible from the python layer.
6.19 4.1.1
Some JPEG images don’t contain DPI information in the image metadata, but do contain it in the EXIF data. A patch
was added in 4.1.0 to read from the EXIF data, but it did not accept all possible types that could be included there.
This fix adds the ability to read ints as well as rational values.
CPython 3.6.1 added a new symbol, PySlice_GetIndicesEx, which was not present in 3.6.0. This had the effect
of causing binaries compiled on CPython 3.6.1 to not work on installations of C-Python 3.6.0. This fix undefines
PySlice_GetIndicesEx if it exists to restore compatibility with both 3.6.0 and 3.6.1. See https://bugs.python.org/
issue29943 for more details.
6.20 4.1.0
The file handling when opening images has been overhauled. Previously, Pillow would attempt to close some, but not
all image formats after loading the image data. Now, the following behavior is specified:
• For images where an open file is passed in, it is the responsibility of the calling code to close the file.
• For images where Pillow opens the file and the file is known to have only one frame, the file is closed after
loading.
• If the file has more than one frame, or if it can’t be determined, then the file is left open to permit seeking to
subsequent frames. It will be closed, eventually, in the close or __del__ methods.
• If the image is memory mapped, then we can’t close the mapping to the underlying file until we are done with
the image. The mapping will be closed in the close or __del__ method.
The PIL.GifImagePlugin code has been refactored to fix the flow when saving images. There are two external
changes that arise from this:
• An PIL.ImagePalette.ImagePalette object is now accepted as a specified palette argument in PIL.
Image.Image.save().
• The image to be saved is no longer modified in place by any of the operations of the save function. Previously
it was modified when optimizing the image palette.
This refactor fixed some bugs with palette handling when saving multiple frame GIFs.
The method PIL.Image.Image.remap_palette() has been added. This method was hoisted from the GifIm-
agePlugin code used to optimize the palette.
6.20.5 Added Decoder Registry and Support for Python Based Decoders
There is now a decoder registry similar to the image plugin registries. Image plugins can register a decoder, and it will
be called when the decoding is requested. This allows for the creation of pure Python decoders. While the Python
decoders will not be as fast as their C based counterparts, they may be easier and quicker to develop or safer to run.
6.20.6 Tests
Many tests have been added, including correctness tests for image formats that have been previously untested.
We are now running automated tests in Docker containers against more Linux versions than are provided on Travis CI,
which is currently Ubuntu 14.04 x64. This Pillow release is tested on 64-bit Alpine, Arch, Ubuntu 12.04 and 16.04,
and 32-bit Debian Stretch and Ubuntu 14.04. This also covers a wider range of dependency versions than are provided
on Travis natively.
6.21 4.0.0
Pillow 4.0 no longer supports Python 2.6 and 3.2. We will not be creating binaries, testing, or retaining compatibility
with these releases. This release removes some workarounds for those Python releases, so the final working version
of Pillow on 2.6 or 3.2 is 3.4.2.
6.21.3 OleFileIO.py
OleFileIO.py has been removed as a vendored file and is now installed from the upstream olefile pypi package. All
internal dependencies are redirected to the olefile package. Direct accesses to PIL.OlefileIO raises a deprecation
warning, then patches the upstream olefile into sys.modules in its place.
It is now possible to save images in modes L, RGB, and RGBA to the uncompressed SGI image format.
Pillow 3.4.0 removed support for creating images with (0,0) size. This has been reenabled, restoring pre 3.4 behavior.
The handles_eof flag for decoding images has been removed, as there were no internal users of the flag. Anyone
maintaining image decoders outside of the Pillow source tree should consider using the cleanup function pointers
instead.
The stretch function on the core image object has been removed. This used to be for enlarging the image, but has been
aliased to resize recently.
6.22 3.4.0
Two new filters available for Image.resize() and Image.thumbnail() functions: BOX and HAMMING. BOX
is the high-performance filter with two times shorter window than BILINEAR. It can be used for image reduction 3
and more times and produces a sharper result than BILINEAR.
HAMMING filter has the same performance as BILINEAR filter while providing the image downscaling quality com-
parable to BICUBIC. Both new filters don’t show good quality for the image upscaling.
JPEG images cannot contain an alpha channel. Pillow prior to 3.4.0 silently drops the alpha channel. With this release
Pillow will now issue a DeprecationWarning when attempting to save a RGBA mode image as a JPEG. This will
become an error in Pillow 4.2.
Pillow can now decode DXT3 images, as well as the previously supported DXT1 and DXT5 formats. All three formats
are now decoded in C code for better performance.
Additional frames can now be appended when saving a GIF file, through the append_images argument. The new
frames are passed in as a list of images, which may be have multiple frames themselves.
Note that the append_images argument is only used if save_all is also in effect, e.g.:
Multiple frames can now be saved in a TIFF file by using the save_all option. e.g.:
The nominally private/debugging function Image.core.open_ppm has been removed. If you were using this
function, please use Image.open instead.
6.23 3.3.2
Pillow prior to 3.3.2 may experience integer overflow errors in map.c when reading specially crafted image files. This
may lead to memory disclosure or corruption.
Specifically, when parameters from the image are passed into Image.core.map_buffer, the size of the im-
age was calculated with xsize * ysize * bytes_per_pixel. This will overflow if the result is larger than
SIZE_MAX. This is possible on a 32-bit system.
Furthermore this size value was added to a potentially attacker provided offset value and compared to the size of
the buffer without checking for overflow or negative values.
These values were then used for creating pointers, at which point Pillow could read the memory and include it in other
images. The image was marked readonly, so Pillow would not ordinarily write to that memory without duplicating the
image first.
This issue was found by Cris Neckar at Divergent Security.
Pillow prior to 3.3.2 and PIL 1.1.7 (at least) do not check for negative image sizes in ImagingNew in Storage.c.
A negative image size can lead to a smaller allocation than expected, leading to arbitrary writes.
This issue was found by Cris Neckar at Divergent Security.
6.24 3.3.0
There is now support for using libimagequant as a higher quality quantization option in Image.quantize() on
Unix-like platforms. This support requires building Pillow from source against libimagequant. We cannot distribute
binaries due to licensing differences.
There are two new options to control the build_ext task in setup.py:
• --debug dumps all of the directories and files that are checked when searching for libraries or headers when
building the extensions.
• --disable-platform-guessing removes many of the directories that are checked for libraries and head-
ers for build systems or cross compilers that specify that information in via environment variables.
6.24.3 Resizing
Image resampling for 8-bit per channel images was rewritten using only integer computings. This is faster on most
platforms and doesn’t introduce precision errors on the wide range of scales. With other performance improvements,
this makes resampling 60% faster on average.
Color calculation for images in the LA mode on semitransparent pixels was fixed.
6.24.4 Rotation
Rotation for angles divisible by 90 degrees now always uses transposition. This greatly improves both quality and
performance in this case. Also, the bug with wrong image size calculation when rotating by 90 degrees was fixed.
The return type for binary data in version 2 Exif and Tiff metadata has been changed from a tuple of integers to bytes.
This is a change from the behavior since 3.0.0.
6.25 3.2.0
The DdsImagePlugin reading DXT1 and DXT5 encoded .dds images was added. DXT3 images are not currently
supported.
The FtexImagePlugin reads textures used for 3D objects in Independence War 2: Edge Of Chaos. The plugin
reads a single texture per file, in the .ftc (compressed) and .ftu (uncompressed) formats.
The GbrImagePlugin (GIMP brush format) has been updated to fix support for version 1 files and add support for
version 2 files.
ImageSequence.Iterator is now an actual iterator implementing the Iterator protocol. It is also now possible
to seek to the first image of the file when using direct indexing.
6.26 3.1.2
Pillow between 2.5.0 and 3.1.1 may overflow a buffer when writing large Jpeg2000 files, allowing for code execution
or other memory corruption.
This occurs specifically in the function j2k_encode_entry, at the line:
This vulnerability requires a particular value for height * width such that height * width *
components * precision overflows, at which point the malloc will be for a smaller value than expected. The
buffer that is allocated will be ((height * width * components * precision) mod (2^31) / 8),
where components is 1-4 and precision is either 8 or 16. Common values would be 4 components at precision 8 for a
standard RGBA image.
The unpackers then split an image that is laid out:
RGBARGBARGBA....
into:
RRR.
GGG.
BBB.
AAA.
If this buffer is smaller than expected, the jpeg2k unpacker functions will write outside the allocation and onto the
heap, corrupting memory.
This issue was found by Alyssa Besseling at Atlassian.
6.27 3.1.1
Pillow 3.1.0 and earlier when linked against libtiff >= 4.0.0 on x64 may overflow a buffer when reading a specially
crafted tiff file.
Specifically, libtiff >= 4.0.0 changed the return type of TIFFScanlineSize from int32 to machine dependent
int32|64. If the scanline is sized so that it overflows an int32, it may be interpreted as a negative number, which
will then pass the size check in TiffDecode.c line 236. To do this, the logical scanline size has to be > 2gb, and
for the test file, the allocated buffer size is 64k against a roughly 4gb scan line size. Any image data over 64k is written
over the heap, causing a segfault.
This issue was found by security researcher FourOne.
In all versions of Pillow, dating back at least to the last PIL 1.1.7 release, FliDecode.c has a buffer overflow error.
Around line 192:
case 16:
/* COPY chunk */
for (y = 0; y < state->ysize; y++) {
UINT8* buf = (UINT8*) im->image[y];
memcpy(buf+x, data, state->xsize);
data += state->xsize;
}
break;
The memcpy has error where x is added to the target buffer address. X is used in several internal temporary variable
roles, but can take a value up to the width of the image. Im->image[y] is a set of row pointers to segments of
memory that are the size of the row. At the max y, this will write the contents of the line off the end of the memory
buffer, causing a segfault.
This issue was found by Alyssa Besseling at Atlassian
In all versions of Pillow, dating back at least to the last PIL 1.1.7 release, PcdDecode.c has a buffer overflow error.
The state.buffer for PcdDecode.c is allocated based on a 3 bytes per pixel sizing, where PcdDecode.c
wrote into the buffer assuming 4 bytes per pixel. This writes 768 bytes beyond the end of the buffer into other Python
object storage. In some cases, this causes a segfault, in others an internal Python malloc error.
If a large value was passed into the new size for an image, it is possible to overflow an int32 value passed into malloc.
kk = malloc(xsize * kmax * sizeof(float)); . . . xbounds = malloc(xsize * 2 * sizeof(int));
xsize is trusted user input. These multiplications can overflow, leading the malloc’d buffer to be undersized. These
allocations are followed by a loop that writes out of bounds. This can lead to corruption on the heap of the Python
process with attacker controlled float data.
This issue was found by Ned Williamson.
6.28 3.1.0
6.28.1 ImageDraw arc, chord and pieslice can now use floats
There is no longer a need to ensure that the start and end arguments for arc, chord and pieslice are integers.
Note that these numbers are not simply rounded internally, but are actually utilised in the drawing process.
When using the ImageDraw multiline methods, the spacing between lines was inconsistent, based on the combination
on ascenders and descenders.
This has now been fixed, so that lines are offset by their baselines, not the absolute height of each line.
There is also now a default spacing of 4px between lines.
There were major changes in the TIFF ImageFileDirectory support in Pillow 3.0 that led to a number of regressions.
Some of them have been fixed in Pillow 3.1, and some of them have been extended to have different behavior.
TiffImagePlugin.IFDRational
Pillow 3.0 changed rational metadata to use a float. In Pillow 3.1, this has changed to allow the expression of 0/0 as a
valid piece of rational metadata to reflect usage in the wild.
Rational metadata is now encapsulated in an IFDRational instance. This class extends the Rational class to allow
a denominator of 0. It compares as a float or a number, but does allow access to the raw numerator and denominator
values through attributes.
When used in a ImageFileDirectory_v1, a 2 item tuple is returned of the numerator and denominator, as was
done previously.
This class should be used when adding a rational value to an ImageFileDirectory for saving to image metadata.
JpegImagePlugin._getexif
In Pillow 3.0, the dictionary returned from the private, experimental, but generally widely used _getexif function
changed to reflect the ImageFileDirectory_v2 format, without a fallback to the previous format.
In Pillow 3.1, _getexif now returns a dictionary compatible with Pillow 2.9 and earlier, built with
ImageFileDirectory_v1 instances. Additionally, any single item tuples have been unwrapped and return a
bare element.
The format returned by Pillow 3.0 has been abandoned. A more fully featured interface for EXIF is anticipated in a
future release.
In Pillow 3.0 and 3.1, images that contain metadata that is internally consistent, but not in agreement with the TIFF
spec, may cause an exception when reading the metadata. This can happen when a tag that is specified to have a single
value is stored with an array of values.
It is anticipated that this behavior will change in future releases.
6.29 3.0.0
There is now support for saving multipage images in the GIF and PDF formats. To enable this functionality, pass in
save_all=True as a keyword argument to the save:
im.save('test.pdf', save_all=True)
The Tiff ImageFileDirectory metadata code has been rewritten. Where previously it returned a somewhat arbitrary set
of values and tuples, it now returns bare values where appropriate and tuples when the metadata item is a sequence or
collection.
The original metadata is still available in the TiffImage.tags, the new values are available in the TiffImage.tags_v2
member. The old structures will be deprecated at some point in the future. When saving Tiff metadata, new code
should use the TiffImagePlugin.ImageFileDirectory_v2 class.
Several methods that have been marked as deprecated for many releases have been removed in this release:
Image.tostring()
Image.fromstring()
Image.offset()
ImageDraw.setink()
ImageDraw.setfill()
The ImageFileIO module
The ImageFont.FreeTypeFont and ImageFont.truetype ``file`` keyword arg
The ImagePalette private _make functions
ImageWin.fromstring()
ImageWin.tostring()
The external dependencies on libjpeg and zlib are now required by default. If the headers or libraries are not found,
then installation will abort with an error. This behaviour can be disabled with the --disable-libjpeg and
--disable-zlib flags.
6.30 2.8.0
Image.open(urllib2.urlopen(url))
Image.open(requests.get(url, stream=True).raw)
If the response uses content-encoding (compression, either gzip or deflate) then this will fail as both the urllib2 and
requests raw file object will produce compressed data in that case. Using Content-Encoding on images is rather
non-sensical as most images are already compressed, but it can still happen.
For requests the work-around is to set the decode_content attribute on the raw object to True:
6.31 2.7.0
The Sane plugin has now been split into its own repo: https://github.com/python-pillow/Sane .
To prevent potential denial of service attacks using compressed text chunks, there are now limits to the decompressed
size of text chunks decoded from PNG images. If the limits are exceeded when opening a PNG image a ValueError
will be raised.
Individual text chunks are limited to PIL.PngImagePlugin.MAX_TEXT_CHUNK, set to 1MB by default. The
total decompressed size of all text chunks is limited to PIL.PngImagePlugin.MAX_TEXT_MEMORY, which de-
faults to 64MB. These values can be changed prior to opening PNG images if you know that there are large text blocks
that are desired.
Image resizing methods resize() and thumbnail() take a resample argument, which tells which filter should
be used for resampling. Possible values are: PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.
BICUBIC and PIL.Image.ANTIALIAS. Almost all of them were changed in this version.
From the beginning BILINEAR and BICUBIC filters were based on affine transformations and used a fixed number
of pixels from the source image for every destination pixel (2x2 pixels for BILINEAR and 4x4 for BICUBIC). This
gave an unsatisfactory result for downscaling. At the same time, a high quality convolutions-based algorithm with
flexible kernel was used for ANTIALIAS filter.
Starting from Pillow 2.7.0, a high quality convolutions-based algorithm is used for all of these three filters.
If you have previously used any tricks to maintain quality when downscaling with BILINEAR and BICUBIC filters
(for example, reducing within several steps), they are unnecessary now.
The image upscaling quality with LANCZOS filter was almost the same as BILINEAR due to bug. This has been fixed.
The BICUBIC filter for affine transformations produced sharp, slightly pixelated image for upscaling. Bicubic for
convolutions is more soft.
Resize performance
In most cases, convolution is more a expensive algorithm for downscaling because it takes into account all the pixels
of source image. Therefore BILINEAR and BICUBIC filters’ performance can be lower than before. On the other
hand the quality of BILINEAR and BICUBIC was close to NEAREST. So if such quality is suitable for your tasks
you can switch to NEAREST filter for downscaling, which will give a huge improvement in performance.
At the same time performance of convolution resampling for downscaling has been improved by around a factor of
two compared to the previous version. The upscaling performance of the LANCZOS filter has remained the same. For
BILINEAR filter it has improved by 1.5 times and for BICUBIC by four times.
In Pillow 2.5 the default filter for thumbnail() was changed from NEAREST to ANTIALIAS. Antialias was chosen
because all the other filters gave poor quality for reduction. Starting from Pillow 2.7.0, ANTIALIAS has been replaced
with BICUBIC, because it’s faster and ANTIALIAS doesn’t give any advantages after downscaling with libjpeg,
which uses supersampling internally, not convolutions.
A new method PIL.Image.TRANSPOSE has been added for the transpose() operation in addition to
FLIP_LEFT_RIGHT, FLIP_TOP_BOTTOM, ROTATE_90, ROTATE_180, ROTATE_270. TRANSPOSE is an al-
gebra transpose, with an image reflected across its main diagonal.
The speed of ROTATE_90, ROTATE_270 and TRANSPOSE has been significantly improved for large images which
don’t fit in the processor cache.
The GaussianBlur() implementation has been replaced with a sequential application of box filters. The new im-
plementation is based on “Theoretical foundations of Gaussian convolution by extended box filtering” from the Math-
ematical Image Analysis Group. As UnsharpMask() implementations use Gaussian blur internally, all changes
from this chapter are also applicable to it.
Blur radius
There was an error in the previous version of Pillow, where blur radius (the standard deviation of Gaussian) actually
meant blur diameter. For example, to blur an image with actual radius 5 you were forced to use value 10. This has
been fixed. Now the meaning of the radius is the same as in other software.
If you used a Gaussian blur with some radius value, you need to divide this value by two.
Blur performance
Box filter computation time is constant relative to the radius and depends on source image size only. Because the new
Gaussian blur implementation is based on box filter, its computation time also doesn’t depend on the blur radius.
For example, previously, if the execution time for a given test image was 1 second for radius 1, 3.6 seconds for radius
10 and 17 seconds for 50, now blur with any radius on same image is executed for 0.2 seconds.
Blur quality
The previous implementation takes into account only source pixels within 2 * standard deviation radius for every
destination pixel. This was not enough, so the quality was worse compared to other Gaussian blur software.
The new implementation does not have this drawback.
Several kwarg parameters for saving TIFF images were previously specified as strings with included spaces (e.g. ‘x
resolution’). This was difficult to use as kwargs without constructing and passing a dictionary. These parameters now
use the underscore character instead of space. (e.g. ‘x_resolution’)
This page lists Pillow features that are deprecated, or have been removed in past major releases, and gives the alterna-
tives to use instead.
Below are features which are considered deprecated. Where appropriate, a DeprecationWarning is issued.
7.1.1 ImageFile.raise_ioerror
187
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Deprecated features are only removed in major releases after an appropriate period of deprecation has passed.
7.2.2 Image.__del__
im = Image.open("hopper.png")
im.save("out.jpg")
Use instead:
Several undocumented functions in ImageOps have been removed. Use the equivalents in ImageFilter instead:
7.2.8 PIL.OleFileIO
• genindex
• modindex
• search
191
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
p PIL.ImageQt, 108
PIL._binary, 124 PIL.ImageSequence, 109
PIL.BdfFontFile, 117 PIL.ImageShow, 119
PIL.BmpImagePlugin, 125 PIL.ImageStat, 109
PIL.BufrStubImagePlugin, 125 PIL.ImageTk, 110
PIL.ContainerIO, 117 PIL.ImageTransform, 120
PIL.CurImagePlugin, 125 PIL.ImageWin, 111
PIL.DcxImagePlugin, 126 PIL.ImImagePlugin, 131
PIL.EpsImagePlugin, 126 PIL.ImtImagePlugin, 131
PIL.ExifTags, 112 PIL.IptcImagePlugin, 131
PIL.FitsStubImagePlugin, 127 PIL.Jpeg2KImagePlugin, 132
PIL.FliImagePlugin, 127 PIL.JpegImagePlugin, 132
PIL.FontFile, 117 PIL.JpegPresets, 121
PIL.FpxImagePlugin, 127 PIL.McIdasImagePlugin, 133
PIL.GbrImagePlugin, 127 PIL.MicImagePlugin, 133
PIL.GdImageFile, 118 PIL.MpegImagePlugin, 133
PIL.GifImagePlugin, 128 PIL.MspImagePlugin, 134
PIL.GimpGradientFile, 118 PIL.PaletteFile, 122
PIL.GimpPaletteFile, 118 PIL.PalmImagePlugin, 134
PIL.GribStubImagePlugin, 129 PIL.PcdImagePlugin, 134
PIL.Hdf5StubImagePlugin, 129 PIL.PcfFontFile, 122
PIL.IcnsImagePlugin, 129 PIL.PcxImagePlugin, 134
PIL.IcoImagePlugin, 130 PIL.PdfImagePlugin, 134
PIL.Image, 47 PIL.PixarImagePlugin, 134
PIL.ImageChops, 63 PIL.PngImagePlugin, 135
PIL.ImageCms, 67 PIL.PpmImagePlugin, 136
PIL.ImageColor, 66 PIL.PsdImagePlugin, 136
PIL.ImageDraw, 81 PIL.PSDraw, 114
PIL.ImageDraw2, 118 PIL.PyAccess, 116
PIL.ImageEnhance, 88 PIL.SgiImagePlugin, 137
PIL.ImageFile, 89 PIL.SpiderImagePlugin, 137
PIL.ImageFilter, 91 PIL.SunImagePlugin, 138
PIL.ImageFont, 94 PIL.TarIO, 123
PIL.ImageGrab, 99 PIL.TgaImagePlugin, 138
PIL.ImageMath, 100 PIL.TiffImagePlugin, 138
PIL.ImageMorph, 102 PIL.TiffTags, 113
PIL.ImageOps, 103 PIL.WalImageFile, 124
PIL.ImagePalette, 107 PIL.WebPImagePlugin, 141
PIL.ImagePath, 108 PIL.WmfImagePlugin, 142
PIL.XbmImagePlugin, 142
193
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
PIL.XpmImagePlugin, 143
PIL.XVThumbImagePlugin, 142
195
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
196 Index
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Index 197
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
198 Index
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Index 199
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
200 Index
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Index 201
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
202 Index
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Index 203
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
204 Index
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
Index 205
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
206 Index
Pillow (PIL Fork) Documentation, Release 7.2.0.dev0
W
WebPImageFile (class in PIL.WebPImagePlugin), 141
width (in module PIL.Image), 63
width() (PIL.ImageTk.BitmapImage method), 110
width() (PIL.ImageTk.PhotoImage method), 111
WmfStubImageFile (class in PIL.WmfImagePlugin),
142
write() (PIL.TiffImagePlugin.AppendingTiffWriter
method), 139
write_byte() (PIL.TiffImagePlugin.ImageFileDirectory_v2
method), 141
write_double() (PIL.TiffImagePlugin.ImageFileDirectory_v2
method), 141
write_float() (PIL.TiffImagePlugin.ImageFileDirectory_v2
method), 141
write_long() (PIL.TiffImagePlugin.ImageFileDirectory_v2
method), 141
write_rational() (PIL.TiffImagePlugin.ImageFileDirectory_v2
method), 141
write_short() (PIL.TiffImagePlugin.ImageFileDirectory_v2
method), 141
write_signed_byte()
(PIL.TiffImagePlugin.ImageFileDirectory_v2
method), 141
write_signed_long()
(PIL.TiffImagePlugin.ImageFileDirectory_v2
method), 141
write_signed_rational()
(PIL.TiffImagePlugin.ImageFileDirectory_v2
method), 141
write_signed_short()
(PIL.TiffImagePlugin.ImageFileDirectory_v2
method), 141
write_string() (PIL.TiffImagePlugin.ImageFileDirectory_v2
method), 141
write_undefined()
(PIL.TiffImagePlugin.ImageFileDirectory_v2
method), 141
writeLong() (PIL.TiffImagePlugin.AppendingTiffWriter
method), 139
writeShort() (PIL.TiffImagePlugin.AppendingTiffWriter
method), 139
X
XbmImageFile (class in PIL.XbmImagePlugin), 142
Index 207