前记
PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了。PIL功能非常强大,但API却非常简单易用。
由于PIL仅支持到Python 2.7,加上年久失修,于是一群志愿者在PIL的基础上创建了兼容的版本,名字叫Pillow,支持最新Python 3.x,又加入了许多新特性,因此,我们可以直接安装使用Pillow。
一、安装Pillow
如果安装了Anaconda,Pillow就已经可用了。否则,需要在命令行下通过pip安装:
$ pip install pillow
如果遇到Permission denied安装失败,请加上sudo重试。
操作图像示例
from PIL import Image
# 打开一个jpg图像文件,注意是当前路径:
im = Image.open('test.jpg')
# 获得图像尺寸:
w, h = im.size
print('Original image size: %sx%s' % (w, h))
# 缩放到50%:
im.thumbnail((w//2, h//2))
print('Resize image to: %sx%s' % (w//2, h//2))
# 把缩放后的图像用jpeg格式保存:
im.save('thumbnail.jpg', 'jpeg')
其他功能如切片、旋转、滤镜、输出文字、调色板等一应俱全。
from PIL import Image, ImageFilter
# 打开一个jpg图像文件,注意是当前路径:
im = Image.open('test.jpg')
# 应用模糊滤镜:
im2 = im.filter(ImageFilter.BLUR)
im2.save('blur.jpg', 'jpeg')
PIL的ImageDraw提供了一系列绘图方法,让我们可以直接绘图。比如要生成字母验证码图片:
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
# 随机字母:
def rndChar():
return chr(random.randint(65, 90))
# 随机颜色1:
def rndColor():
return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
# 随机颜色2:
def rndColor2():
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
# 240 x 60:
width = 60 * 4
height = 60
image = Image.new('RGB', (width, height), (255, 255, 255))
# 创建Font对象:
font = ImageFont.truetype('Arial.ttf', 36)
# 创建Draw对象:
draw = ImageDraw.Draw(image)
# 填充每个像素:
for x in range(width):
for y in range(height):
draw.point((x, y), fill=rndColor())
# 输出文字:
for t in range(4):
draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2())
# 模糊:
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg', 'jpeg')
我们用随机颜色填充背景,再画上文字,最后对图像进行模糊,得到验证码图片如下:
如果运行的时候报错:
IOError: cannot open resource
这是因为PIL无法定位到字体文件的位置,可以根据操作系统提供绝对路径,比如:
'/Library/Fonts/Arial.ttf'
二、官方文档
Warnings(需要特别注意)
Pillow and PIL cannot co-exist in the same environment. Before installing Pillow, please uninstall PIL.
Pillow库和PIL库不能在相同的环境中共存。在安装Pillow库之前,请卸载PIL库。
Pillow >= 1.0 no longer supports “import Image”. Please use “from PIL import Image” instead.
Pillow库> = 1.0不再支持“import Image”。请使用“from PIL import Image”。
Pillow >= 2.1.0 no longer supports “import _imaging”. Please use “from PIL.Image import core as _imaging” instead.
Pillow库> = 2.1.0不再支持“import _imaging”。请使用“from PIL.Image import core as _imaging”代替。
版本支持列表:
三、细说安装
The following instructions will install Pillow with support for most common image formats. See External Libraries for a full list of external libraries supported.
下面的说明将安装Pillow库支持最常用的图像格式。看到外部库的完整列表外部库支持。
Install Pillow with pip:
$ pip install Pillow
- Windows Installation(Windows安装)
We provide Pillow binaries for Windows compiled for the matrix of supported Pythons in both 32 and 64-bit versions in wheel, egg, and executable installers. These binaries have all of the optional libraries included except for raqm and libimagequant:
我们提供Pillow库为Windows二进制文件编译支持矩阵的蟒蛇在32和64位版本轮,鸡蛋,和可执行的安装程序。这些二进制文件的所有可选库包括除了raqm和libimagequant:
> pip install Pillow
- macOS Installation(macOS安装)
We provide binaries for macOS for each of the supported Python versions in the wheel format. These include support for all optional libraries except libimagequant. Raqm support requires libraqm, fribidi, and harfbuzz to be installed separately:
我们提供二进制文件为每个支持的macOS车轮格式的Python版本。这包括支持所有可选库libimagequant除外。Raqm支持需要libraqm、fribidi harfbuzz单独安装:
$ pip install Pillow
- Linux Installation(Linux安装)
We provide binaries for Linux for each of the supported Python versions in the manylinux wheel format. These include support for all optional libraries except libimagequant. Raqm support requires libraqm, fribidi, and harfbuzz to be installed separately:
我们为Linux提供二进制文件为每个支持的Python版本manylinux轮格式。这包括支持所有可选库libimagequant除外。Raqm支持需要libraqm、fribidi harfbuzz单独安装:
$ pip install Pillow
Most major Linux distributions, including Fedora, Debian/Ubuntu and ArchLinux also include Pillow in packages that previously contained PIL e.g. python-imaging.
大多数Linux发行版默认包含Pillow库,包括Fedora, Debian / Ubuntu和ArchLinux还包括以前包含PIL库如python-imaging 包。
FreeBSD Installation(FreeBSD安装)
Pillow can be installed on FreeBSD via the official Ports or Packages systems:
Pillow库可以通过官方的渠道或包系统安装在FreeBSD系统:
Ports:
$ cd /usr/ports/graphics/py-pillow && make install clean
Packages:
$ pkg install py27-pillow
The Pillow FreeBSD port and packages are tested by the ports team with all supported FreeBSD versions and against Python 2.7 and 3.x.
Pillow库FreeBSD港口和包由端口测试团队与所有支持FreeBSD和Python 2.7版本和3.x版本。
Building From Source(从源代码构建)
Download and extract the compressed archive from PyPI.
从PyPI下载和提取压缩存档。
- External Libraries(外部库)
You do not need to install all supported external libraries to use Pillow’s basic features. Zlib and libjpeg are required by default.
你不需要安装所有支持的外部库使用Pillow库的基本特性。Zlib和libjpeg默认是必需的。
There are scripts to install the dependencies for some operating systems included in the depends
directory. Also see the Dockerfiles in our docker images repo.
脚本安装的依赖关系有一些操作系统包含在看目录。也在docker images repo看到Dockerfiles。
Pillow库的许多特性需要外部库:
libjpeg provides JPEG functionality.
Pillow has been tested with libjpeg versions 6b, 8, 9-9c and libjpeg-turbo version 8.
Starting with Pillow 3.0.0, libjpeg is required by default, but may be disabled with the --disable-jpeg flag.
zlib provides access to compressed PNGs
Starting with Pillow 3.0.0, zlib is required by default, but may be disabled with the --disable-zlib flag.
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.7-2.9.
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 above 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.
Pillow does not support the earlier 1.5 series which ships with Ubuntu <= 14.04 and Debian Jessie.
libimagequant provides improved color quantization
Pillow has been tested with libimagequant 2.6-2.12.2
Libimagequant is licensed GPLv3, which is more restrictive than the Pillow license, therefore we will not be distributing binaries with libimagequant support enabled.
Windows support: Libimagequant requires VS2013/MSVC 18 to compile, so it is unlikely to work with Python 2.7 on Windows.
libraqm provides complex text layout support.
libraqm provides bidirectional text support (using FriBiDi), shaping (using HarfBuzz), and proper script itemization. As a result, Raqm can support most writing systems covered by Unicode.
libraqm depends on the following libraries: FreeType, HarfBuzz, FriBiDi, make sure that you install them before installing libraqm if not available as package in your system.
setting text direction or font features is not supported without libraqm.
libraqm is dynamically loaded in Pillow 5.0.0 and above, so support is available if all the libraries are installed.
Windows support: Raqm support is currently unsupported on Windows.
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:
如果前提是安装在机器的标准库的位置(例如,/ usr或/usr/local),不需要额外的配置。如果他们是安装在标准位置,您可能需要配置使用setuptools这些位置通过编辑设置。py或设置。cfg或在命令行上添加环境变量:
$ CFLAGS="-I/usr/pkg/include" pip install pillow
If Pillow has been previously built without the required prerequisites, it may be necessary to manually clear the pip cache or build without cache using the --no-cache-dir option to force a build with newly installed external libraries.
如果枕头之前构建没有所需的先决条件,可能需要手动清除pip缓存或构建缓存使用——no-cache-dir选项强制建立和新安装的外部库。
- Build Options(构建选项)
Environment variable: MAX_CONCURRENCY=n. By default, Pillow will use multiprocessing to build the extension on all available CPUs, but not more than 4. Setting MAX_CONCURRENCY to 1 will disable parallel building.
Build flags: --disable-zlib, --disable-jpeg, --disable-tiff, --disable-freetype, --disable-lcms, --disable-webp, --disable-webpmux, --disable-jpeg2000, --disable-imagequant. Disable building the corresponding feature even if the development libraries are present on the building machine.
Build flags: --enable-zlib, --enable-jpeg, --enable-tiff, --enable-freetype, --enable-lcms, --enable-webp, --enable-webpmux, --enable-jpeg2000, --enable-imagequant. Require that the corresponding feature is built. The build will raise an exception if the libraries are not found. Webpmux (WebP metadata) relies on WebP support. Tcl and Tk also must be used together.
Build flag: --disable-platform-guessing. Skips all of the platform dependent guessing of include and library directories for automated build systems that configure the proper paths in the environment variables (e.g. Buildroot).
Build flag: --debug. Adds a debugging flag to the include and library search process to dump all paths searched for and found to stdout.
Sample usage:
$ MAX_CONCURRENCY=1 python setup.py build_ext --enable-[feature] install
or using pip:
$ pip install pillow --global-option="build_ext" --global-option="--enable-[feature]"
Building on macOS(建立在macOS)
The Xcode command line tools are required to compile portions of Pillow. The tools are installed by running xcode-select --install from the command line. The command line tools are required even if you have the full Xcode package installed. It may be necessary to run sudo xcodebuild -license to accept the license prior to using the tools.
Xcode命令行工具需要编译的部分枕头。安装的工具运行xcode-select——从命令行安装。命令行工具是必需的,即使你有完整的Xcode包安装。可能需要运行sudo xcodebuild许可证之前接受许可使用的工具。
The easiest way to install external libraries is via Homebrew. After you install Homebrew, run:
安装外部库最简单的方法是通过自制程序。你安装自制程序后,运行:
$ brew install libtiff libjpeg webp little-cms2
To install libraqm on macOS use Homebrew to install its dependencies:
安装libraqm macOS使用自制程序来安装它的依赖关系:
$ brew install freetype harfbuzz fribidi
Then see depends/install_raqm_cmake.sh
to install libraqm.
然后看depends/install_raqm_cmake.sh。安装libraqm。
Now install Pillow with:
现在安装枕头:
$ pip install Pillow
or from within the uncompressed source directory:
或在未压缩的源目录:
$ python setup.py install
Building on Windows(Windows上)
We don’t recommend trying to build on Windows. It is a maze of twisty passages, mostly dead ends. There are build scripts and notes for the Windows build in the winbuild directory.
我们不建议试图建立在Windows。弯弯曲曲的通道是一个迷宫,大多是死胡同。有构建脚本和笔记的Windows建立winbuild目录。
Building on FreeBSD
Only FreeBSD 10 and 11 tested
只有FreeBSD 10和11测试过
Make sure you have Python’s development libraries installed.:
确保您已经安装了Python的开发库。
$ sudo pkg install python2
Or for Python 3:
$ sudo pkg install python3
Prerequisites are installed on FreeBSD 10 or 11 with:
先决条件是安装在FreeBSD 10或11:
$ sudo pkg install jpeg-turbo tiff webp lcms2 freetype2 openjpeg harfbuzz fribidi
Then see depends/install_raqm_cmake.sh
to install libraqm.
然后看depends/install_raqm_cmake.sh。安装libraqm。
Building on Linux
If you didn’t build Python from source, make sure you have Python’s development libraries installed.
如果你没有从源代码构建Python,确保您已经安装了Python的开发库。
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 dnf install python-devel redhat-rpm-config
Or for Python 3:
$ sudo dnf install python3-devel redhat-rpm-config
redhat-rpm-config is required on Fedora 23, but not earlier versions.
redhat-rpm-config在Fedora 23是必需的,但不是早期版本。
Prerequisites are installed on Ubuntu 14.04 LTS with:
Ubuntu 14.04 LTS上安装先决条件:
$ sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev \
libfreetype6-dev liblcms2-dev libwebp-dev libharfbuzz-dev libfribidi-dev \
tcl8.6-dev tk8.6-dev python-tk
Then see depends/install_raqm.sh to install libraqm.
Prerequisites are installed on recent RedHat Centos or Fedora with:
最近RedHat Centos或Fedora上安装先决条件:
$ sudo dnf install libtiff-devel libjpeg-devel zlib-devel freetype-devel \
lcms2-devel libwebp-devel tcl-devel tk-devel libraqm-devel \
libimagequant-devel
Note that the package manager may be yum or dnf, depending on the exact distribution.
注意,包管理器可能是百胜或dnf,取决于具体的分布。
See also the Dockerfile
s in the Test Infrastructure repo (https://github.com/python-pillow/docker-images) for a known working install process for other tested distros.
参见测试基础设施中的Dockerfiles回购(https://github.com/python-pillow/docker-images)一个已知的工作为其他测试发行版安装过程。
Building on Android
Basic Android support has been added for compilation within the Termux environment. The dependencies can be installed by:
基本的Android支持Termux中已经添加了编译环境。可以安装的依赖关系:
$ pkg -y install python python-dev ndk-sysroot clang make \
libjpeg-turbo-dev
这是测试在Termux应用ChromeOS,在x86上。
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, macOS, and Windows.
当前平台支持库Pillow。二进制发行版提供志愿者的基础上为每一个版本,但源应该编译和运行平台支持上市。一般来说,我们的目标是支持所有当前版本的Linux, macOS和Windows。
- Continuous Integration Targets(持续集成的目标)
These platforms are built and tested for every change.
这些平台构建和测试每一个变化。
Mac OS X CI is not run for every commit, but is run for every release.
Mac OS X CI不是运行每一个提交,但每个发布版本都可运行。
Other Platforms
These platforms have been reported to work at the versions mentioned.
这些平台在提到的版本已报告工作。
Contributors please test Pillow on your platform then update this document and send a pull request.
投稿者请测试枕在你的平台上然后更新这个文档和发送一个请求。
Old Versions
You can download old distributions from the release history at PyPI and by direct URL access eg. https://pypi.org/project/Pillow/1.0/.
您可以下载旧的分布在PyPI释放历史和直接的URL访问。https://pypi.org/project/Pillow/1.0/。