前記
PIL:Python Imaging Library组题,已經(jīng)是Python平臺(tái)事實(shí)上的圖像處理標(biāo)準(zhǔn)庫了吧凉。PIL功能非常強(qiáng)大钧敞,但API卻非常簡(jiǎn)單易用满粗。
由于PIL僅支持到Python 2.7殖熟,加上年久失修帆谍,于是一群志愿者在PIL的基礎(chǔ)上創(chuàng)建了兼容的版本培己,名字叫Pillow巡揍,支持最新Python 3.x蘑斧,又加入了許多新特性,因此边翼,我們可以直接安裝使用Pillow鱼响。
一、安裝Pillow
如果安裝了Anaconda组底,Pillow就已經(jīng)可用了丈积。否則,需要在命令行下通過pip安裝:
$ pip install pillow
如果遇到Permission denied安裝失敗债鸡,請(qǐng)加上sudo重試桶癣。
操作圖像示例
from PIL import Image
# 打開一個(gè)jpg圖像文件,注意是當(dāng)前路徑:
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')
其他功能如切片娘锁、旋轉(zhuǎn)牙寞、濾鏡、輸出文字莫秆、調(diào)色板等一應(yīng)俱全间雀。
from PIL import Image, ImageFilter
# 打開一個(gè)jpg圖像文件,注意是當(dāng)前路徑:
im = Image.open('test.jpg')
# 應(yīng)用模糊濾鏡:
im2 = im.filter(ImageFilter.BLUR)
im2.save('blur.jpg', 'jpeg')
PIL的ImageDraw提供了一系列繪圖方法镊屎,讓我們可以直接繪圖惹挟。比如要生成字母驗(yàn)證碼圖片:
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
# 隨機(jī)字母:
def rndChar():
return chr(random.randint(65, 90))
# 隨機(jī)顏色1:
def rndColor():
return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
# 隨機(jī)顏色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))
# 創(chuàng)建Font對(duì)象:
font = ImageFont.truetype('Arial.ttf', 36)
# 創(chuàng)建Draw對(duì)象:
draw = ImageDraw.Draw(image)
# 填充每個(gè)像素:
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')
我們用隨機(jī)顏色填充背景,再畫上文字缝驳,最后對(duì)圖像進(jìn)行模糊连锯,得到驗(yàn)證碼圖片如下:
如果運(yùn)行的時(shí)候報(bào)錯(cuò):
IOError: cannot open resource
這是因?yàn)镻IL無法定位到字體文件的位置,可以根據(jù)操作系統(tǒng)提供絕對(duì)路徑用狱,比如:
'/Library/Fonts/Arial.ttf'
二运怖、官方文檔
Warnings(需要特別注意)
Pillow and PIL cannot co-exist in the same environment. Before installing Pillow, please uninstall PIL.
Pillow庫和PIL庫不能在相同的環(huán)境中共存。在安裝Pillow庫之前,請(qǐng)卸載PIL庫夏伊。
Pillow >= 1.0 no longer supports “import Image”. Please use “from PIL import Image” instead.
Pillow庫> = 1.0不再支持“import Image”摇展。請(qǐng)使用“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”溺忧。請(qǐng)使用“from PIL.Image import core as _imaging”代替咏连。
版本支持列表:
三、細(xì)說安裝
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二進(jìn)制文件編譯支持矩陣的蟒蛇在32和64位版本輪,雞蛋,和可執(zhí)行的安裝程序歌溉。這些二進(jìn)制文件的所有可選庫包括除了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:
我們提供二進(jìn)制文件為每個(gè)支持的macOS車輪格式的Python版本垄懂。這包括支持所有可選庫libimagequant除外。Raqm支持需要libraqm、fribidi harfbuzz單獨(dú)安裝:
$ 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:
我們?yōu)長(zhǎng)inux提供二進(jìn)制文件為每個(gè)支持的Python版本manylinux輪格式埠偿。這包括支持所有可選庫libimagequant除外。Raqm支持需要libraqm榜晦、fribidi harfbuzz單獨(dú)安裝:
$ 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.
大多數(shù)Linux發(fā)行版默認(rèn)包含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庫可以通過官方的渠道或包系統(tǒng)安裝在FreeBSD系統(tǒng):
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港口和包由端口測(cè)試團(tuán)隊(duì)與所有支持FreeBSD和Python 2.7版本和3.x版本。
Building From Source(從源代碼構(gòu)建)
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默認(rèn)是必需的。
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.
腳本安裝的依賴關(guān)系有一些操作系統(tǒng)包含在看目錄识窿。也在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:
一旦你安裝了先決條件,運(yùn)行:
$ 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:
如果前提是安裝在機(jī)器的標(biāo)準(zhǔn)庫的位置(例如,/ usr或/usr/local),不需要額外的配置。如果他們是安裝在標(biāo)準(zhǔn)位置,您可能需要配置使用setuptools這些位置通過編輯設(shè)置喻频。py或設(shè)置缩宜。cfg或在命令行上添加環(huán)境變量:
$ 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.
如果枕頭之前構(gòu)建沒有所需的先決條件,可能需要手動(dòng)清除pip緩存或構(gòu)建緩存使用——no-cache-dir選項(xiàng)強(qiáng)制建立和新安裝的外部庫。
- Build Options(構(gòu)建選項(xiàng))
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命令行工具需要編譯的部分枕頭甥温。安裝的工具運(yùn)行xcode-select——從命令行安裝锻煌。命令行工具是必需的,即使你有完整的Xcode包安裝∫鲵荆可能需要運(yùn)行sudo xcodebuild許可證之前接受許可使用的工具宋梧。
The easiest way to install external libraries is via Homebrew. After you install Homebrew, run:
安裝外部庫最簡(jiǎn)單的方法是通過自制程序。你安裝自制程序后,運(yùn)行:
$ brew install libtiff libjpeg webp little-cms2
To install libraqm on macOS use Homebrew to install its dependencies:
安裝libraqm macOS使用自制程序來安裝它的依賴關(guān)系:
$ 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:
現(xiàn)在安裝枕頭:
$ 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。彎彎曲曲的通道是一個(gè)迷宮,大多是死胡同加叁。有構(gòu)建腳本和筆記的Windows建立winbuild目錄倦沧。
Building on FreeBSD
Only FreeBSD 10 and 11 tested
只有FreeBSD 10和11測(cè)試過
Make sure you have Python’s development libraries installed.:
確保您已經(jīng)安裝了Python的開發(fā)庫。
$ 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.
如果你沒有從源代碼構(gòu)建Python,確保您已經(jīng)安裝了Python的開發(fā)庫。
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.
參見測(cè)試基礎(chǔ)設(shè)施中的Dockerfiles回購(gòu)(https://github.com/python-pillow/docker-images)一個(gè)已知的工作為其他測(cè)試發(fā)行版安裝過程。
Building on Android
Basic Android support has been added for compilation within the Termux environment. The dependencies can be installed by:
基本的Android支持Termux中已經(jīng)添加了編譯環(huán)境轮傍≡荼ⅲ可以安裝的依賴關(guān)系:
$ pkg -y install python python-dev ndk-sysroot clang make \
libjpeg-turbo-dev
這是測(cè)試在Termux應(yīng)用ChromeOS,在x86上。
Platform Support(平臺(tái)支持)
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.
當(dāng)前平臺(tái)支持庫Pillow创夜。二進(jìn)制發(fā)行版提供志愿者的基礎(chǔ)上為每一個(gè)版本,但源應(yīng)該編譯和運(yùn)行平臺(tái)支持上市杭跪。一般來說,我們的目標(biāo)是支持所有當(dāng)前版本的Linux, macOS和Windows。
- Continuous Integration Targets(持續(xù)集成的目標(biāo))
These platforms are built and tested for every change.
這些平臺(tái)構(gòu)建和測(cè)試每一個(gè)變化。
Mac OS X CI is not run for every commit, but is run for every release.
Mac OS X CI不是運(yùn)行每一個(gè)提交,但每個(gè)發(fā)布版本都可運(yùn)行涧尿。
Other Platforms
These platforms have been reported to work at the versions mentioned.
這些平臺(tái)在提到的版本已報(bào)告工作系奉。
Contributors please test Pillow on your platform then update this document and send a pull request.
投稿者請(qǐng)測(cè)試枕在你的平臺(tái)上然后更新這個(gè)文檔和發(fā)送一個(gè)請(qǐng)求。
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/缺亮。