Pillow (PIL fork) Documentation - Read the Docs

Pillow (PIL fork) Documentation - Read the Docs
Pillow (PIL fork) Documentation
Release 2.6.0
Author
December 01, 2014
Contents
1
2
3
4
Installation
1.1 Simple installation . .
1.2 External libraries . . .
1.3 Build Options . . . . .
1.4 Linux installation . . .
1.5 Mac OS X installation
1.6 Windows installation .
1.7 FreeBSD installation .
1.8 Platform support . . .
1.9 Old Versions . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
3
3
3
4
5
5
5
6
6
7
About Pillow
2.1 Goals . . . . . .
2.2 License . . . . .
2.3 Why a fork? . .
2.4 What about PIL?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
9
9
9
9
9
Guides
3.1 Overview . . . . . . . . . . . . . . . . .
3.2 Tutorial . . . . . . . . . . . . . . . . . .
3.3 Concepts . . . . . . . . . . . . . . . . .
3.4 Porting existing PIL-based code to Pillow
3.5 Developer . . . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
11
11
12
19
21
21
Reference
4.1 Image Module . . . . . . . . . . . . . . . . . .
4.2 ImageChops (“Channel Operations”) Module .
4.3 ImageColor Module . . . . . . . . . . . . . .
4.4 ImageCms Module . . . . . . . . . . . . . . .
4.5 ImageDraw Module . . . . . . . . . . . . . .
4.6 ImageEnhance Module . . . . . . . . . . . .
4.7 ImageFile Module . . . . . . . . . . . . . .
4.8 ImageFilter Module . . . . . . . . . . . . .
4.9 ImageFont Module . . . . . . . . . . . . . .
4.10 ImageGrab Module (Windows-only) . . . . .
4.11 ImageMath Module . . . . . . . . . . . . . .
4.12 ImageMorph Module . . . . . . . . . . . . . .
4.13 ImageOps Module . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
23
23
25
25
26
26
30
31
31
33
34
34
36
36
.
.
.
.
.
.
.
.
.
.
.
.
i
4.14
4.15
4.16
4.17
4.18
4.19
4.20
4.21
4.22
4.23
4.24
4.25
4.26
.
.
.
.
.
.
.
.
.
.
.
.
.
36
36
37
37
38
39
39
39
39
47
47
48
48
5
Appendices
5.1 Image file formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.2 Writing your own file decoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
53
53
63
6
Original PIL README
69
7
Indices and tables
75
Python Module Index
77
ii
ImagePalette Module . . . . . . . . . .
ImagePath Module . . . . . . . . . . . .
ImageQt Module . . . . . . . . . . . . . .
ImageSequence Module . . . . . . . . .
ImageStat Module . . . . . . . . . . . .
ImageTk Module . . . . . . . . . . . . . .
ImageWin Module (Windows-only) . . . .
ExifTags Module . . . . . . . . . . . . .
OleFileIO Module . . . . . . . . . . . .
PSDraw Module . . . . . . . . . . . . . . .
PixelAccess Class . . . . . . . . . . . .
PyAccess Module . . . . . . . . . . . . .
PIL Package (autodoc of remaining modules)
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Pillow (PIL fork) Documentation, Release 2.6.0
Pillow is the �friendly’ PIL fork by Alex Clark and Contributors. PIL is the Python Imaging Library by Fredrik Lundh
and Contributors. To install Pillow, please follow the installation instructions. To download source and/or contribute
to development of Pillow please see: https://github.com/python-pillow/Pillow.
Contents
1
Pillow (PIL fork) Documentation, Release 2.6.0
2
Contents
CHAPTER 1
Installation
Warning: Pillow >= 2.1.0 no longer supports “import _imaging”. Please use “from PIL.Image import core as
_imaging” instead.
Warning: Pillow >= 1.0 no longer supports “import Image”. Please use “from PIL import Image” instead.
Warning: PIL and Pillow currently cannot co-exist in the same environment. If you want to use Pillow, please
remove PIL first.
Note: Pillow >= 2.0.0 supports Python versions 2.6, 2.7, 3.2, 3.3, 3.4
Note: Pillow < 2.0.0 supports Python versions 2.4, 2.5, 2.6, 2.7.
1.1 Simple installation
Note: The following instructions will install Pillow with support for most formats. See External libraries for the
features you would gain by installing the external libraries first. This page probably also include specific instructions
for your platform.
You can install Pillow with pip:
$ pip install Pillow
Or easy_install (for installing Python Eggs, as pip does not support them):
$ easy_install Pillow
Or download the compressed archive from PyPI, extract it, and inside it run:
$ python setup.py install
1.2 External libraries
Note: You do not need to install all of the external libraries to use Pillow’s basic features.
3
Pillow (PIL fork) Documentation, Release 2.6.0
Many of Pillow’s features require external libraries:
• libjpeg provides JPEG functionality.
– Pillow has been tested with libjpeg versions 6b, 8, and 9 and libjpeg-turbo version 8.
• zlib provides access to compressed PNGs
• libtiff provides compressed TIFF functionality
– Pillow has been tested with libtiff versions 3.x and 4.0
• libfreetype provides type related services
• littlecms provides color management
– Pillow version 2.2.1 and below uses liblcms1, Pillow 2.3.0 and above uses liblcms2. Tested with 1.19 and
2.2.
• libwebp provides the WebP format.
– Pillow has been tested with version 0.1.3, which does not read transparent WebP files. Versions 0.3.0 and
0.4.0 support transparency.
• tcl/tk provides support for tkinter bitmap and photo images.
• openjpeg provides JPEG 2000 functionality.
– Pillow has been tested with openjpeg 2.0.0 and 2.1.0.
Once you have installed the prerequisites,run:
$ pip install Pillow
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:
$ CFLAGS="-I/usr/pkg/include" pip install pillow
1.3 Build Options
• Environment Variable: MAX_CONCURRENCY=n. By default, Pillow will use multiprocessing to build the extension in parallel. This may not be ideal for machines that report a large number of cores compared to the actual
processor power. Set MAX_CONCURRENCY to 1 to disable parallel building, or to a larger number to limit to
that number of parallel tasks.
• Build flags: --disable-zlib, --disable-jpeg, --disable-tiff, --disable-freetype,
--disable-tcl, --disable-tk, --disable-lcms, --disable-webp, --disable-webpmux,
--disable-jpeg2000. 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-tcl, --enable-tk, --enable-lcms, --enable-webp, --enable-webpmux,
--enable-jpeg2000. 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.
Sample Usage:
4
Chapter 1. Installation
Pillow (PIL fork) Documentation, Release 2.6.0
$ MAX_CONCURRENCY=1 python setup.py build-ext --enable-[feature] install
1.4 Linux installation
Note: Fedora, Debian/Ubuntu, and ArchLinux include Pillow (instead of PIL) with their distributions. Consider using
those instead of installing manually.
We do not provide binaries for Linux. If you didn’t build Python from source, make sure you have Python’s
development libraries installed. In Debian or Ubuntu:
$ sudo apt-get install python-dev python-setuptools
Or for Python 3:
$ sudo apt-get install python3-dev python3-setuptools
In Fedora, the command is:
$ sudo yum install python-devel
Prerequisites are installed on Ubuntu 12.04 LTS or Raspian Wheezy 7.0 with:
$ sudo apt-get install libtiff4-dev libjpeg8-dev zlib1g-dev \
libfreetype6-dev liblcms2-dev libwebp-dev tcl8.5-dev tk8.5-dev python-tk
Prerequisites are installed on Ubuntu 14.04 LTS with:
$ sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev \
libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk
Prerequisites are installed on Fedora 20 with:
$ sudo yum install libtiff-devel libjpeg-devel libzip-devel freetype-devel \
lcms2-devel libwebp-devel tcl-devel tk-devel
1.5 Mac OS X installation
We provide binaries for OS X in the form of Python Wheels. Alternatively you can compile Pillow with with XCode.
The easiest way to install external libraries is via Homebrew. After you install Homebrew, run:
$ brew install libtiff libjpeg webp little-cms2
Install Pillow with:
$ pip install Pillow
1.6 Windows installation
We provide binaries for Windows in the form of Python Eggs and Python Wheels:
1.4. Linux installation
5
Pillow (PIL fork) Documentation, Release 2.6.0
1.6.1 Python Eggs
Note: pip does not support Python Eggs; use easy_install instead.
$ easy_install Pillow
1.6.2 Python Wheels
Note: Experimental. Requires setuptools >=0.8 and pip >=1.4.1
$ pip install --use-wheel Pillow
If the above does not work, it’s likely because we haven’t uploaded a wheel for the latest version of Pillow. In that
case, try pinning it to a specific version:
$ pip install --use-wheel Pillow==2.6.1
1.7 FreeBSD installation
Note: Only FreeBSD 10 tested
Make sure you have Python’s development libraries installed.:
$ sudo pkg install python2
Or for Python 3:
$ sudo pkg install python3
Prerequisites are installed on FreeBSD 10 with:
$ sudo pkg install jpeg tiff webp lcms2 freetype2
1.8 Platform support
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, OS X, and Windows.
Note: Contributors please test on your platform, edit this document, and send a pull request.
6
Chapter 1. Installation
Pillow (PIL fork) Documentation, Release 2.6.0
Operating system
Mac OS X 10.10 Yosemite
Mac OS X 10.9 Mavericks
Mac OS X 10.8 Mountain
Lion
Redhat Linux 6
CentOS 6.3
Fedora 20
Ubuntu Linux 10.04 LTS
Ubuntu Linux 12.04 LTS
Ubuntu Linux 14.04 LTS
Raspian Wheezy
Gentoo Linux
FreeBSD 10
Windows 7 Pro
Windows Server 2008 R2
Enterprise
Windows 8 Pro
Windows 8.1 Pro
Supported
Tested Python versions
Tested Pillow
versions
Yes
Yes
2.7,3.4
2.6,2.7,3.2,3.3
2.6.1
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
2.6
2.7,3.3
2.7,3.3
2.6
2.6,2.7,3.2,3.3,PyPy2.4,
PyPy3,v2.3
2.7,3.2
2.7,3.2,3.3,3.4
2.7,3.2
2.7,3.2
2.7,3.4
2.7,3.2,3.3
3.3
Yes
Yes
2.6,2.7,3.2,3.3,3.4a3
2.6,2.7,3.2,3.3,3.4
2.3.0
2.3.0
2.6.1
2.6.1
Tested
processors
x86-64
x86-64
x86-64
x86
x86
x86-64
x86,x86-64
x86,x86-64
ppc
2.3.0
2.3.0
2.1.0
2.4,2.3.1
2.2.1
x86
arm
x86-64
x86-64
x86-64
x86-64
2.2.0
2.3.0, 2.4.0
x86,x86-64
x86,x86-64
1.9 Old Versions
You can download old distributions from PyPI. Only the latest 1.x and 2.x releases are visible, but all releases are
available by direct URL access e.g. https://pypi.python.org/pypi/Pillow/1.0.
1.9. Old Versions
7
Pillow (PIL fork) Documentation, Release 2.6.0
8
Chapter 1. Installation
CHAPTER 2
About Pillow
2.1 Goals
The fork authors’ goal is to foster active development of PIL through:
• Continuous integration testing via Travis CI
• Publicized development activity on GitHub
• Regular releases to the Python Package Index
2.2 License
like
PIL
itself,
Pillow
is
licensed
under
<http://www.pythonware.com/products/pil/license.htm>:
the
MIT-like
PIL
Software
License
Software License
The Python Imaging Library (PIL) is
Copyright В© 1997-2011 by Secret Labs AB
Copyright В© 1995-2011 by Fredrik Lundh
By obtaining, using, and/or copying this software and/or its associated documentation, you agree that
Permission to use, copy, modify, and distribute this software and its associated documentation for an
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IM
2.3 Why a fork?
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.
2.4 What about PIL?
9
Pillow (PIL fork) Documentation, Release 2.6.0
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.
As more time passes since the last PIL release, 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 the corresponding Pillow tickets here.
Please provide a link to the PIL ticket so we can track the issue(s) upstream.
10
Chapter 2. About Pillow
CHAPTER 3
Guides
3.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.
3.1.1 Image Archives
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.
3.1.2 Image Display
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.
3.1.3 Image Processing
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.
11
Pillow (PIL fork) Documentation, Release 2.6.0
3.2 Tutorial
3.2.1 Using the Image class
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("lena.ppm")
If successful, this function returns an Image object. You can now use instance attributes to examine the file contents:
>>> from __future__ import print_function
>>> 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 IOError 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 the
xv utility to display the image. If you don’t have xv 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.
3.2.2 Reading and writing images
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.
Convert files to JPEG
from __future__ import print_function
import os, sys
from PIL import Image
for infile in sys.argv[1:]:
f, e = os.path.splitext(infile)
outfile = f + ".jpg"
12
Chapter 3. Guides
Pillow (PIL fork) Documentation, Release 2.6.0
if infile != outfile:
try:
Image.open(infile).save(outfile)
except IOError:
print("cannot convert", infile)
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:
Create JPEG thumbnails
from __future__ import print_function
import os, sys
from PIL import Image
size = (128, 128)
for infile in sys.argv[1:]:
outfile = os.path.splitext(infile)[0] + ".thumbnail"
if infile != outfile:
try:
im = Image.open(infile)
im.thumbnail(size)
im.save(outfile, "JPEG")
except IOError:
print("cannot create thumbnail for", infile)
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:
Identify Image Files
from __future__ import print_function
import sys
from PIL import Image
for infile in sys.argv[1:]:
try:
with Image.open(infile) as im:
print(infile, im.format, "%dx%d" % im.size, im.mode)
except IOError:
pass
3.2.3 Cutting, pasting, and merging images
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.
3.2. Tutorial
13
Pillow (PIL fork) Documentation, Release 2.6.0
Copying a subrectangle from an image
box = (100, 100, 400, 400)
region = im.crop(box)
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.
Processing a subrectangle, and pasting it 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
def roll(image, delta):
"Roll an image sideways"
xsize, ysize = image.size
delta = delta % xsize
if delta == 0: return image
part1 = image.crop((0, 0, delta, ysize))
part2 = image.crop((delta, 0, xsize, ysize))
image.paste(part2, (0, 0, xsize-delta, ysize))
image.paste(part1, (xsize-delta, 0, xsize, ysize))
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.
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:
Splitting and merging bands
r, g, b = im.split()
im = Image.merge("RGB", (b, g, r))
14
Chapter 3. Guides
Pillow (PIL fork) Documentation, Release 2.6.0
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.
3.2.4 Geometrical transforms
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.
Simple geometry transforms
out = im.resize((128, 128))
out = im.rotate(45) # 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
out
out
out
out
=
=
=
=
=
im.transpose(Image.FLIP_LEFT_RIGHT)
im.transpose(Image.FLIP_TOP_BOTTOM)
im.transpose(Image.ROTATE_90)
im.transpose(Image.ROTATE_180)
im.transpose(Image.ROTATE_270)
There’s no difference in performance or result between transpose(ROTATE) and corresponding rotate() operations.
A more general form of image transformations can be carried out via the transform() method.
3.2.5 Color transforms
The Python Imaging Library allows you to convert images between different pixel representations using the
convert() method.
Converting between modes
im = Image.open("lena.ppm").convert("L")
The library supports transformations between each supported mode and the “L” and “RGB” modes. To convert between other modes, you may have to use an intermediate image (typically an “RGB” image).
3.2.6 Image enhancement
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.
3.2. Tutorial
15
Pillow (PIL fork) Documentation, Release 2.6.0
Applying filters
from PIL import ImageFilter
out = im.filter(ImageFilter.DETAIL)
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:
Applying point transforms
# multiply each pixel by 1.2
out = im.point(lambda i: i * 1.2)
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:
Processing individual bands
# split the image into individual bands
source = im.split()
R, G, B = 0, 1, 2
# select regions where red is less than 100
mask = source[R].point(lambda i: i < 100 and 255)
# process the green band
out = source[G].point(lambda i: i * 0.7)
# paste the processed band back, but only where red was < 100
source[G].paste(out, None, mask)
# build a new multiband image
im = Image.merge(im.mode, source)
Note the syntax used to create the mask:
imout = im.point(lambda i: expression and 255)
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.
16
Chapter 3. Guides
Pillow (PIL fork) Documentation, Release 2.6.0
Enhancing images
from PIL import ImageEnhance
enh = ImageEnhance.Contrast(im)
enh.enhance(1.3).show("30% more contrast")
3.2.7 Image sequences
The Python Imaging Library contains some basic support for image sequences (also called animation formats). Supported 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
from PIL import Image
im = Image.open("animation.gif")
im.seek(1) # skip to the second frame
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.
Note that most drivers in the current version of the library only allow you to seek to the next frame (as in the above
example). To rewind the file, you may have to reopen it.
The following iterator class lets you use the for-statement to loop over the sequence:
A sequence iterator class
class ImageSequence:
def __init__(self, im):
self.im = im
def __getitem__(self, ix):
try:
if ix:
self.im.seek(ix)
return self.im
except EOFError:
raise IndexError # end of sequence
for frame in ImageSequence(im):
# ...do something to frame...
3.2. Tutorial
17
Pillow (PIL fork) Documentation, Release 2.6.0
3.2.8 Postscript printing
The Python Imaging Library includes functions to print images, text and graphics on Postscript printers. Here’s a
simple example:
Drawing Postscript
from PIL import Image
from PIL import PSDraw
im = Image.open("lena.ppm")
title = "lena"
box = (1*72, 2*72, 7*72, 10*72) # in points
ps = PSDraw.PSDraw() # default is sys.stdout
ps.begin_document(title)
# draw the image (75 dpi)
ps.image(box, im, 75)
ps.rectangle(box)
# draw centered title
ps.setfont("HelveticaNarrow-Bold", 36)
w, h, b = ps.textsize(title)
ps.text((4*72-w/2, 1*72-h), title)
ps.end_document()
3.2.9 More on reading images
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:
im = Image.open("lena.ppm")
If everything goes well, the result is an PIL.Image.Image object. Otherwise, an IOError 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.
Reading from an open file
fp = open("lena.ppm", "rb")
im = Image.open(fp)
To read an image from string data, use the StringIO class:
Reading from a string
import StringIO
im = Image.open(StringIO.StringIO(buffer))
18
Chapter 3. Guides
Pillow (PIL fork) Documentation, Release 2.6.0
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.
Reading from a tar archive
from PIL import TarIO
fp = TarIO.TarIO("Imaging.tar", "Imaging/test/lena.ppm")
im = Image.open(fp)
3.2.10 Controlling the decoder
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.
Reading in draft mode
from __future__ import print_function
im = Image.open(file)
print("original =", im.mode, im.size)
im.draft("L", (100, 100))
print("draft =", im.mode, im.size)
This prints something like:
original = RGB (512, 512)
draft = L (128, 128)
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.
3.3 Concepts
The Python Imaging Library handles raster images; that is, rectangles of pixel data.
3.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.
To get the number and names of bands in an image, use the getbands() method.
3.3. Concepts
19
Pillow (PIL fork) Documentation, Release 2.6.0
3.3.2 Modes
The mode of an image defines the type and depth of a pixel in the image. 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)
• 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)
PIL also provides limited support for a few special modes, including LA (L with alpha), RGBX (true color with padding)
and RGBa (true color with premultiplied alpha). However, PIL doesn’t support user-defined modes; if you 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.
3.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.
3.3.4 Coordinate System
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).
3.3.5 Palette
The palette mode (P) uses a color palette to define the actual color for each pixel.
3.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.
20
Chapter 3. Guides
Pillow (PIL fork) Documentation, Release 2.6.0
3.3.7 Filters
For geometry operations that may map multiple input pixels to a single output pixel, the Python Imaging Library
provides four different resampling filters.
NEAREST Pick the nearest pixel from the input image. Ignore all other input pixels.
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.
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.
ANTIALIAS Calculate the output pixel value using a high-quality Lanczos filter (a truncated sinc) on all pixels that
may contribute to the output value. In the current version of PIL, this filter can only be used with the resize and
thumbnail methods.
New in version 1.1.3.
3.4 Porting existing PIL-based code to Pillow
Pillow is a functional drop-in replacement for the Python Imaging Library. To run your existing PIL-compatible code
with Pillow, it needs to be modified to import the Image module from the PIL namespace instead of the global
namespace. Change this:
import Image
to this:
from PIL import Image
The _imaging module has been moved. You can now import it like this:
from PIL.Image import core as _imaging
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.
3.5 Developer
Note: When committing only trivial changes, please include [ci skip] in the commit message to avoid running tests
on Travis-CI. Thank you!
3.5.1 Release
Details about making a Pillow release.
3.4. Porting existing PIL-based code to Pillow
21
Pillow (PIL fork) Documentation, Release 2.6.0
Version number
The version number is currently stored in 3 places:
PIL/__init__.py _imaging.c setup.py
22
Chapter 3. Guides
CHAPTER 4
Reference
4.1 Image Module
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.
4.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).
Open, rotate, and display an image (using the default viewer)
from PIL import Image
im = Image.open("bride.jpg")
im.rotate(45).show()
The following script creates nice 128x128 thumbnails of all JPEG images in the current directory.
Create thumbnails
from PIL import Image
import glob, os
size = 128, 128
for infile in glob.glob("*.jpg"):
file, ext = os.path.splitext(infile)
im = Image.open(infile)
im.thumbnail(size, Image.ANTIALIAS)
im.save(file + ".thumbnail", "JPEG")
23
Pillow (PIL fork) Documentation, Release 2.6.0
4.1.2 Functions
Image processing
Constructing images
Registering plugins
Note: These functions are for use by plugin authors. Application authors can ignore them.
4.1.3 The Image Class
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.
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.212671, 0.715160,
0.019334, 0.119193,
out = im.convert("RGB",
0.180423, 0,
0.072169, 0,
0.950227, 0 )
rgb2xyz)
4.1.4 Attributes
Instances of the Image class have the following attributes:
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.palette
Colour palette table, if any. If mode is “P”, 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.
24
Chapter 4. Reference
Pillow (PIL fork) Documentation, Release 2.6.0
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
4.2 ImageChops (“Channel Operations”) Module
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”).
4.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).
4.3 ImageColor Module
The ImageColor module contains color tables and converters from CSS3-style color specifiers to RGB tuples. This
module is used by PIL.Image.Image.new() and the ImageDraw module, among others.
4.3.1 Color Names
The ImageColor module supports the following string formats:
• Hexadecimal color specifiers, given as #rgb or #rrggbb. For example, #ff0000 specifies pure red.
• RGB functions, given as rgb(red, green, blue) where the color values are integers in the range 0
to 255. Alternatively, the color values can be given as three percentages (0% to 100%). For example,
rgb(255,0,0) and rgb(100%,0%,0%) both specify pure red.
• Hue-Saturation-Lightness (HSL) functions, given as hsl(hue, saturation%, lightness%) where
hue is the color given as an angle between 0 and 360 (red=0, green=120, blue=240), saturation is a value
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.
• 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.
4.2. ImageChops (“Channel Operations”) Module
25
Pillow (PIL fork) Documentation, Release 2.6.0
4.3.2 Functions
4.4 ImageCms Module
The ImageCms module provides color profile management support using the LittleCMS2 color management engine,
based on Kevin Cazabon’s PyCMS library.
4.5 ImageDraw Module
The ImageDraw module provide 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.
4.5.1 Example: Draw a gray cross over an image
from PIL import Image, ImageDraw
im = Image.open("lena.pgm")
draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=128)
draw.line((0, im.size[1], im.size[0], 0), fill=128)
del draw
# write to stdout
im.save(sys.stdout, "PNG")
4.5.2 Concepts
Coordinates
The graphics interface uses the same coordinate system as PIL itself, with (0, 0) in the upper left corner.
Colors
To specify colors, you can use numbers or tuples just as you would use with PIL.Image.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
See Color Names for the color names supported by Pillow.
26
Chapter 4. Reference
Pillow (PIL fork) Documentation, Release 2.6.0
Fonts
PIL can use bitmap fonts or OpenType/TrueType fonts.
Bitmap fonts are stored in PIL’s own format, where each font typically consists of a two files, one named .pil and the
other usually named .pbm. The former contains font metrics, the latter raster data.
To load a bitmap font, use the load functions in the ImageFont module.
To load a OpenType/TrueType font, use the truetype function in the ImageFont module. Note that this function
depends on third-party libraries, and may not available in all PIL builds.
4.5.3 Example: Draw Partial Opacity Text
from PIL import Image, ImageDraw, ImageFont
# get an image
base = Image.open(’Pillow/Tests/images/lena.png’).convert(’RGBA’)
# 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)
# draw text, half opacity
d.text((10,10), "Hello", font=fnt, fill=(255,255,255,128))
# draw text, full opacity
d.text((10,60), "World", font=fnt, fill=(255,255,255,255))
out = Image.alpha_composite(base, txt)
out.show()
4.5.4 Functions
class PIL.ImageDraw.Draw(im, mode=None)
Creates an object that can be used to draw in the given image.
Note that the image will be modified in place.
Parameters
• im – The image to draw in.
• mode – Optional mode to use for color values. For RGB images, this argument can be RGB
or RGBA (to blend the drawing into the image). For all other modes, this argument must be
the same as the image mode. If omitted, the mode defaults to the mode of the image.
4.5.5 Methods
PIL.ImageDraw.Draw.arc(xy, start, end, fill=None)
Draws an arc (a portion of a circle outline) between the start and end angles, inside the given bounding box.
Parameters
4.5. ImageDraw Module
27
Pillow (PIL fork) Documentation, Release 2.6.0
• xy – Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or
[x0, y0, x1, y1].
• start – Starting angle, in degrees. Angles are measured from 3 o’clock, increasing clockwise.
• end – Ending angle, in degrees.
• fill – Color to use for the arc.
PIL.ImageDraw.Draw.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.Draw.chord(xy, start, end, fill=None, outline=None)
Same as arc(), but connects the end points with a straight line.
Parameters
• xy – Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or
[x0, y0, x1, y1].
• outline – Color to use for the outline.
• fill – Color to use for the fill.
PIL.ImageDraw.Draw.ellipse(xy, fill=None, outline=None)
Draws an ellipse inside the given bounding box.
Parameters
• xy – Four points to define the bounding box. Sequence of either [(x0, y0), (x1,
y1)] or [x0, y0, x1, y1].
• outline – Color to use for the outline.
• fill – Color to use for the fill.
PIL.ImageDraw.Draw.line(xy, fill=None, width=0)
Draws a line between the coordinates in the xy list.
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 line.
• width – The line width, in pixels. Note that line joins are not handled well, so wide polylines
will not look good.
New in version 1.1.5.
Note: This option was broken until version 1.1.6.
PIL.ImageDraw.Draw.pieslice(xy, start, end, fill=None, outline=None)
Same as arc, but also draws straight lines between the end points and the center of the bounding box.
Parameters
• xy – Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or
[x0, y0, x1, y1].
28
Chapter 4. Reference
Pillow (PIL fork) Documentation, Release 2.6.0
• outline – Color to use for the outline.
• fill – Color to use for the fill.
PIL.ImageDraw.Draw.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.Draw.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.Draw.rectangle(xy, fill=None, outline=None)
Draws a rectangle.
Parameters
• xy – Four 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.
PIL.ImageDraw.Draw.shape(shape, fill=None, outline=None)
Warning: This method is experimental.
Draw a shape.
PIL.ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None)
Draws the string at the given position.
Parameters
• xy – Top left corner of the text.
• text – Text to be drawn.
• font – An ImageFont instance.
• fill – Color to use for the text.
PIL.ImageDraw.Draw.textsize(text, font=None)
Return the size of the given string, in pixels.
Parameters
• text – Text to be measured.
4.5. ImageDraw Module
29
Pillow (PIL fork) Documentation, Release 2.6.0
• font – An ImageFont instance.
4.5.6 Legacy API
The Draw class contains a constructor and a number of methods which are provided for backwards compatibility only.
For this to work properly, you should either use options on the drawing primitives, or these methods. Do not mix the
old and new calling conventions.
PIL.ImageDraw.ImageDraw(image)
Return type Draw
PIL.ImageDraw.Draw.setink(ink)
Deprecated since version 1.1.5.
Sets the color to use for subsequent draw and fill operations.
PIL.ImageDraw.Draw.setfill(fill)
Deprecated since version 1.1.5.
Sets the fill mode.
If the mode is 0, subsequently drawn shapes (like polygons and rectangles) are outlined. If the mode is 1, they
are filled.
PIL.ImageDraw.Draw.setfont(font)
Deprecated since version 1.1.5.
Sets the default font to use for the text method.
Parameters font – An ImageFont instance.
4.6 ImageEnhance Module
The ImageEnhance module contains a number of classes that can be used for image enhancement.
4.6.1 Example: Vary the sharpness of an image
from PIL import ImageEnhance
enhancer = ImageEnhance.Sharpness(image)
for i in range(8):
factor = i / 4.0
enhancer.enhance(factor).show("Sharpness %f" % factor)
Also see the enhancer.py demo program in the Scripts/ directory.
4.6.2 Classes
All enhancement classes implement a common interface, containing a single method:
30
Chapter 4. Reference
Pillow (PIL fork) Documentation, Release 2.6.0
4.7 ImageFile Module
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.
4.7.1 Example: Parse an image
from PIL import ImageFile
fp = open("lena.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")
4.7.2 Parser
4.8 ImageFilter Module
The ImageFilter module contains definitions for a pre-defined set of filters, which can be be used with the
Image.filter() method.
4.8.1 Example: Filter an image
from PIL import ImageFilter
im1 = im.filter(ImageFilter.BLUR)
im2 = im.filter(ImageFilter.MinFilter(3))
im3 = im.filter(ImageFilter.MinFilter) # same as MinFilter(3)
4.8.2 Filters
The current version of the library provides the following set of predefined image enhancement filters:
• BLUR
• CONTOUR
• DETAIL
4.7. ImageFile Module
31
Pillow (PIL fork) Documentation, Release 2.6.0
• EDGE_ENHANCE
• EDGE_ENHANCE_MORE
• EMBOSS
• FIND_EDGES
• SMOOTH
• SMOOTH_MORE
• SHARPEN
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.
https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking
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.
32
Chapter 4. Reference
Pillow (PIL fork) Documentation, Release 2.6.0
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.
4.9 ImageFont Module
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 :command�pilfont� utility 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
4.9.1 Example
from PIL import ImageFont, ImageDraw
draw = ImageDraw.Draw(image)
# use a bitmap font
font = ImageFont.load("arial.pil")
draw.text((10, 10), "hello", font=font)
# use a truetype font
font = ImageFont.truetype("arial.ttf", 15)
draw.text((10, 25), "world", font=font)
4.9.2 Functions
4.9.3 Methods
PIL.ImageFont.ImageFont.getsize(text)
Returns (width, height)
PIL.ImageFont.ImageFont.getmask(text, mode=’�)
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.
4.9. ImageFont Module
33
Pillow (PIL fork) Documentation, Release 2.6.0
New in version 1.1.5.
Returns An internal PIL storage memory instance as defined by the PIL.Image.core interface
module.
4.10 ImageGrab Module (Windows-only)
The ImageGrab module can be used to copy the contents of the screen or the clipboard to a PIL image memory.
Note: The current version works on Windows only.
New in version 1.1.3.
PIL.ImageGrab.grab(bbox=None)
Take a snapshot of the screen. The pixels inside the bounding box are returned as an “RGB” image. If the
bounding box is omitted, the entire screen is copied.
New in version 1.1.3.
Parameters bbox – What region to copy. Default is the entire screen.
Returns An image
PIL.ImageGrab.grabclipboard()
Take a snapshot of the clipboard image, if any.
New in version 1.1.4.
Returns An image, a list of filenames, or None if the clipboard does not contain image data or
filenames. Note that if a list is returned, the filenames may not represent image files.
4.11 ImageMath Module
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.
4.11.1 Example: Using the ImageMath module
import Image, ImageMath
im1 = Image.open("image1.jpg")
im2 = Image.open("image2.jpg")
out = ImageMath.eval("convert(min(a, b), ’L’)", a=im1, b=im2)
out.save("result.png")
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.
34
Chapter 4. Reference
Pillow (PIL fork) Documentation, Release 2.6.0
• 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 expression.
4.11.2 Expression syntax
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
These functions are applied to each individual pixel.
abs(image)
Absolute value.
convert(image, mode)
Convert image to the given mode. The mode must be given as a string constant.
float(image)
Convert image to 32-bit floating point. This is equivalent to convert(image, “F”).
4.11. ImageMath Module
35
Pillow (PIL fork) Documentation, Release 2.6.0
int(image)
Convert image to 32-bit integer. This is equivalent to convert(image, “I”).
Note that 1-bit and 8-bit images are automatically converted to 32-bit integers if necessary to get a correct result.
max(image1, image2)
Maximum value.
min(image1, image2)
Minimum value.
4.12 ImageMorph Module
The ImageMorph module provides morphology operations on images.
4.13 ImageOps Module
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.
Only bug fixes have been added since the Pillow fork.
New in version 1.1.3.
4.14 ImagePalette Module
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.
4.15 ImagePath Module
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 assignment, or item and slice deletion.
36
Chapter 4. Reference
Pillow (PIL fork) Documentation, Release 2.6.0
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:
xOut = xIn * a + yIn * b + c
yOut = xIn * d + yIn * e + f
4.16 ImageQt Module
The ImageQt module contains support for creating PyQt4 or PyQt5 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 PyQt4/5 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.
4.17 ImageSequence Module
The ImageSequence module contains a wrapper class that lets you iterate over the frames of an image sequence.
4.17.1 Extracting frames from an animation
from PIL import Image, ImageSequence
im = Image.open("animation.fli")
index = 1
4.16. ImageQt Module
37
Pillow (PIL fork) Documentation, Release 2.6.0
for frame in ImageSequence.Iterator(im):
frame.save("frame%d.png" % index)
index = index + 1
4.17.2 The Iterator class
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.
4.18 ImageStat Module
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.
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.
38
Chapter 4. Reference
Pillow (PIL fork) Documentation, Release 2.6.0
4.19 ImageTk Module
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.
4.20 ImageWin Module (Windows-only)
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 contexts 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)
4.21 ExifTags Module
The ExifTags module exposes two dictionaries which provide constants and clear-text names for various wellknown EXIF tags.
class PIL.ExifTags.TAGS
The TAG dictionary maps 16-bit integer EXIF tag enumerations to descriptive string names. For instance:
>>> from PIL.ExifTags import TAGS
>>> TAGS[0x010e]
’ImageDescription’
class PIL.ExifTags.GPSTAGS
The GPSTAGS dictionary maps 8-bit integer EXIF gps enumerations to descriptive string names. For instance:
>>> from PIL.ExifTags import GPSTAGS
>>> GPSTAGS[20]
’GPSDestLatitude’
4.22 OleFileIO Module
The OleFileIO module reads Microsoft OLE2 files (also called Structured Storage or Microsoft Compound Document File Format), such as Microsoft Office documents, Image Composer and FlashPix files, and Outlook messages.
This module is the OleFileIO_PL project by Philippe Lagadec, v0.30, merged back into Pillow.
4.22.1 How to use this module
For more information, see also the file PIL/OleFileIO.py, sample code at the end of the module itself, and docstrings
within the code.
4.19. ImageTk Module
39
Pillow (PIL fork) Documentation, Release 2.6.0
About the structure of OLE files
An OLE file can be seen as a mini file system or a Zip archive: It contains streams of data that look like files embedded
within the OLE file. Each stream has a name. For example, the main stream of a MS Word document containing its
text is named “WordDocument”.
An OLE file can also contain storages. A storage is a folder that contains streams or other storages. For example, a
MS Word document with VBA macros has a storage called “Macros”.
Special streams can contain properties. A property is a specific value that can be used to store information such as the
metadata of a document (title, author, creation date, etc). Property stream names usually start with the character �05’.
For example, a typical MS Word document may look like this:
\x05DocumentSummaryInformation (stream)
\x05SummaryInformation (stream)
WordDocument (stream)
Macros (storage)
PROJECT (stream)
PROJECTwm (stream)
VBA (storage)
Module1 (stream)
ThisDocument (stream)
_VBA_PROJECT (stream)
dir (stream)
ObjectPool (storage)
Test if a file is an OLE container
Use isOleFile to check if the first bytes of the file contain the Magic for OLE files, before opening it. isOleFile returns
True if it is an OLE file, False otherwise.
assert OleFileIO.isOleFile(’myfile.doc’)
Open an OLE file from disk
Create an OleFileIO object with the file path as parameter:
ole = OleFileIO.OleFileIO(’myfile.doc’)
Open an OLE file from a file-like object
This is useful if the file is not on disk, e.g. already stored in a string or as a file-like object.
ole = OleFileIO.OleFileIO(f)
For example the code below reads a file into a string, then uses BytesIO to turn it into a file-like object.
data = open(’myfile.doc’, ’rb’).read()
f = io.BytesIO(data) # or StringIO.StringIO for Python 2.x
ole = OleFileIO.OleFileIO(f)
40
Chapter 4. Reference
Pillow (PIL fork) Documentation, Release 2.6.0
How to handle malformed OLE files
By default, the parser is configured to be as robust and permissive as possible, allowing to parse most malformed
OLE files. Only fatal errors will raise an exception. It is possible to tell the parser to be more strict in order to raise
exceptions for files that do not fully conform to the OLE specifications, using the raise_defect option:
ole = OleFileIO.OleFileIO(’myfile.doc’, raise_defects=DEFECT_INCORRECT)
When the parsing is done, the list of non-fatal issues detected is available as a list in the parsing_issues attribute of the
OleFileIO object:
print(’Non-fatal issues raised during parsing:’)
if ole.parsing_issues:
for exctype, msg in ole.parsing_issues:
print(’- %s: %s’ % (exctype.__name__, msg))
else:
print(’None’)
Syntax for stream and storage path
Two different syntaxes are allowed for methods that need or return the path of streams and storages:
1. Either a list of strings including all the storages from the root up to the stream/storage name. For example a
stream called “WordDocument” at the root will have [’WordDocument’] as full path. A stream called “ThisDocument” located in the storage “Macros/VBA” will be [’Macros’, �VBA’, �ThisDocument’]. This is the original
syntax from PIL. While hard to read and not very convenient, this syntax works in all cases.
2. Or a single string with slashes to separate storage and stream names (similar to the Unix path syntax). The
previous examples would be �WordDocument’ and �Macros/VBA/ThisDocument’. This syntax is easier, but
may fail if a stream or storage name contains a slash.
Both are case-insensitive.
Switching between the two is easy:
slash_path = ’/’.join(list_path)
list_path = slash_path.split(’/’)
Get the list of streams
listdir() returns a list of all the streams contained in the OLE file, including those stored in storages. Each stream is
listed itself as a list, as described above.
print(ole.listdir())
Sample result:
[[’\x01CompObj’], [’\x05DocumentSummaryInformation’], [’\x05SummaryInformation’]
, [’1Table’], [’Macros’, ’PROJECT’], [’Macros’, ’PROJECTwm’], [’Macros’, ’VBA’,
’Module1’], [’Macros’, ’VBA’, ’ThisDocument’], [’Macros’, ’VBA’, ’_VBA_PROJECT’]
, [’Macros’, ’VBA’, ’dir’], [’ObjectPool’], [’WordDocument’]]
As an option it is possible to choose if storages should also be listed, with or without streams:
ole.listdir (streams=False, storages=True)
4.22. OleFileIO Module
41
Pillow (PIL fork) Documentation, Release 2.6.0
Test if known streams/storages exist:
exists(path) checks if a given stream or storage exists in the OLE file.
if ole.exists(’worddocument’):
print("This is a Word document.")
if ole.exists(’macros/vba’):
print("This document seems to contain VBA macros.")
Read data from a stream
openstream(path) opens a stream as a file-like object.
The following example extracts the “Pictures” stream from a PPT file:
pics = ole.openstream(’Pictures’)
data = pics.read()
Get information about a stream/storage
Several methods can provide the size, type and timestamps of a given stream/storage:
get_size(path) returns the size of a stream in bytes:
s = ole.get_size(’WordDocument’)
get_type(path) returns the type of a stream/storage, as one of the following constants: STGTY_STREAM for a stream,
STGTY_STORAGE for a storage, STGTY_ROOT for the root entry, and False for a non existing path.
t = ole.get_type(’WordDocument’)
get_ctime(path) and get_mtime(path) return the creation and modification timestamps of a stream/storage, as a Python
datetime object with UTC timezone. Please note that these timestamps are only present if the application that created
the OLE file explicitly stored them, which is rarely the case. When not present, these methods return None.
c = ole.get_ctime(’WordDocument’)
m = ole.get_mtime(’WordDocument’)
The root storage is a special case: You can get its creation and modification timestamps using the OleFileIO.root
attribute:
c = ole.root.getctime()
m = ole.root.getmtime()
Extract metadata
get_metadata() will check if standard property streams exist, parse all the properties they contain, and return an
OleMetadata object with the found properties as attributes.
meta = ole.get_metadata()
print(’Author:’, meta.author)
print(’Title:’, meta.title)
print(’Creation date:’, meta.create_time)
# print all metadata:
meta.dump()
42
Chapter 4. Reference
Pillow (PIL fork) Documentation, Release 2.6.0
Available attributes include:
codepage, title, subject, author, keywords, comments, template,
last_saved_by, revision_number, total_edit_time, last_printed, create_time,
last_saved_time, num_pages, num_words, num_chars, thumbnail,
creating_application, security, codepage_doc, category, presentation_target,
bytes, lines, paragraphs, slides, notes, hidden_slides, mm_clips,
scale_crop, heading_pairs, titles_of_parts, manager, company, links_dirty,
chars_with_spaces, unused, shared_doc, link_base, hlinks, hlinks_changed,
version, dig_sig, content_type, content_status, language, doc_version
See the source code of the OleMetadata class for more information.
Parse a property stream
get_properties(path) can be used to parse any property stream that is not handled by get_metadata. It returns a dictionary indexed by integers. Each integer is the index of the property, pointing to its value. For example in the standard
property stream �05SummaryInformation’, the document title is property #2, and the subject is #3.
p = ole.getproperties(’specialprops’)
By default as in the original PIL version, timestamp properties are converted into a number of seconds since Jan
1,1601. With the option convert_time, you can obtain more convenient Python datetime objects (UTC timezone).
If some time properties should not be converted (such as total editing time in �05SummaryInformation’), the list of
indexes can be passed as no_conversion:
p = ole.getproperties(’specialprops’, convert_time=True, no_conversion=[10])
Close the OLE file
Unless your application is a simple script that terminates after processing an OLE file, do not forget to close each
OleFileIO object after parsing to close the file on disk.
ole.close()
Use OleFileIO as a script
OleFileIO can also be used as a script from the command-line to display the structure of an OLE file and its metadata,
for example:
PIL/OleFileIO.py myfile.doc
You can use the option -c to check that all streams can be read fully, and -d to generate very verbose debugging
information.
4.22.2 How to contribute
The code is available in a Mercurial repository on bitbucket. You may use it to submit enhancements or to report any
issue.
If you would like to help us improve this module, or simply provide feedback, please contact me. You can help in
many ways:
• test this module on different platforms / Python versions
4.22. OleFileIO Module
43
Pillow (PIL fork) Documentation, Release 2.6.0
• find and report bugs
• improve documentation, code samples, docstrings
• write unittest test cases
• provide tricky malformed files
4.22.3 How to report bugs
To report a bug, for example a normal file which is not parsed correctly, please use the issue reporting page, or if
you prefer to do it privately, use this contact form. Please provide all the information about the context and how to
reproduce the bug.
If possible please join the debugging output of OleFileIO. For this, launch the following command :
PIL/OleFileIO.py -d -c file >debug.txt
4.22.4 Classes and Methods
class PIL.OleFileIO.OleFileIO(filename=None, raise_defects=40)
OLE container object
This class encapsulates the interface to an OLE 2 structured storage file.
openstream() methods to access the contents of this file.
Use the listdir() and
Object names are given as a list of strings, one for each subentry level. The root entry should be omitted. For
example, the following code extracts all image streams from a Microsoft Image Composer file:
ole = OleFileIO("fan.mic")
for entry in ole.listdir():
if entry[1:2] == "Image":
fin = ole.openstream(entry)
fout = open(entry[0:1], "wb")
while True:
s = fin.read(8192)
if not s:
break
fout.write(s)
You can use the viewer application provided with the Python Imaging Library to view the resulting files (which
happens to be standard TIFF files).
close()
close the OLE file, to release the file object
dumpdirectory()
Dump directory (for debugging only)
dumpfat(fat, firstindex=0)
Displays a part of FAT in human-readable form for debugging purpose
dumpsect(sector, firstindex=0)
Displays a sector in a human-readable form, for debugging purpose.
exists(filename)
Test if given filename exists as a stream or a storage in the OLE container.
Parameters filename – path of stream in storage tree. (see openstream for syntax)
44
Chapter 4. Reference
Pillow (PIL fork) Documentation, Release 2.6.0
Returns True if object exist, else False.
get_metadata()
Parse standard properties streams, return an OleMetadata object containing all the available metadata. (also
stored in the metadata attribute of the OleFileIO object)
new in version 0.25
get_rootentry_name()
Return root entry name. Should usually be �Root Entry’ or �R’ in most implementations.
get_size(filename)
Return size of a stream in the OLE container, in bytes.
Parameters filename – path of stream in storage tree (see openstream for syntax)
Returns size in bytes (long integer)
Raises
• IOError – if file not found
• TypeError – if this is not a stream
get_type(filename)
Test if given filename exists as a stream or a storage in the OLE container, and return its type.
Parameters filename – path of stream in storage tree. (see openstream for syntax)
Returns
False if object does not exist, its entry type (>0) otherwise:
• STGTY_STREAM: a stream
• STGTY_STORAGE: a storage
• STGTY_ROOT: the root entry
getctime(filename)
Return creation time of a stream/storage.
Parameters filename – path of stream/storage in storage tree. (see openstream for syntax)
Returns None if creation time is null, a python datetime object otherwise (UTC timezone)
new in version 0.26
getmtime(filename)
Return modification time of a stream/storage.
Parameters filename – path of stream/storage in storage tree. (see openstream for syntax)
Returns None if modification time is null, a python datetime object otherwise (UTC timezone)
new in version 0.26
getproperties(filename, convert_time=False, no_conversion=None)
Return properties described in substream.
Parameters
• filename – path of stream in storage tree (see openstream for syntax)
• convert_time – bool, if True timestamps will be converted to Python datetime
• no_conversion – None or list of int, timestamps not to be converted (for example total
editing time is not a real timestamp)
4.22. OleFileIO Module
45
Pillow (PIL fork) Documentation, Release 2.6.0
Returns a dictionary of values indexed by id (integer)
getsect(sect)
Read given sector from file on disk.
Parameters sect – sector index
Returns a string containing the sector data.
listdir(streams=True, storages=False)
Return a list of streams stored in this file
Parameters
• streams – bool, include streams if True (True by default) - new in v0.26
• storages – bool, include storages if True (False by default) - new in v0.26 (note: the root
storage is never included)
loaddirectory(sect)
Load the directory.
Parameters sect – sector index of directory stream.
loadfat(header)
Load the FAT table.
loadfat_sect(sect)
Adds the indexes of the given sector to the FAT
Parameters sect – string containing the first FAT sector, or array of long integers
Returns index of last FAT sector.
loadminifat()
Load the MiniFAT table.
open(filename)
Open an OLE2 file. Reads the header, FAT and directory.
Parameters filename – string-like or file-like object
openstream(filename)
Open a stream as a read-only file object (BytesIO).
Parameters filename – path of stream in storage tree (except root entry), either:
• a string using Unix path syntax, for example: �storage_1/storage_1.2/stream’
• a list of storage filenames, path to the desired stream/storage. Example: [’storage_1’,
�storage_1.2’, �stream’]
Returns file object (read-only)
Raises IOError if filename not found, or if this is not a stream.
sect2array(sect)
convert a sector to an array of 32 bits unsigned integers, swapping bytes on big endian CPUs such as
PowerPC (old Macs)
PIL.OleFileIO.isOleFile(filename)
Test if file is an OLE container (according to its header).
Parameters filename – file name or path (str, unicode)
Returns True if OLE, False otherwise.
46
Chapter 4. Reference
Pillow (PIL fork) Documentation, Release 2.6.0
4.23 PSDraw Module
The PSDraw module provides simple print support for Postscript printers. You can print text, graphics and images
through this module.
4.24 PixelAccess Class
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.
4.24.1 Example
The following script loads an image, accesses one pixel from it, then changes it.
from PIL import Image
im = Image.open(’hopper.jpg’)
px = im.load()
print (px[4,4])
px[4,4] = (0,0,0)
print (px[4,4])
Results in the following:
(23, 24, 68)
(0, 0, 0)
4.24.2 PixelAccess Class
class PixelAccess
__setitem__(self, xy, color):
Modifies the pixel at x,y. The color is given as a single numerical value for single band images, and a tuple
for multi-band images
Parameters
• xy – The pixel coordinate, given as (x, y).
• value – The pixel value.
__getitem__(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.
putpixel(self, xy, color):
Modifies the pixel at x,y. The color is given as a single numerical value for single band images, and a tuple
for multi-band images
4.23. PSDraw Module
47
Pillow (PIL fork) Documentation, Release 2.6.0
Parameters
• xy – The pixel coordinate, given as (x, y).
• value – The pixel value.
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.
4.25 PyAccess Module
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.
4.25.1 Example
The following script loads an image, accesses one pixel from it, then changes it.
from PIL import Image
im = Image.open(’hopper.jpg’)
px = im.load()
print (px[4,4])
px[4,4] = (0,0,0)
print (px[4,4])
Results in the following:
(23, 24, 68)
(0, 0, 0)
4.25.2 PyAccess Class
4.26 PIL Package (autodoc of remaining modules)
Reference for modules whose documentation has not yet been ported or written can be found here.
4.26.1 BdfFontFile Module
4.26.2 ContainerIO Module
class PIL.ContainerIO.ContainerIO(file, offset, length)
isatty()
48
Chapter 4. Reference
Pillow (PIL fork) Documentation, Release 2.6.0
read(n=0)
readline()
readlines()
seek(offset, mode=0)
tell()
4.26.3 FontFile Module
4.26.4 GdImageFile Module
4.26.5 GimpGradientFile Module
class PIL.GimpGradientFile.GimpGradientFile(fp)
Bases: PIL.GimpGradientFile.GradientFile
class PIL.GimpGradientFile.GradientFile
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)
4.26.6 GimpPaletteFile Module
class PIL.GimpPaletteFile.GimpPaletteFile(fp)
getpalette()
rawmode = �RGB’
4.26.7 ImageDraw2 Module
4.26.8 ImageFileIO Module
The ImageFileIO module can be used to read an image from a socket, or any other stream device.
Deprecated. New code should use the PIL.ImageFile.Parser class in the PIL.ImageFile module instead.
See also:
modules PIL.ImageFile.Parser
class PIL.ImageFileIO.ImageFileIO(fp)
Bases: _io.BytesIO
4.26. PIL Package (autodoc of remaining modules)
49
Pillow (PIL fork) Documentation, Release 2.6.0
4.26.9 ImageShow Module
4.26.10 ImageTransform Module
4.26.11 JpegPresets Module
JPEG quality settings equivalent to the Photoshop settings.
More presets can be added to the presets dict if needed.
Can be use when saving JPEG file.
To apply the preset, specify:
quality="preset_name"
To apply only the quantization table:
qtables="preset_name"
To apply only the subsampling setting:
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.: http://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:1:1 (or 4:2:0?).
You can get the subsampling of a JPEG with the JpegImagePlugin.get_subsampling(im) function.
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.: http://en.wikipedia.org/wiki/Quantization_matrix#Quantization_matrices,
http://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).
50
Chapter 4. Reference
Pillow (PIL fork) Documentation, Release 2.6.0
You can convert the dict format to the preset format with the JpegImagePlugin.convert_dict_qtables(dict_qtables)
function.
Libjpeg ref.: http://www.jpegcameras.com/libjpeg/libjpeg-3.html
4.26.12 PaletteFile Module
class PIL.PaletteFile.PaletteFile(fp)
getpalette()
rawmode = �RGB’
4.26.13 PcfFontFile Module
4.26.14 PngImagePlugin.iTXt Class
4.26.15 PngImagePlugin.PngInfo Class
4.26.16 TarIO Module
class PIL.TarIO.TarIO(tarfile, file)
Bases: PIL.ContainerIO.ContainerIO
4.26.17 TiffTags Module
4.26.18 WalImageFile Module
4.26.19 _binary Module
PIL._binary.i16be(c, o=0)
PIL._binary.i16le(c, o=0)
Converts a 2-bytes (16 bits) string to an integer.
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 integer.
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)
4.26. PIL Package (autodoc of remaining modules)
51
Pillow (PIL fork) Documentation, Release 2.6.0
52
Chapter 4. Reference
CHAPTER 5
Appendices
5.1 Image file formats
The Python Imaging Library supports a wide variety of raster file formats. Nearly 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.
5.1.1 Fully supported formats
BMP
PIL 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.
EPS
PIL 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.
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)
53
Pillow (PIL fork) Documentation, Release 2.6.0
GIF
PIL reads GIF87a and GIF89a versions of the GIF file format. The library writes run-length encoded GIF87a files.
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).
duration Time between frames in an animation (in milliseconds).
transparency Transparency color index. This key is omitted if the image is not transparent.
version Version (either GIF87a or GIF89a).
Reading sequences
The GIF loader supports the seek() and tell() methods.
You can seek to the next frame
(im.seek(im.tell() + 1), or rewind the file by seeking to the first frame. Random access is not supported.
Reading local images
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)]
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 PIL formats.
JPEG
PIL 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 draft() method also configures the JPEG decoder to trade some
quality for speed.
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.
54
Chapter 5. Appendices
Pillow (PIL fork) Documentation, Release 2.6.0
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.
icc-profile The ICC color profile for the image.
exif Raw EXIF data from the image.
The save() method supports the following options:
quality The image quality, on a scale from 1 (worst) to 95 (best). The default is 75. Values above 95 should be
avoided; 100 disables portions of the JPEG compression algorithm, and results in large files with hardly any
gain in image quality.
optimize If present, indicates that the encoder should make an extra pass over the image in order to select optimal
encoder settings.
progressive If present, indicates that this image should be stored as a progressive JPEG file.
dpi A tuple of integers representing the pixel density, (x,y).
icc-profile If present, the image is stored with the provided ICC profile. If this parameter is not provided, the image
will be saved with no profile attached. To preserve the existing profile:
im.save(filename, ’jpeg’, icc_profile=im.info.get(’icc_profile’))
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:1:1: Specific sampling values
• -1: equivalent to keep
• 0: equivalent to 4:4:4
• 1: equivalent to 4:2:2
• 2: equivalent to 4:1:1
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.
5.1. Image file formats
55
Pillow (PIL fork) Documentation, Release 2.6.0
JPEG 2000
New in version 2.4.0.
PIL reads and writes JPEG 2000 files containing L, LA, RGB or RGBA data. It can also read files containing YCbCr
data, which it converts on read into RGB or RGBA depending on whether or not there is an alpha channel. PIL supports
JPEG 2000 raw codestreams (.j2k files), as well as boxed JPEG 2000 files (.j2p or .jpx files). PIL 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 PIL 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 Discrete 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 options 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 PIL (if you fail to do this, you will get errors about not being able to load the _imaging DLL).
56
Chapter 5. Appendices
Pillow (PIL fork) Documentation, Release 2.6.0
MSP
PIL identifies and reads MSP files from Windows 1 and 2. The library writes uncompressed (Windows 1) versions of
this format.
PCX
PIL reads and writes PCX files containing 1, L, P, or RGB data.
PNG
PIL identifies, reads, and writes PNG files containing 1, L, P, RGB, or RGBA data. Interlaced files are supported as of
v1.1.7.
The open() method sets the following info properties, when appropriate:
gamma Gamma, given as a floating point number.
transparency Transparency color index. This key is omitted if the image is not a transparent palette image.
Open also sets Image.text to a list of the values of the tEXt, zTXt, and iTXt chunks of the PNG image.
The save() method supports the following options:
optimize If present, 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, L, and RGB images, this option controls what color image to mark as transparent.
dpi A tuple of two numbers corresponding to the desired dpi in each direction.
pnginfo A PIL.PngImagePlugin.PngInfo instance containing text tags.
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 distribution README for details.
PPM
PIL reads and writes PBM, PGM and PPM files containing 1, L or RGB data.
SPIDER
PIL reads and writes SPIDER image files of 32-bit floating point data (“F;32F”).
PIL 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
istack Set to 1 if the file is an image stack, else 0.
5.1. Image file formats
57
Pillow (PIL fork) Documentation, Release 2.6.0
nimages Set to the number of images in the stack.
A convenience method, convert2byte(), is provided for converting floating point data to byte data (mode L):
im = Image.open(’image001.spi’).convert2byte()
Writing files in SPIDER format
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.
TIFF
PIL reads and writes TIFF files. It can read both striped and tiled images, pixel and plane interleaved multi-band
images, and either uncompressed, or Packbits, LZW, or JPEG compressed images.
If you have libtiff and its headers installed, PIL can read and write many more kinds of compressed TIFF files. If not,
PIL will always write uncompressed files.
The open() method sets the following info properties:
compression Compression mode.
dpi Image resolution as an (xdpi, ydpi) tuple, where applicable. You can use the tag attribute to get more detailed
information about the image resolution.
New in version 1.1.5.
In addition, the tag attribute contains a dictionary of decoded TIFF fields. Values are stored as either strings or tuples.
Note that only short, long and ASCII tags are correctly unpacked by this release.
Saving Tiff Images
The save() method can take the following keyword arguments:
tiffinfo A ImageFileDirectory object or dict object containing tiff tags and values. The TIFF field type is
autodetected for Numeric and string values, any other types require using an ImageFileDirectory object
and setting the type in tagtype with the appropriate numerical value from TiffTags.TYPES.
New in version 2.3.0.
compression
A string containing the desired compression method for the file.
(valid only with libtiff installed)
Valid compression methods are:
[None, "tiff_ccitt", "group3", "group4",
"tiff_jpeg", "tiff_adobe_deflate", "tiff_thunderscan", "tiff_deflate",
"tiff_sgilog", "tiff_sgilog24", "tiff_raw_16"]
These arguments to set the tiff header fields are an alternative to using the general tags available through tiffinfo.
description
software
date time
58
Chapter 5. Appendices
Pillow (PIL fork) Documentation, Release 2.6.0
artist
copyright Strings
resolution unit A string of “inch”, “centimeter” or “cm”
resolution
x resolution
y resolution
dpi Either a Float, Integer, or 2 tuple of (numerator, denominator). Resolution implies an equal x and y resolution,
dpi also implies a unit of inches.
WebP
PIL reads and writes WebP files. The specifics of PIL’s capabilities with this format are currently undocumented.
The save() method supports the following options:
lossless If present, instructs the WEBP writer to use lossless compression.
quality Integer, 1-100, Defaults to 80. Sets the quality level for lossy compression.
icc_procfile 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.
XBM
PIL reads and writes X bitmap files (mode 1).
XV Thumbnails
PIL can read XV thumbnail files.
5.1.2 Read-only formats
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.
5.1. Image file formats
59
Pillow (PIL fork) Documentation, Release 2.6.0
FLI, FLC
PIL reads Autodesk FLI and FLC animations.
The open() method sets the following info properties:
duration The delay (in milliseconds) between each frame.
FPX
PIL 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.
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.
GBR
The GBR decoder reads GIMP brush files.
The open() method sets the following info properties:
description The brush name.
GD
PIL reads uncompressed GD files. Note that this file format cannot be automatically identified, so 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.
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), (255, 255)]. Any size is bigger then the original size or 255 will be ignored.
ICNS
PIL reads Mac OS X .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:
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)).
60
Chapter 5. Appendices
Pillow (PIL fork) Documentation, Release 2.6.0
IMT
PIL reads Image Tools images containing L data.
IPTC/NAA
PIL provides limited read support for IPTC/NAA newsphoto files.
MCIDAS
PIL identifies and reads 8-bit McIdas area files.
MIC (read only)
PIL 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.
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.
MIC (read only)
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.
PCD
PIL reads PhotoCD files containing RGB data. By default, the 768x512 resolution is read. You can use the draft()
method to read the lower resolution versions instead, thus effectively resizing the image to 384x256 or 192x128.
Higher resolutions cannot be read by the Python Imaging Library.
PSD
PIL identifies and reads PSD files written by Adobe Photoshop 2.5 and 3.0.
SGI
PIL reads uncompressed L, RGB, and RGBA files.
TGA
PIL reads 24- and 32-bit uncompressed and run-length encoded TGA files.
5.1. Image file formats
61
Pillow (PIL fork) Documentation, Release 2.6.0
WAL
New in version 1.1.4.
PIL reads Quake2 WAL texture files.
Note that this file format cannot be automatically identified, so you must use the open function in the WalImageFile
module to read files in this format.
By default, a Quake2 standard palette is attached to the texture. To override the palette, use the putpalette method.
XPM
PIL reads X pixmap files (mode P) with 256 colors or less.
The open() method sets the following info properties:
transparency Transparency color index. This key is omitted if the image is not transparent.
5.1.3 Write-only formats
PALM
PIL provides write-only support for PALM pixmap files.
The format code is Palm, the extension is .palm.
PDF
PIL can write PDF (Acrobat) images. Such images are written as binary PDF 1.1 files, using either JPEG or HEX
encoding depending on the image mode (and whether JPEG support is available or not).
PIXAR (read only)
PIL provides limited support for PIXAR raster files. The library can identify and read “dumped” RGB files.
The format code is PIXAR.
5.1.4 Identify-only formats
BUFR
New in version 1.1.3.
PIL provides a stub driver for BUFR files.
To add read or write support to your application, use PIL.BufrStubImagePlugin.register_handler().
FITS
New in version 1.1.5.
PIL provides a stub driver for FITS files.
To add read or write support to your application, use PIL.FitsStubImagePlugin.register_handler().
62
Chapter 5. Appendices
Pillow (PIL fork) Documentation, Release 2.6.0
GRIB
New in version 1.1.5.
PIL provides a stub driver for GRIB files.
The driver requires the file to start with a GRIB header. If you have files with embedded GRIB data, or files with
multiple GRIB fields, your application has to seek to the header before passing the file handle to PIL.
To add read or write support to your application, use PIL.GribStubImagePlugin.register_handler().
HDF5
New in version 1.1.5.
PIL provides a stub driver for HDF5 files.
To add read or write support to your application, use PIL.Hdf5StubImagePlugin.register_handler().
MPEG
PIL identifies MPEG files.
WMF
PIL can identify placable WMF files.
In PIL 1.1.4 and earlier, the WMF driver provides some limited rendering support, but not enough to be useful for any
real application.
In PIL 1.1.5 and later, the WMF driver is a stub driver. To add WMF read or write support to your application, use
PIL.WmfImagePlugin.register_handler() to register a WMF handler.
from PIL import Image
from PIL import WmfImagePlugin
class WmfHandler:
def open(self, im):
...
def load(self, im):
...
return image
def save(self, im, fp, filename):
...
wmf_handler = WmfHandler()
WmfImagePlugin.register_handler(wmf_handler)
im = Image.open("sample.wmf")
5.2 Writing your own file decoder
The Python Imaging Library 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
5.2. Writing your own file decoder
63
Pillow (PIL fork) Documentation, Release 2.6.0
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 decoder manually.
A decoder plug-in should contain a decoder class, based on the PIL.ImageFile.ImageFile base class. This
class should provide an _open() method, which reads the file header and sets up at least the mode and size
attributes. To be able to load the file, the method must also create a list of tile descriptors. The class must be
explicitly registered, via a call to the Image module.
For performance reasons, it is important that the _open() method quickly rejects files that do not have the appropriate
contents.
5.2.1 Example
The following plug-in supports a simple format, which has a 128-byte header consisting of the words “SPAM” followed 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:
from PIL import Image, ImageFile
import string
class SpamImageFile(ImageFile.ImageFile):
format = "SPAM"
format_description = "Spam raster image"
def _open(self):
# check header
header = self.fp.read(128)
if header[:4] != "SPAM":
raise SyntaxError, "not a SPAM file"
header = string.split(header)
# size in pixels (width, height)
self.size = int(header[1]), int(header[2])
# 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))
]
64
Chapter 5. Appendices
Pillow (PIL fork) Documentation, Release 2.6.0
Image.register_open("SPAM", SpamImageFile)
Image.register_extension("SPAM", ".spam")
Image.register_extension("SPAM", ".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 decoder, the calling code considers exceptions like SyntaxError, KeyError, and IndexError, as
a failure to identify the file.
Note that the decoder 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.
5.2.2 The tile attribute
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:
(decoder, region, offset, parameters)
The fields are used as follows:
decoder Specifies which decoder to use. The raw decoder used here supports uncompressed data, in a variety of
pixel formats. For more information on this decoder, see the description below.
region A 4-tuple specifying where to store data in the image.
offset Byte offset from the beginning of the file to image data.
parameters Parameters to the decoder. The contents of this field depends on the decoder specified by the first field in
the tile descriptor tuple. If the decoder doesn’t need any parameters, use None for this field.
Note that the tile attribute contains a list of tile descriptors, not just a single descriptor.
The raw decoder
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.fromstring() function, use the following syntax:
image = Image.fromstring(
mode, size, data, "raw",
raw mode, stride, orientation
)
When used in a tile descriptor, the parameter field should look like:
(raw mode, stride, orientation)
The fields are used as follows:
raw mode The pixel layout used in the file, and is used to properly convert data to PIL’s internal layout. For a
summary of the available formats, see the table below.
stride The distance in bytes between two consecutive lines in the image. If 0, the image is assumed to be packed (no
padding between lines). If omitted, the stride defaults to 0.
orientation
5.2. Writing your own file decoder
65
Pillow (PIL fork) Documentation, Release 2.6.0
Whether the first line in the image is the top line on the screen (1), or the bottom line (-1). If omitted, the
orientation defaults to 1.
The raw mode field is used to determine how the data should be unpacked to match PIL’s internal pixel layout. PIL
supports a large set of raw modes; for a complete list, see the table in the Unpack.c module. The following table
describes some commonly used raw modes:
mode
1
1;I
1;R
L
L;I
P
RGB
BGR
RGBX
RGB;L
description
1-bit bilevel, stored with the leftmost pixel in the most significant bit. 0 means black, 1 means white.
1-bit inverted bilevel, stored with the leftmost pixel in the most significant bit. 0 means white, 1 means
black.
1-bit reversed bilevel, stored with the leftmost pixel in the least significant bit. 0 means black, 1 means
white.
8-bit greyscale. 0 means black, 255 means white.
8-bit inverted greyscale. 0 means white, 255 means black.
8-bit palette-mapped image.
24-bit true colour, stored as (red, green, blue).
24-bit true colour, stored as (blue, green, red).
24-bit true colour, stored as (blue, green, red, pad).
24-bit true colour, line interleaved (first all red pixels, the all green pixels, finally all blue pixels).
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.
5.2.3 Decoding floating point data
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
F
F;8
F;8S
F;16
F;16S
F;16B
F;16BS
F;16N
F;16NS
F;32
F;32S
F;32B
F;32BS
F;32N
F;32NS
F;32F
F;32BF
F;32NF
F;64F
F;64BF
F;64NF
66
description
32-bit native floating point.
8-bit unsigned integer.
8-bit signed integer.
16-bit little endian unsigned integer.
16-bit little endian signed integer.
16-bit big endian unsigned integer.
16-bit big endian signed integer.
16-bit native unsigned integer.
16-bit native signed integer.
32-bit little endian unsigned integer.
32-bit little endian signed integer.
32-bit big endian unsigned integer.
32-bit big endian signed integer.
32-bit native unsigned integer.
32-bit native signed integer.
32-bit little endian floating point.
32-bit big endian floating point.
32-bit native floating point.
64-bit little endian floating point.
64-bit big endian floating point.
64-bit native floating point.
Chapter 5. Appendices
Pillow (PIL fork) Documentation, Release 2.6.0
5.2.4 The bit decoder
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 fromstring function, use the following syntax:
image = fromstring(
mode, size, data, "bit",
bits, pad, fill, sign, orientation
)
When used in a tile descriptor, the parameter field should look like:
(bits, pad, fill, sign, orientation)
The fields are used as follows:
bits Number of bits per pixel (2-32). No default.
pad Padding between lines, in bits. This is either 0 if there is no padding, or 8 if lines are padded to full bytes. If
omitted, the pad value defaults to 8.
fill Controls how data are added to, and stored from, the decoder bit buffer.
fill=0 Add bytes to the LSB end of the decoder buffer; store pixels from the MSB end.
fill=1 Add bytes to the MSB end of the decoder buffer; store pixels from the MSB end.
fill=2 Add bytes to the LSB end of the decoder buffer; store pixels from the LSB end.
fill=3 Add bytes to the MSB end of the decoder buffer; store pixels from the LSB end.
If omitted, the fill order defaults to 0.
sign If non-zero, bit fields are sign extended. If zero or omitted, bit fields are unsigned.
orientation Whether the first line in the image is the top line on the screen (1), or the bottom line (-1). If omitted, the
orientation defaults to 1.
5.2. Writing your own file decoder
67
Pillow (PIL fork) Documentation, Release 2.6.0
68
Chapter 5. Appendices
CHAPTER 6
Original PIL README
What follows is the original PIL 1.1.7 README file contents.
The Python Imaging Library
$Id$
Release 1.1.7 (November 15, 2009)
====================================================================
The Python Imaging Library 1.1.7
====================================================================
Contents
-------+ Introduction
+ Support Options
- Commercial support
- Free support
+ Software License
+ Build instructions (all platforms)
- Additional notes for Mac OS X
- Additional notes for Windows
-------------------------------------------------------------------Introduction
-------------------------------------------------------------------The Python Imaging Library (PIL) adds image processing capabilities
to your Python environment. This library provides extensive file
format support, an efficient internal representation, and powerful
image processing capabilities.
This source kit has been built and tested with Python 2.0 and newer,
on Windows, Mac OS X, and major Unix platforms. Large parts of the
library also work on 1.5.2 and 1.6.
The main distribution site for this software is:
http://www.pythonware.com/products/pil/
That site also contains information about free and commercial support
options, PIL add-ons, answers to frequently asked questions, and more.
69
Pillow (PIL fork) Documentation, Release 2.6.0
Development versions (alphas, betas) are available here:
http://effbot.org/downloads/
The PIL handbook is not included in this distribution; to get the
latest version, check:
http://www.pythonware.com/library/
http://effbot.org/books/imagingbook/ (drafts)
For installation and licensing details, see below.
-------------------------------------------------------------------Support Options
-------------------------------------------------------------------+ Commercial Support
Secret Labs (PythonWare) offers support contracts for companies using
the Python Imaging Library in commercial applications, and in missioncritical environments. The support contract includes technical support,
bug fixes, extensions to the PIL library, sample applications, and more.
For the full story, check:
http://www.pythonware.com/products/pil/support.htm
+ Free Support
For support and general questions on the Python Imaging Library, send
e-mail to the Image SIG mailing list:
[email protected]
You can join the Image SIG by sending a mail to:
[email protected]
Put "subscribe" in the message body to automatically subscribe to the
list, or "help" to get additional information. Alternatively, you can
send your questions to the Python mailing list, [email protected],
or post them to the newsgroup comp.lang.python. DO NOT SEND SUPPORT
QUESTIONS TO PYTHONWARE ADDRESSES.
-------------------------------------------------------------------Software License
-------------------------------------------------------------------The Python Imaging Library is
Copyright (c) 1997-2009 by Secret Labs AB
Copyright (c) 1995-2009 by Fredrik Lundh
70
Chapter 6. Original PIL README
Pillow (PIL fork) Documentation, Release 2.6.0
By obtaining, using, and/or copying this software and/or its
associated documentation, you agree that you have read, understood,
and will comply with the following terms and conditions:
Permission to use, copy, modify, and distribute this software and its
associated documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appears in all
copies, and that both that copyright notice and this permission notice
appear in supporting documentation, and that the name of Secret Labs
AB or the author not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-------------------------------------------------------------------Build instructions (all platforms)
-------------------------------------------------------------------For a list of changes in this release, see the CHANGES document.
0. If you’re in a hurry, try this:
$ tar xvfz Imaging-1.1.7.tar.gz
$ cd Imaging-1.1.7
$ python setup.py install
If you prefer to know what you’re doing, read on.
1. Prerequisites.
If you need any of the features described below, make sure you
have the necessary libraries before building PIL.
feature
library
----------------------------------------------------------------JPEG support
libjpeg (6a or 6b)
http://www.ijg.org
http://www.ijg.org/files/jpegsrc.v6b.tar.gz
ftp://ftp.uu.net/graphics/jpeg/
PNG support
zlib (1.2.3 or later is recommended)
http://www.gzip.org/zlib/
OpenType/TrueType
support
freetype2 (2.3.9 or later is recommended)
http://www.freetype.org
http://freetype.sourceforge.net
71
Pillow (PIL fork) Documentation, Release 2.6.0
CMS support
support
littleCMS (1.1.5 or later is recommended)
http://www.littlecms.com/
If you have a recent Linux version, the libraries provided with the
operating system usually work just fine. If some library is
missing, installing a prebuilt version (jpeg-devel, zlib-devel,
etc) is usually easier than building from source. For example, for
Ubuntu 9.10 (karmic), you can install the following libraries:
sudo
sudo
sudo
sudo
apt-get
apt-get
apt-get
apt-get
install
install
install
install
libjpeg62-dev
zlib1g-dev
libfreetype6-dev
liblcms1-dev
If you’re using Mac OS X, you can use the ’fink’ tool to install
missing libraries (also see the Mac OS X section below).
Similar tools are available for many other platforms.
2. To build under Python 1.5.2, you need to install the stand-alone
version of the distutils library:
http://www.python.org/sigs/distutils-sig/download.html
You can fetch distutils 1.0.2 from the Python source repository:
svn export http://svn.python.org/projects/python/tags/Distutils-1_0_2/Lib/distutils/
For newer releases, the distutils library is included in the
Python standard library.
NOTE: Version 1.1.7 is not fully compatible with 1.5.2. Some
more recent additions to the library may not work, but the core
functionality is available.
3. If you didn’t build Python from sources, make sure you have
Python’s build support files on your machine. If you’ve downloaded a prebuilt package (e.g. a Linux RPM), you probably
need additional developer packages. Look for packages named
"python-dev", "python-devel", or similar. For example, for
Ubuntu 9.10 (karmic), use the following command:
sudo apt-get install python-dev
4. When you have everything you need, unpack the PIL distribution
(the file Imaging-1.1.7.tar.gz) in a suitable work directory:
$ cd MyExtensions # example
$ gunzip Imaging-1.1.7.tar.gz
$ tar xvf Imaging-1.1.7.tar
5. Build the library. We recommend that you do an in-place build,
and run the self test before installing.
72
Chapter 6. Original PIL README
Pillow (PIL fork) Documentation, Release 2.6.0
$ cd Imaging-1.1.7
$ python setup.py build_ext -i
$ python selftest.py
During the build process, the setup.py will display a summary
report that lists what external components it found. The selftest will display a similar report, with what external components
the tests found in the actual build files:
---------------------------------------------------------------PIL 1.1.7 SETUP SUMMARY
---------------------------------------------------------------*** TKINTER support not available (Tcl/Tk 8.5 libraries needed)
--- JPEG support available
--- ZLIB (PNG/ZIP) support available
--- FREETYPE support available
---------------------------------------------------------------Make sure that the optional components you need are included.
If the build script won’t find a given component, you can edit the
setup.py file and set the appropriate ROOT variable. For details,
see instructions in the file.
If the build script finds the component, but the tests cannot
identify it, try rebuilding *all* modules:
$ python setup.py clean
$ python setup.py build_ext -i
6. If the setup.py and selftest.py commands finish without any
errors, you’re ready to install the library:
$ python setup.py install
(depending on how Python has been installed on your machine,
you might have to log in as a superuser to run the ’install’
command, or use the ’sudo’ command to run ’install’.)
-------------------------------------------------------------------Additional notes for Mac OS X
-------------------------------------------------------------------On Mac OS X you will usually install additional software such as
libjpeg or freetype with the "fink" tool, and then it ends up in
"/sw". If you have installed the libraries elsewhere, you may have
to tweak the "setup.py" file before building.
-------------------------------------------------------------------Additional notes for Windows
-------------------------------------------------------------------On Windows, you need to tweak the ROOT settings in the "setup.py"
file, to make it find the external libraries. See comments in the
file for details.
73
Pillow (PIL fork) Documentation, Release 2.6.0
Make sure to build PIL and the external libraries with the same
runtime linking options as was used for the Python interpreter
(usually /MD, under Visual Studio).
Note that most Python distributions for Windows include libraries
compiled for Microsoft Visual Studio. You can get the free Express
edition of Visual Studio from:
http://www.microsoft.com/Express/
To build extensions using other tool chains, see the "Using
non-Microsoft compilers on Windows" section in the distutils handbook:
http://www.python.org/doc/current/inst/non-ms-compilers.html
For additional information on how to build extensions using the
popular MinGW compiler, see:
http://mingw.org (compiler)
http://sebsauvage.net/python/mingw.html (build instructions)
http://sourceforge.net/projects/gnuwin32 (prebuilt libraries)
74
Chapter 6. Original PIL README
CHAPTER 7
Indices and tables
• genindex
• modindex
• search
75
Pillow (PIL fork) Documentation, Release 2.6.0
76
Chapter 7. Indices and tables
Python Module Index
p
PIL._binary, 51
PIL.ContainerIO, 48
PIL.ExifTags, 39
PIL.GimpGradientFile, 49
PIL.GimpPaletteFile, 49
PIL.Image, 23
PIL.ImageChops, 25
PIL.ImageCms, 26
PIL.ImageColor, 25
PIL.ImageDraw, 26
PIL.ImageEnhance, 30
PIL.ImageFile, 30
PIL.ImageFileIO, 49
PIL.ImageFilter, 31
PIL.ImageFont, 33
PIL.ImageGrab, 34
PIL.ImageMath, 34
PIL.ImageMorph, 36
PIL.ImageOps, 36
PIL.ImagePalette, 36
PIL.ImagePath, 36
PIL.ImageQt, 37
PIL.ImageSequence, 37
PIL.ImageStat, 38
PIL.ImageTk, 38
PIL.ImageWin, 39
PIL.JpegPresets, 50
PIL.OleFileIO, 39
PIL.PaletteFile, 51
PIL.PSDraw, 46
PIL.PyAccess, 48
PIL.TarIO, 51
PIL.TiffTags, 51
77
Pillow (PIL fork) Documentation, Release 2.6.0
78
Python Module Index
Index
A
getsize()
(PIL.ImageFont.PIL.ImageFont.ImageFont
method), 33
abs() (built-in function), 35
arc() (PIL.ImageDraw.PIL.ImageDraw.Draw method), 27 GimpGradientFile (class in PIL.GimpGradientFile), 49
GimpPaletteFile (class in PIL.GimpPaletteFile), 49
gradient (PIL.GimpGradientFile.GradientFile attribute),
B
49
bitmap()
(PIL.ImageDraw.PIL.ImageDraw.Draw
GradientFile (class in PIL.GimpGradientFile), 49
method), 28
C
chord() (PIL.ImageDraw.PIL.ImageDraw.Draw method),
28
compact() (PIL.ImagePath.PIL.ImagePath.Path method),
37
ContainerIO (class in PIL.ContainerIO), 48
convert() (built-in function), 35
count (PIL.ImageStat.PIL.ImageStat.Stat attribute), 38
curved() (in module PIL.GimpGradientFile), 49
E
ellipse()
I
i16be() (in module PIL._binary), 51
i16le() (in module PIL._binary), 51
i32be() (in module PIL._binary), 51
i32le() (in module PIL._binary), 51
i8() (in module PIL._binary), 51
ImageFileIO (class in PIL.ImageFileIO), 49
ImageQt.ImageQt (class in PIL.ImageQt), 37
info (in module PIL.Image), 24
int() (built-in function), 35
isatty() (PIL.ContainerIO.ContainerIO method), 48
Iterator (class in PIL.ImageSequence), 38
(PIL.ImageDraw.PIL.ImageDraw.Draw
method), 28
K
eval() (in module PIL.ImageMath), 34
Kernel (class in PIL.ImageFilter), 32
extrema (PIL.ImageStat.PIL.ImageStat.Stat attribute), 38
F
float() (built-in function), 35
format (in module PIL.Image), 24
G
GaussianBlur (class in PIL.ImageFilter), 32
getbbox() (PIL.ImagePath.PIL.ImagePath.Path method),
37
getmask()
(PIL.ImageFont.PIL.ImageFont.ImageFont
method), 33
getpalette()
(PIL.GimpGradientFile.GradientFile
method), 49
getpalette()
(PIL.GimpPaletteFile.GimpPaletteFile
method), 49
getpalette() (PIL.PaletteFile.PaletteFile method), 51
L
line() (PIL.ImageDraw.PIL.ImageDraw.Draw method),
28
linear() (in module PIL.GimpGradientFile), 49
M
map() (PIL.ImagePath.PIL.ImagePath.Path method), 37
max() (built-in function), 36
MaxFilter (class in PIL.ImageFilter), 32
mean (PIL.ImageStat.PIL.ImageStat.Stat attribute), 38
median (PIL.ImageStat.PIL.ImageStat.Stat attribute), 38
MedianFilter (class in PIL.ImageFilter), 32
min() (built-in function), 36
MinFilter (class in PIL.ImageFilter), 32
mode (in module PIL.Image), 24
ModeFilter (class in PIL.ImageFilter), 32
79
Pillow (PIL fork) Documentation, Release 2.6.0
O
o16be() (in module PIL._binary), 51
o16le() (in module PIL._binary), 51
o32be() (in module PIL._binary), 51
o32le() (in module PIL._binary), 51
o8() (in module PIL._binary), 51
PIL.TiffTags (module), 51
PixelAccess (built-in class), 47
point() (PIL.ImageDraw.PIL.ImageDraw.Draw method),
29
polygon()
(PIL.ImageDraw.PIL.ImageDraw.Draw
method), 29
P
R
palette (in module PIL.Image), 24
PaletteFile (class in PIL.PaletteFile), 51
pieslice()
(PIL.ImageDraw.PIL.ImageDraw.Draw
method), 28
PIL._binary (module), 51
PIL.ContainerIO (module), 48
PIL.ExifTags (module), 39
PIL.ExifTags.GPSTAGS (class in PIL.ExifTags), 39
PIL.ExifTags.TAGS (class in PIL.ExifTags), 39
PIL.GimpGradientFile (module), 49
PIL.GimpPaletteFile (module), 49
PIL.Image (module), 23
PIL.ImageChops (module), 25
PIL.ImageCms (module), 26
PIL.ImageColor (module), 25
PIL.ImageDraw (module), 26
PIL.ImageDraw.Draw (class in PIL.ImageDraw), 27
PIL.ImageDraw.ImageDraw()
(in
module
PIL.ImageDraw), 30
PIL.ImageEnhance (module), 30
PIL.ImageFile (module), 30
PIL.ImageFileIO (module), 49
PIL.ImageFilter (module), 31
PIL.ImageFont (module), 33
PIL.ImageGrab (module), 34
PIL.ImageGrab.grab() (in module PIL.ImageGrab), 34
PIL.ImageGrab.grabclipboard()
(in
module
PIL.ImageGrab), 34
PIL.ImageMath (module), 34
PIL.ImageMorph (module), 36
PIL.ImageOps (module), 36
PIL.ImagePalette (module), 36
PIL.ImagePath (module), 36
PIL.ImagePath.Path (class in PIL.ImagePath), 36
PIL.ImageQt (module), 37
PIL.ImageSequence (module), 37
PIL.ImageStat (module), 38
PIL.ImageStat.Stat (class in PIL.ImageStat), 38
PIL.ImageTk (module), 38
PIL.ImageWin (module), 39
PIL.JpegPresets (module), 50
PIL.OleFileIO (module), 39
PIL.PaletteFile (module), 51
PIL.PSDraw (module), 46
PIL.PyAccess (module), 48
PIL.TarIO (module), 51
RankFilter (class in PIL.ImageFilter), 32
rawmode (PIL.GimpPaletteFile.GimpPaletteFile attribute), 49
rawmode (PIL.PaletteFile.PaletteFile attribute), 51
read() (PIL.ContainerIO.ContainerIO method), 49
readline() (PIL.ContainerIO.ContainerIO method), 49
readlines() (PIL.ContainerIO.ContainerIO method), 49
rectangle()
(PIL.ImageDraw.PIL.ImageDraw.Draw
method), 29
rms (PIL.ImageStat.PIL.ImageStat.Stat attribute), 38
80
S
seek() (PIL.ContainerIO.ContainerIO method), 49
setfill() (PIL.ImageDraw.PIL.ImageDraw.Draw method),
30
setfont()
(PIL.ImageDraw.PIL.ImageDraw.Draw
method), 30
setink() (PIL.ImageDraw.PIL.ImageDraw.Draw method),
30
shape() (PIL.ImageDraw.PIL.ImageDraw.Draw method),
29
sine() (in module PIL.GimpGradientFile), 49
size (in module PIL.Image), 24
sphere_decreasing() (in module PIL.GimpGradientFile),
49
sphere_increasing() (in module PIL.GimpGradientFile),
49
stddev (PIL.ImageStat.PIL.ImageStat.Stat attribute), 38
sum (PIL.ImageStat.PIL.ImageStat.Stat attribute), 38
sum2 (PIL.ImageStat.PIL.ImageStat.Stat attribute), 38
T
TarIO (class in PIL.TarIO), 51
tell() (PIL.ContainerIO.ContainerIO method), 49
text() (PIL.ImageDraw.PIL.ImageDraw.Draw method),
29
textsize()
(PIL.ImageDraw.PIL.ImageDraw.Draw
method), 29
tolist() (PIL.ImagePath.PIL.ImagePath.Path method), 37
transform()
(PIL.ImagePath.PIL.ImagePath.Path
method), 37
U
UnsharpMask (class in PIL.ImageFilter), 32
Index
Pillow (PIL fork) Documentation, Release 2.6.0
V
var (PIL.ImageStat.PIL.ImageStat.Stat attribute), 38
Index
81
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF

advertisement