Pillow¶
Pillow 是由 Alex Clark等人 从 PIL 建立的一个分支(fork)。PIL 是由 Fredrik 等人建立的 Python Imaging Library。
安装¶
警告¶
警告
Pillow 和 PIL不能共存。在安装 Pillow 之前,请先卸载 PIL。
警告
Pillow >= 1.0不再支持 “import Image”。请用”from PIL import Image”代替。
警告
Pillow >= 2.1.0 不再支持”import _imaging”。请用”from PIL.Image import core as _imaging”代替。
注解¶
注解
以下 Python 版本支持 Pillow
Python | 2.4 | 2.5 | 2.6 | 2.7 | 3.2 | 3.3 | 3.4 | 3.5 | 3.6 | 3.7 |
Pillow < 2.0.0 | Yes | Yes | Yes | Yes | ||||||
Pillow 2.x - 3.x | Yes | Yes | Yes | Yes | Yes | Yes | ||||
Pillow 4.x | Yes | Yes | Yes | Yes | Yes | |||||
Pillow 5.0.x - 5.1.x | Yes | Yes | Yes | Yes | ||||||
Pillow 5.2.x - 5.4.x | Yes | Yes | Yes | Yes | Yes | |||||
Pillow 6.x | Yes | Yes | Yes | Yes | ||||||
Pillow >= 7.0.0 | Yes | Yes | Yes |
基本安装¶
注解
以下指导将会安装支持大多数常见图像格式的 Pillow 库,请参阅 外部库 以获取支持的外部库的完整列表。
使用 pip 安装 Pillow:
$ pip install Pillow
在Windows下安装¶
对于 Windows,我们提供了wheel,egg,exe类型的 Pillow 二进制文件,这些二进制文件针对受支持的 Python 编译了32位和64位版本。除了 raqm 和 libimagequant,这些二进制文件包含了所有的可选库:
> pip install Pillow
在mac操作系统下安装¶
对于 mac 操作系统,我们提供了受支持的 Python 的 wheel 格式的二进制文件。除了 libimagequant,这些二进制文件包含所有可选库。要获得 Raqm 支持,必须单独安装 libraqm,fribidi 和 harfbuzz:
$ pip install Pillow
在Linux上安装¶
对于 Linux,我们针对每个受支持的 Python 提供了 manylinux wheel 格式的二进制文件。除了 libimagequant,这些二进制文件包含所有可选库。要获得 Raqm 支持,必须单独安装 libraqm,fribidi 和 harfbuzz:
$ pip install Pillow
大多数主要的 Linux 发行版,包括 Fedora,Debian / Ubuntu 和 ArchLinux,在之前包含 PIL 的包中也包含 Pillow。比如 python-imaging
。
在FreeBSD上安装¶
在 FreeBSD 上,可以通过官方的 Ports 或者 Packages 系统安装 Pillow。
Ports:
$ cd /usr/ports/graphics/py-pillow && make install clean
Packages:
$ pkg install py27-pillow
注解
Pillow FreeBSD port 和所有的包已由 ports 团队针对所有受支持的 FreeBSD 版本和 Python 2.7 和 3.x 进行了测试。
从源代码编译¶
下载并提取 compressed archive from PyPI.
外部库¶
注解
为了使用 Pillow 的基本功能,你 不需要 安装所有受支持的外部。默认情况下需要 Zlib 和 libjpeg。
平台支持¶
旧版本¶
你可以从 PyPI发行历史 下载旧的发行版,或者直接通过 URL 链接,比如 https://pypi.org/project/Pillow/1.0/。
手册¶
概览¶
Python Imaging Library 为你的 Python 解释器增加了图像处理功能。
该库提供了广泛的文件格式支持,有效的内部表示以及相当强大的图像处理功能。
核心图像库旨在快速访问以几种基本像素格式存储的数据。 它应该为通用图像处理工具提供坚实的基础。
让我们看一下该库的一些可能使用方法。
图像存档¶
Python Imaging Library是图像存档和批处理应用的理想选择。你可以使用该库创建缩略图,转换文件格式,打印图像等。
当前版本的库可以识别和读取多种格式类型的文件。有意将写操作限制于最常用的交换和表示格式。
图像展示¶
当前的发现版包括TK PhotoImage
和 BitmapImage
接口,以及在 PythonWin 和其他基于 Windows 的工具下可以使用的 Windows DIB interface
。
为了进行调试,show()
方法将图像存储到磁盘,并调用外部显示程序。
图像处理¶
该库包含基本的图像处理功能,包括点操作,使用一组内置的卷积核进行滤波,以及颜色空间转换。
该库也支持图像缩放,旋转和任意的仿射变换。
直方图方法可以让你从图像中提取一些统计信息。这可用于自动对比度增强和全局统计分析。
教程¶
使用Image类¶
Python Imaging Library中最重要的类是 Image
,该类定义在同名的模块中。你可以通过多种方式创建该类的实例;通过从文件加载图像,处理其他图像,或者从头创建图像。
为了从文件加载图像,使用 Image
模块中的 open()
函数:
>>> from PIL import Image
>>> im = Image.open("hopper.ppm")
如果成功,这个函数返回一个 Image
对象。你现在可以使用属性实例检查文件内容:
>>> from __future__ import print_function
>>> print(im.format, im.size, im.mode)
PPM (512, 512) RGB
format
属性识别图像的来源。如果图像不是从文件中读取,该属性被设置为 None。size
属性是一个包含宽度和高度(以像素为单位)的元组。mode
属性定义图像中频段的数量和名称,以及像素类型和深度。常见模式: 灰度图的模式为 “L”,真彩色图的模式为 “RGB”,预打印图的模式为 “CMYK”。
若文件打不开,则引发 IOError
异常。
一旦有了一个 Image
类的实例,就可以使用该类定义的方法来处理和操作图像。例如,展示刚加载的图像:
>>> im.show()
注解
标准版本的 show()
效率不高,因为它将图像保存到临时文件并调用实用程序来显示图像。如果你没有安装适当的实用程序,它甚至将无法工作。然而当它能工作时,它对于调试和测试非常方便。
以下各节概述了此库中提供的各种功能。
读写图像¶
Python Imaging Library支持多种图像文件格式。要从磁盘中读取文件,请使用 Image
模块中的 open()
函数。无需知道文件的格式即可打开文件。该库根据文件的内容自动确定格式。
要保存文件,请使用 Image
模块中的 save()
函数。保存文件时,名称变得很重要。除非指定格式,否则库将使用文件扩展名来决定要使用哪种文件存储格式。
将文件转换为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"
if infile != outfile:
try:
Image.open(infile).save(outfile)
except IOError:
print("cannot convert", infile)
可以给 save()
方法提供第二个参数,以显式指定文件格式。如果使用非标准扩展名,则必须始终以这种方式指定格式:
创建JPEG缩略图¶
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)
值得注意的一点是,除非确实需要,否则库不会解码或加载光栅数据。当打开一个文件时,将读取文件头以确定文件格式,并提取诸如模式、大小以及其他对解码文件所需的属性之类的信息,但是文件的剩余内容随后才会处理。
这意味着打开图像文件是一个快速操作,与文件大小和压缩类型无关。下面是一个简单的脚本,用以快速识别一组图像文件:
识别图像文件¶
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
剪切、粘贴和融合图像¶
Image
类包含一些方法,这些方法让你可以操纵图像中的区域。 要从图像中提取子矩形,请使用 crop()
方法。
从图像中复制子矩形¶
box = (100, 100, 400, 400)
region = im.crop(box)
区域由一个四元组定义,坐标为(左,上,右,下)。Python Imaging Library使用的坐标系的左上角为 (0,0)。另外请注意,坐标指的是像素之间的位置,因此上面的例子中的区域恰好是 300x300 像素。
现在可以用某种方式处理该区域并将其粘贴回去。
处理子矩形,并将其粘贴回去¶
region = region.transpose(Image.ROTATE_180)
im.paste(region, box)
当将区域粘贴回去的时候,区域的大小必须与给定区域完全匹配。另外,该区域不能延伸到图像之外。然而,原始图像和区域的模式不需要匹配。如果不匹配,在粘贴之前区域会被自动转换。(详细信息,请参考 颜色变换 )
下面是另一个例子:
滚动图像¶
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(part1, (xsize-delta, 0, xsize, ysize))
image.paste(part2, (0, 0, xsize-delta, ysize))
return image
对于更高级的技巧, paste()
方法可以将透明掩码作为可选参数。在此掩码中,255 表示粘贴的图像在该位置是不透明的(也就是说,粘贴的图像应按原样使用)。0 表示粘贴的图像是完全透明的。0-255 之间的值表示不同级别的透明度。例如,粘贴一个 RGBA 图像并将其用作掩码,将会粘贴图像的不透明部分,但不粘贴其透明背景。
Python Imaging Library还允许你使用多频段图像(例如RGB图像)的各个频段。 split()
方法将创建一组新图像,每个图像包含原始多频段图像中的一个频段。 merge()
函数采用一种模式,将一组图像组合成一个新图像。下面的例子交换了 RGB 图像的三个频段:
几何变换¶
PIL.Image.Image
类包含重新调整图像大小的 resize()
方法和旋转图像的 rotate()
方法。前者参数为指定新尺寸的元组,后者参数为逆时针旋转的角度。
简单的几何变换¶
out = im.resize((128, 128))
out = im.rotate(45) # degrees counter-clockwise
要以 90 度为单位旋转图像,可以使用 rotate()
方法或者 transpose()
方法。后者还可用于围绕图像的水平或垂直轴翻转图像。
转置图像¶
out = im.transpose(Image.FLIP_LEFT_RIGHT)
out = im.transpose(Image.FLIP_TOP_BOTTOM)
out = im.transpose(Image.ROTATE_90)
out = im.transpose(Image.ROTATE_180)
out = im.transpose(Image.ROTATE_270)
也可以用 rotate()
来实现与 transpose(ROTATE)
相同的操作,expand
标志设置为True,用于提供对图像大小的相同的修改。
通过 transform()
方法执行更加通用形式的图像变换。
颜色变换¶
Python Imaging Library允许你使用 convert()
方法在不同像素表示之间转换图像。
模式之间的转换¶
from PIL import Image
im = Image.open("hopper.ppm").convert("L")
该库支持每种受支持的模式与 “L” 和 “RGB” 模式之间的转换。要在其他模式之间转换,必须使用中间图像(通常是 “RGB” 模式图像)。
图像增强¶
Python Imaging Library提供了许多可用于增强图像的方法和模块。
滤波器¶
ImageFilter
模块包含许多可以与 filter()
方法一起使用的预定义增强滤波器。
应用滤波器¶
from PIL import ImageFilter
out = im.filter(ImageFilter.DETAIL)
点操作¶
point()
方法可用于转换图像的像素值(例如,图像对比度操纵)。大多数情况下,需要一个参数的函数对象可以传递给该方法。根据该函数处理每个像素:
应用点变换¶
# multiply each pixel by 1.2
out = im.point(lambda i: i * 1.2)
使用上述技术,你可以快速将任何简单表达式应用于图像。你还可以结合 point()
和 paste()
方法来选择性地修改图像:
处理各个频段¶
# 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)
注意创建掩码的语法:
imout = im.point(lambda i: expression and 255)
Python根据确定结果的必要,仅评估逻辑表达式的部分,并返回最后检查的值作为表达式的结果。因此,如果上面的表达式为 false(0),Python 不会查看第二个操作数,因此返回 0。否则返回 255。
增强¶
要进行更高级的图像增强,可以使用 ImageEnhance
中的类。一旦从图像中创建,可以使用增强对象快速尝试不同的设置。
你可以通过这种方式调整对比度,亮度,色彩平衡和清晰度。
增强图像¶
from PIL import ImageEnhance
enh = ImageEnhance.Contrast(im)
enh.enhance(1.3).show("30% more contrast")
图像序列¶
Python Imaging Library包含对图像序列(也称为动画格式)的一些基本支持。支持的格式包含 FLI/FLC,GIF和一些实验性格式。TIFF 文件也可以包含多帧。
当打开序列文件时,PIL 自动加载序列的第一帧。你可以使用 seek()
和 tell()
方法在不同帧之间移动:
读取序列¶
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
如本例所示,当序列结束时,你将受到 EOFError
异常。
下面的类可以让你使用 for 语句遍历序列:
使用ImageSequence Iterator类¶
from PIL import ImageSequence
for frame in ImageSequence.Iterator(im):
# ...do something to frame...
Postscript 打印¶
Python Imaging Library包含用于在 Postscript 打印机上打印图像,文本和图形的函数。下面是一个简单示例:
绘制Postscript¶
from PIL import Image
from PIL import PSDraw
im = Image.open("hopper.ppm")
title = "hopper"
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 title
ps.setfont("HelveticaNarrow-Bold", 36)
ps.text((3*72, 4*72), title)
ps.end_document()
更多关于读取图像¶
如前所述, Image
模块中的 open()
函数用于打开图像文件。大多数情况下,只需将文件名作为参数传递给它::
from PIL import Image
im = Image.open("hopper.ppm")
如果一切顺利,结果是一个 PIL.Image.Image
对象。否则引发 IOError
异常。
你可以使用类似文件的对象代替文件名。该对象必须实现 read()
, seek()
和 tell()
方法,并以二进制模式打开。
从打开的文件中读取¶
from PIL import Image
with open("hopper.ppm", "rb") as fp:
im = Image.open(fp)
要想从字符串数据中读取图像,使用 StringIO
类:
从字符串中读取¶
from PIL import Image
import StringIO
im = Image.open(StringIO.StringIO(buffer))
注意,在读取图像头之前,库会倒退文件(使用 seek(0)
)。另外,在读取图像数据时,也可以使用 seek。如果图像文件嵌在较大的文件中(比如 tar 文件),你可以使用 ContainerIO
或者 TarIO
模块来访问它。
从tar文档中读取¶
from PIL import Image, TarIO
fp = TarIO.TarIO("Tests/images/hopper.tar", "hopper.jpg")
im = Image.open(fp)
控制解码器¶
一些解码器允许你在从文件中读取图像时对其进行操作。在创建缩略图(通常速度比质量重要)和打印到单色激光打印机(仅需要灰度版本的图像)时, 通常可以使用它来加速解码。
draft()
方法处理已经打开但尚未加载的图像,因此它尽可能匹配给定的模式和大小。这是通过重新配置图像解码器来完成的。
以 draft 模式读取¶
仅适用于 JPEG 和 MPO 文件。
from PIL import Image
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)
打印信息如下:
original = RGB (512, 512)
draft = L (128, 128)
注意,生成的图像可能与要求的模式和尺寸不完全匹配。为确保图像不大于给定的大小,请使用 thumbnail()
方法。
概念¶
Python Imaging Library处理 光栅 图像,也就是矩形像素数据。
频段¶
图像可以包含一个或多个频段的数据。 Python Imaging Library可让你在单个图像中存储多个频段,只要它们都具有相同的维度和深度。例如,对于红色,绿色,蓝色和 alpha 透明度值,PNG图像可能具有 ‘R’,‘G’,‘B’,‘A’ 频段。许多操作分别作用于每个频段,例如直方图。通常认为每个像素对于每个频段具有一个值。
要获取图像中频段的数量和名称,请使用 getbands()
方法。
模式¶
图像的 mode
定义了图像中像素的类型和深度。每个像素使用整个位深度范围。因此,1 位的像素的范围是 0-1,8 位像素的范围是 0-255,以此类推。当前版本支持以下标准模式:
1
(1-bit 像素, 黑和白, 一个像素占用一个byte)L
(8-bit 像素, 黑和白)P
(8-bit 像素, 使用调色板映射到任何其他模式)RGB
(3x8-bit 像素, 真彩色)RGBA
(4x8-bit 像素, 带透明度掩码的真彩色)CMYK
(4x8-bit 像素, 分色)YCbCr
(3x8-bit 像素, 颜色视频格式)
- 注意,这里指的是JPEG,不是ITU-R BT.2020标准
LAB
(3x8-bit 像素, L*a*b 颜色空间)HSV
(3x8-bit 像素, 色相,饱和度,明度颜色空间)I
(32-bit 有符号整数像素)F
(32-bit 浮点像素)
Pillow 还为一些特殊模式提供有限的支持,包括:
LA
(L with alpha)PA
(P with alpha)RGBX
(true color with padding)RGBa
(true color with premultiplied alpha)La
(L with premultiplied alpha)I;16
(16-bit unsigned integer pixels)I;16L
(16-bit little endian unsigned integer pixels)I;16B
(16-bit big endian unsigned integer pixels)I;16N
(16-bit native endian unsigned integer pixels)BGR;15
(15-bit reversed true colour)BGR;16
(16-bit reversed true colour)BGR;24
(24-bit reversed true colour)BGR;32
(32-bit reversed true colour)
然而,Pillow 不支持用户定义的模式;如果你需要处理上面未列出的频段的组合,请使用 Image 对象序列。
你可以通过 mode
属性读取图像的模式。这是一个包含以上值之一的字符串。
尺寸¶
你可以通过 size
属性读取图像尺寸。这是一个2元组,包含以像素为单位的水平和垂直尺寸。
坐标系统¶
Python Imaging Library使用笛卡尔像素坐标系,左上角为(0,0)。注意,坐标是指像素角;地址为(0,0)的像素中心实际上位于(0.5,0.5)。
坐标通常以2元组(x,y)的形式传递给库。矩形用4元组表示,左上角在前。例如,将覆盖 800x600 像素图像的矩形写作(0,0,800,600)。
调色板¶
调色板模式(P
)使用调色板定义每个像素的实际颜色。
信息¶
你可以使用 info
属性将辅助信息附加到图像。它是一个字典对象。
加载和保存图像文件时,如何处理这类信息取决于文件格式处理程序(请参考 Image file formats)。大多数处理程序在加载图像时将属性添加到 info
属性,但在保存图像时将其忽略。
滤波器¶
对于可能将多个输入像素映射到单个输出像素的几何运算,Python Imaging Library提供了不同的重采样 滤波器 。
NEAREST
从输入图像中选择最近的像素,忽略所有其他输入像素。
BOX
源图像的每个像素以相同的权重贡献到目标图像的一个像素。For upscaling is equivalent of
NEAREST
。该滤波器只能与resize()
和thumbnail()
方法使用。3.4.0 新版功能.
BILINEAR
若要调整大小,对所有可能影响输出值的像素使用线性插值计算输出像素的值。对于其他变换,在输入图像中2x2邻域上进行线性插值。
HAMMING
生成比
BILEAR
更清晰的图像,并且在局部不会有像BOX
那样的错位。该滤波器只能与resize()
和thumbnail()
方法使用。3.4.0 新版功能.
BICUBIC
若要调整大小,对所有可能影响输出值的像素使用三次插值计算输出像素的值。对于其他变换,在输入图像中4x4邻域上进行三次插值。
LANCZOS
对所有可能影响输出值的像素使用高质量的 Lanczos 滤波器计算输出像素的值。该滤波器只能与
resize()
和thumbnail()
方法使用。1.1.3 新版功能.
滤波器对比表¶
Filter | Downscaling quality | Upscaling quality | Performance |
---|---|---|---|
NEAREST |
√√√√√ | ||
BOX |
√ | √√√√ | |
BILINEAR |
√ | √ | √√√ |
HAMMING |
√√ | √√√ | |
BICUBIC |
√√√ | √√√ | √√ |
LANCZOS |
√√√√ | √√√√ | √ |
附录¶
注解
贡献者在修改 bug,增加特性或是测试时,请根据需要或适当地包含附录。
Image file formats¶
The Python Imaging Library supports a wide variety of raster file formats. Over 30 different file formats can be identified and read by the library. Write support is less extensive, but most common interchange and presentation formats are supported.
The open()
function identifies files from their
contents, not their names, but the save()
method
looks at the name to determine which format to use, unless the format is given
explicitly.
Fully supported formats¶
目录
BMP¶
Pillow reads and writes Windows and OS/2 BMP files containing 1
, L
, P
,
or RGB
data. 16-colour images are read as P
images. Run-length encoding
is not supported.
The open()
method sets the following
info
properties:
- compression
- Set to
bmp_rle
if the file is run-length encoded.
DIB¶
Pillow reads and writes DIB files. DIB files are similar to BMP files, so see above for more information.
6.0.0 新版功能.
EPS¶
Pillow identifies EPS files containing image data, and can read files that
contain embedded raster images (ImageData descriptors). If Ghostscript is
available, other EPS files can be read as well. The EPS driver can also write
EPS images. The EPS driver can read EPS images in L
, LAB
, RGB
and
CMYK
mode, but Ghostscript may convert the images to RGB
mode rather
than leaving them in the original color space. The EPS driver can write images
in L
, RGB
and CMYK
modes.
If Ghostscript is available, you can call the load()
method with the following parameter to affect how Ghostscript renders the EPS
- scale
Affects the scale of the resultant rasterized image. If the EPS suggests that the image be rendered at 100px x 100px, setting this parameter to 2 will make the Ghostscript render a 200px x 200px image instead. The relative position of the bounding box is maintained:
im = Image.open(...) im.size #(100,100) im.load(scale=2) im.size #(200,200)
GIF¶
Pillow reads GIF87a and GIF89a versions of the GIF file format. The library writes run-length encoded files in GIF87a by default, unless GIF89a features are used or GIF89a is already in use.
Note that GIF files are always read as grayscale (L
)
or palette mode (P
) images.
The open()
method sets the following
info
properties:
- background
- Default background color (a palette color index).
- transparency
- Transparency color index. This key is omitted if the image is not transparent.
- version
- Version (either
GIF87a
orGIF89a
). - duration
- May not be present. The time to display the current frame of the GIF, in milliseconds.
- loop
- May not be present. The number of times the GIF should loop. 0 means that it will loop forever.
- comment
- May not be present. A comment about the image.
- extension
- May not be present. Contains application specific information.
The GIF loader supports the seek()
and
tell()
methods. You can combine these methods
to seek to the next frame (im.seek(im.tell() + 1)
).
im.seek()
raises an EOFError
if you try to seek after the last frame.
When calling save()
, the following options
are available:
im.save(out, save_all=True, append_images=[im1, im2, ...])
- save_all
- If present and true, all frames of the image will be saved. If not, then only the first frame of a multiframe image will be saved.
- append_images
A list of images to append as additional frames. Each of the images in the list can be single or multiframe images. This is currently supported for GIF, PDF, TIFF, and WebP.
It is also supported for ICNS. If images are passed in of relevant sizes, they will be used instead of scaling down the main image.
- include_color_table
- Whether or not to include local color table.
- interlace
- Whether or not the image is interlaced. By default, it is, unless the image is less than 16 pixels in width or height.
- disposal
Indicates the way in which the graphic is to be treated after being displayed.
- 0 - No disposal specified.
- 1 - Do not dispose.
- 2 - Restore to background color.
- 3 - Restore to previous content.
Pass a single integer for a constant disposal, or a list or tuple to set the disposal for each frame separately.- palette
- Use the specified palette for the saved image. The palette should
be a bytes or bytearray object containing the palette entries in
RGBRGB… form. It should be no more than 768 bytes. Alternately,
the palette can be passed in as an
PIL.ImagePalette.ImagePalette
object. - optimize
- If present and true, attempt to compress the palette by eliminating unused colors. This is only useful if the palette can be compressed to the next smaller power of 2 elements.
Note that if the image you are saving comes from an existing GIF, it may have
the following properties in its info
dictionary.
For these options, if you do not pass them in, they will default to
their info
values.
- transparency
- Transparency color index.
- duration
- The display duration of each frame of the multiframe gif, in milliseconds. Pass a single integer for a constant duration, or a list or tuple to set the duration for each frame separately.
- loop
- Integer number of times the GIF should loop. 0 means that it will loop forever. By default, the image will not loop.
- comment
- A comment about the image.
The GIF loader creates an image memory the same size as the GIF file’s logical
screen size, and pastes the actual pixel data (the local image) into this
image. If you only want the actual pixel rectangle, you can manipulate the
size
and tile
attributes before loading the file:
im = Image.open(...)
if im.tile[0][0] == "gif":
# only read the first "local image" from this GIF file
tag, (x0, y0, x1, y1), offset, extra = im.tile[0]
im.size = (x1 - x0, y1 - y0)
im.tile = [(tag, (0, 0) + im.size, offset, extra)]
ICNS¶
Pillow reads and (macOS only) writes macOS .icns
files. By default, the
largest available icon is read, though you can override this by setting the
size
property before calling
load()
. The open()
method
sets the following info
property:
- sizes
- A list of supported sizes found in this icon file; these are a
3-tuple,
(width, height, scale)
, wherescale
is 2 for a retina icon and 1 for a standard icon. You are permitted to use this 3-tuple format for thesize
property if you set it before callingload()
; 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 ofsize
will be(1024, 1024)
).
The save()
method can take the following keyword arguments:
- append_images
A list of images to replace the scaled down versions of the image. The order of the images does not matter, as their use is determined by the size of each image.
5.1.0 新版功能.
ICO¶
ICO is used to store icons on Windows. The largest available icon is read.
The save()
method supports the following options:
- sizes
- A list of sizes including in this ico file; these are a 2-tuple,
(width, height)
; Default to[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)]
. Any sizes bigger than the original size or 256 will be ignored.
IM¶
IM is a format used by LabEye and other applications based on the IFUNC image processing library. The library reads and writes most uncompressed interchange versions of this format.
IM is the only format that can store all internal Pillow formats.
JPEG¶
Pillow reads JPEG, JFIF, and Adobe JPEG files containing L
, RGB
, or
CMYK
data. It writes standard and progressive JFIF files.
Using the draft()
method, you can speed things up by
converting RGB
images to L
, and resize images to 1/2, 1/4 or 1/8 of
their original size while loading them.
The open()
method may set the following
info
properties if available:
- jfif
- JFIF application marker found. If the file is not a JFIF file, this key is not present.
- jfif_version
- A tuple representing the jfif version, (major version, minor version).
- jfif_density
- A tuple representing the pixel density of the image, in units specified by jfif_unit.
- jfif_unit
Units for the jfif_density:
- 0 - No Units
- 1 - Pixels per Inch
- 2 - Pixels per Centimeter
- dpi
- A tuple representing the reported pixel density in pixels per inch, if the file is a jfif file and the units are in inches.
- adobe
- Adobe application marker found. If the file is not an Adobe JPEG file, this key is not present.
- adobe_transform
- Vendor Specific Tag.
- progression
- Indicates that this is a progressive JPEG file.
- 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 and true, indicates that the encoder should make an extra pass over the image in order to select optimal encoder settings.
- progressive
- If present and true, 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 and true, 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:2:0
: Specific sampling values-1
: equivalent tokeep
0
: equivalent to4:4:4
1
: equivalent to4:2:2
2
: equivalent to4:2:0
- qtables
If present, sets the qtables for the encoder. This is listed as an advanced option for wizards in the JPEG documentation. Use with caution.
qtables
can be one of several types of values:- a string, naming a preset, e.g.
keep
,web_low
, orweb_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.
2.5.0 新版功能.
- a string, naming a preset, e.g.
注解
To enable JPEG support, you need to build and install the IJG JPEG library before building the Python Imaging Library. See the distribution README for details.
JPEG 2000¶
2.4.0 新版功能.
Pillow 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. Pillow supports JPEG 2000 raw codestreams (.j2k
files),
as well as boxed JPEG 2000 files (.j2p
or .jpx
files). Pillow does
not support files whose components have different sampling frequencies.
When loading, if you set the mode
on the image prior to the
load()
method being invoked, you can ask Pillow to
convert the image to either RGB
or RGBA
rather than choosing for
itself. It is also possible to set reduce
to the number of resolutions to
discard (each one reduces the size of the resulting image by a factor of 2),
and layers
to specify the number of quality layers to load.
The save()
method supports the following options:
- offset
- The image offset, as a tuple of integers, e.g. (16, 16)
- tile_offset
- The tile offset, again as a 2-tuple of integers.
- tile_size
- The tile size as a 2-tuple. If not specified, or if set to None, the image will be saved without tiling.
- quality_mode
- Either
"rates"
or"dB"
depending on the units you want to use to specify image quality. - quality_layers
- A sequence of numbers, each of which represents either an approximate size
reduction (if quality mode is
"rates"
) or a signal to noise ratio value in decibels. If not specified, defaults to a single layer of full quality. - num_resolutions
- The number of different image resolutions to be stored (which corresponds to the number of 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 toFalse
, 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.
注解
To enable JPEG 2000 support, you need to build and install the OpenJPEG library, version 2.0.0 or higher, before building the Python Imaging Library.
Windows users can install the OpenJPEG binaries available on the
OpenJPEG website, but must add them to their PATH in order to use Pillow (if
you fail to do this, you will get errors about not being able to load the
_imaging
DLL).
MSP¶
Pillow identifies and reads MSP files from Windows 1 and 2. The library writes uncompressed (Windows 1) versions of this format.
PNG¶
Pillow identifies, reads, and writes PNG files containing 1
, L
, LA
,
I
, P
, RGB
or RGBA
data. Interlaced files are supported as of
v1.1.7.
As of Pillow 6.0, EXIF data can be read from PNG images. However, unlike other
image formats, EXIF data is not guaranteed to be present in
info
until load()
has been
called.
The open()
method sets the following
info
properties, when appropriate:
- chromaticity
- The chromaticity points, as an 8 tuple of floats. (
White Point X
,White Point Y
,Red X
,Red Y
,Green X
,Green Y
,Blue X
,Blue Y
) - gamma
- Gamma, given as a floating point number.
- srgb
The sRGB rendering intent as an integer.
- 0 Perceptual
- 1 Relative Colorimetric
- 2 Saturation
- 3 Absolute Colorimetric
- transparency
For
P
images: Either the palette index for full transparent pixels, or a byte string with alpha values for each palette entry.For
1
,L
,I
andRGB
images, the color that represents full transparent pixels in this image.This key is omitted if the image is not a transparent palette image.
open
also sets Image.text
to a dictionary of the values of the
tEXt
, zTXt
, and iTXt
chunks of the PNG image. Individual
compressed chunks are limited to a decompressed size of
PngImagePlugin.MAX_TEXT_CHUNK
, by default 1MB, to prevent
decompression bombs. Additionally, the total size of all of the text
chunks is limited to PngImagePlugin.MAX_TEXT_MEMORY
, defaulting to
64MB.
The save()
method supports the following options:
- optimize
- If present and true, instructs the PNG writer to make the output file as small as possible. This includes extra processing in order to find optimal encoder settings.
- transparency
For
P
,1
,L
,I
, andRGB
images, this option controls what color from the image to mark as transparent.For
P
images, this can be a either the palette index, or a byte string with alpha values for each palette entry.- dpi
- A tuple of two numbers corresponding to the desired dpi in each direction.
- pnginfo
- A
PIL.PngImagePlugin.PngInfo
instance containing text tags. - compress_level
- ZLIB compression level, a number between 0 and 9: 1 gives best speed,
9 gives best compression, 0 gives no compression at all. Default is 6.
When
optimize
option is Truecompress_level
has no effect (it is set to 9 regardless of a value passed). - icc_profile
- The ICC Profile to include in the saved file.
- exif
The exif data to include in the saved file.
6.0.0 新版功能.
- 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.
注解
To enable PNG support, you need to build and install the ZLIB compression library before building the Python Imaging Library. See the installation documentation for details.
SPIDER¶
Pillow reads and writes SPIDER image files of 32-bit floating point data (“F;32F”).
Pillow also reads SPIDER stack files containing sequences of SPIDER images. The
seek()
and tell()
methods are supported, and
random access is allowed.
The open()
method sets the following attributes:
- format
- Set to
SPIDER
- istack
- Set to 1 if the file is an image stack, else 0.
- n_frames
- 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()
The extension of SPIDER files may be any 3 alphanumeric characters. Therefore the output format must be specified explicitly:
im.save('newimage.spi', format='SPIDER')
For more information about the SPIDER image processing package, see the SPIDER homepage at Wadsworth Center.
TGA¶
Pillow reads and writes TGA images containing L
, LA
, P
,
RGB
, and RGBA
data. Pillow can read and write both uncompressed and
run-length encoded TGAs.
TIFF¶
Pillow reads and writes TIFF files. It can read both striped and tiled images, pixel and plane interleaved multi-band images. If you have libtiff and its headers installed, Pillow can read and write many kinds of compressed TIFF files. If not, Pillow will only read and write uncompressed files.
注解
Beginning in version 5.0.0, Pillow requires libtiff to read or write compressed files. Prior to that release, Pillow had buggy support for reading Packbits, LZW and JPEG compressed TIFFs without using libtiff.
The open()
method sets the following
info
properties:
- compression
Compression mode.
2.0.0 新版功能.
- dpi
Image resolution as an
(xdpi, ydpi)
tuple, where applicable. You can use thetag
attribute to get more detailed information about the image resolution.1.1.5 新版功能.
- resolution
Image resolution as an
(xres, yres)
tuple, where applicable. This is a measurement in whichever unit is specified by the file.1.1.5 新版功能.
The tag_v2
attribute contains a dictionary
of TIFF metadata. The keys are numerical indexes from
TAGS_V2
. Values are strings or numbers for single
items, multiple values are returned in a tuple of values. Rational
numbers are returned as a IFDRational
object.
3.0.0 新版功能.
For compatibility with legacy code, the
tag
attribute contains a dictionary of
decoded TIFF fields as returned prior to version 3.0.0. Values are
returned as either strings or tuples of numeric values. Rational
numbers are returned as a tuple of (numerator, denominator)
.
3.0.0 版后已移除.
The TIFF loader supports the seek()
and
tell()
methods, taking and returning frame numbers
within the image file. You can combine these methods to seek to the next frame
(im.seek(im.tell() + 1)
). Frames are numbered from 0 to im.num_frames - 1
,
and can be accessed in any order.
im.seek()
raises an EOFError
if you try to seek after the
last frame.
The save()
method can take the following keyword arguments:
- save_all
If true, Pillow will save all frames of the image to a multiframe tiff document.
3.4.0 新版功能.
- append_images
A list of images to append as additional frames. Each of the images in the list can be single or multiframe images. Note however, that for correct results, all the appended images should have the same
encoderinfo
andencoderconfig
properties.4.2.0 新版功能.
- tiffinfo
A
ImageFileDirectory_v2
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 anImageFileDirectory_v2
object and setting the type intagtype
with the appropriate numerical value fromTiffTags.TYPES
.2.3.0 新版功能.
Metadata values that are of the rational type should be passed in using a
IFDRational
object.3.1.0 新版功能.
For compatibility with legacy code, a
ImageFileDirectory_v1
object may be passed in this field. However, this is deprecated.5.4.0 新版功能.
Previous versions only supported some tags when writing using libtiff. The supported list is found in
LIBTIFF_CORE
.6.1.0 新版功能.
Added support for signed types (e.g.
TIFF_SIGNED_LONG
) and multiple values. Multiple values for a single tag must be toImageFileDirectory_v2
as a tuple and require a matching type intagtype
tagtype.- 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"
- quality
The image quality for JPEG compression, on a scale from 0 (worst) to 100 (best). The default is 75.
6.1.0 新版功能.
These arguments to set the tiff header fields are an alternative to using the general tags available through tiffinfo.
description
software
date_time
artist
- copyright
- Strings
- resolution_unit
- An integer. 1 for no unit, 2 for inches and 3 for centimeters.
- resolution
- Either an integer or a float, used for both the x and y resolution.
- x_resolution
- Either an integer or a float.
- y_resolution
- Either an integer or a float.
- dpi
- A tuple of (x_resolution, y_resolution), with inches as the resolution unit. For consistency with other image formats, the x and y resolutions of the dpi will be rounded to the nearest integer.
WebP¶
Pillow reads and writes WebP files. The specifics of Pillow’s capabilities with this format are currently undocumented.
The save()
method supports the following options:
- lossless
- If present and true, instructs the WebP writer to use lossless compression.
- quality
- Integer, 1-100, Defaults to 80. For lossy, 0 gives the smallest size and 100 the largest. For lossless, this parameter is the amount of effort put into the compression: 0 is the fastest, but gives larger files compared to the slowest, but best, 100.
- method
- Quality/speed trade-off (0=fast, 6=slower-better). Defaults to 0.
- icc_profile
- The ICC Profile to include in the saved file. Only supported if the system WebP library was built with webpmux support.
- exif
- The exif data to include in the saved file. Only supported if the system WebP library was built with webpmux support.
注解
Support for animated WebP files will only be enabled if the system WebP
library is v0.5.0 or later. You can check webp animation support at
runtime by calling features.check("webp_anim")
.
When calling save()
, the following options
are available when the save_all
argument is present and true.
- append_images
- A list of images to append as additional frames. Each of the images in the list can be single or multiframe images.
- duration
- The display duration of each frame, in milliseconds. Pass a single integer for a constant duration, or a list or tuple to set the duration for each frame separately.
- loop
- Number of times to repeat the animation. Defaults to [0 = infinite].
- background
- Background color of the canvas, as an RGBA tuple with values in the range of (0-255).
- minimize_size
- If true, minimize the output size (slow). Implicitly disables key-frame insertion.
- kmin, kmax
- Minimum and maximum distance between consecutive key frames in the output. The library may insert some key frames as needed to satisfy this criteria. Note that these conditions should hold: kmax > kmin and kmin >= kmax / 2 + 1. Also, if kmax <= 0, then key-frame insertion is disabled; and if kmax == 1, then all frames will be key-frames (kmin value does not matter for these special cases).
- allow_mixed
- If true, use mixed compression mode; the encoder heuristically chooses between lossy and lossless for each frame.
Read-only formats¶
BLP¶
BLP is the Blizzard Mipmap Format, a texture format used in World of
Warcraft. Pillow supports reading JPEG
Compressed or raw BLP1
images, and all types of BLP2
images.
CUR¶
CUR is used to store cursors on Windows. The CUR decoder reads the largest available cursor. Animated cursors are not supported.
DCX¶
DCX is a container file format for PCX files, defined by Intel. The DCX format
is commonly used in fax applications. The DCX decoder can read files containing
1
, L
, P
, or RGB
data.
When the file is opened, only the first image is read. You can use
seek()
or ImageSequence
to read other images.
DDS¶
DDS is a popular container texture format used in video games and natively
supported by DirectX.
Currently, uncompressed RGB data and DXT1, DXT3, and DXT5 pixel formats are
supported, and only in RGBA
mode.
3.4.0 新版功能: DXT3
FLI, FLC¶
Pillow reads Autodesk FLI and FLC animations.
The open()
method sets the following
info
properties:
- duration
- The delay (in milliseconds) between each frame.
FPX¶
Pillow reads Kodak FlashPix files. In the current version, only the highest resolution image is read from the file, and the viewing transform is not taken into account.
注解
To enable full FlashPix support, you need to build and install the IJG JPEG library before building the Python Imaging Library. See the distribution README for details.
FTEX¶
3.2.0 新版功能.
The FTEX decoder reads textures used for 3D objects in Independence War 2: Edge Of Chaos. The plugin reads a single texture per file, in the compressed and uncompressed formats.
GBR¶
The GBR decoder reads GIMP brush files, version 1 and 2.
The open()
method sets the following
info
properties:
- comment
- The brush name.
- spacing
- The spacing between the brushes, in pixels. Version 2 only.
GD¶
Pillow reads uncompressed GD2 files. Note that you must use
PIL.GdImageFile.open()
to read such a file.
The open()
method sets the following
info
properties:
- transparency
- Transparency color index. This key is omitted if the image is not transparent.
MIC¶
Pillow identifies and reads Microsoft Image Composer (MIC) files. When opened,
the first sprite in the file is loaded. You can use seek()
and
tell()
to read other sprites from the file.
Note that there may be an embedded gamma of 2.2 in MIC files.
MPO¶
Pillow identifies and reads Multi Picture Object (MPO) files, loading the primary
image when first opened. The seek()
and tell()
methods may be used to read other pictures from the file. The pictures are
zero-indexed and random access is supported.
PCD¶
Pillow reads PhotoCD files containing RGB
data. This only reads the 768x512
resolution image from the file. Higher resolutions are encoded in a proprietary
encoding.
PIXAR¶
Pillow provides limited support for PIXAR raster files. The library can identify and read “dumped” RGB files.
The format code is PIXAR
.
WAL¶
1.1.4 新版功能.
Pillow 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.
Write-only formats¶
PALM¶
Pillow provides write-only support for PALM pixmap files.
The format code is Palm
, the extension is .palm
.
PDF¶
Pillow can write PDF (Acrobat) images. Such images are written as binary PDF 1.4 files, using either JPEG or HEX encoding depending on the image mode (and whether JPEG support is available or not).
The save()
method can take the following keyword arguments:
- save_all
If a multiframe image is used, by default, only the first image will be saved. To save all frames, each frame to a separate page of the PDF, the
save_all
parameter must be present and set toTrue
.3.0.0 新版功能.
- append_images
A list of images to append as additional pages. Each of the images in the list can be single or multiframe images.
4.2.0 新版功能.
- append
Set to True to append pages to an existing PDF file. If the file doesn’t exist, an
IOError
will be raised.5.1.0 新版功能.
- resolution
- Image resolution in DPI. This, together with the number of pixels in the image, will determine the physical dimensions of the page that will be saved in the PDF.
- title
The document’s title. If not appending to an existing PDF file, this will default to the filename.
5.1.0 新版功能.
- author
The name of the person who created the document.
5.1.0 新版功能.
- subject
The subject of the document.
5.1.0 新版功能.
- keywords
Keywords associated with the document.
5.1.0 新版功能.
- creator
If the document was converted to PDF from another format, the name of the conforming product that created the original document from which it was converted.
5.1.0 新版功能.
- producer
If the document was converted to PDF from another format, the name of the conforming product that converted it to PDF.
5.1.0 新版功能.
- creationDate
The creation date of the document. If not appending to an existing PDF file, this will default to the current time.
5.3.0 新版功能.
- modDate
The modification date of the document. If not appending to an existing PDF file, this will default to the current time.
5.3.0 新版功能.
XV Thumbnails¶
Pillow can read XV thumbnail files.
Identify-only formats¶
BUFR¶
1.1.3 新版功能.
Pillow provides a stub driver for BUFR files.
To add read or write support to your application, use
PIL.BufrStubImagePlugin.register_handler()
.
FITS¶
1.1.5 新版功能.
Pillow provides a stub driver for FITS files.
To add read or write support to your application, use
PIL.FitsStubImagePlugin.register_handler()
.
GRIB¶
1.1.5 新版功能.
Pillow 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 Pillow.
To add read or write support to your application, use
PIL.GribStubImagePlugin.register_handler()
.
HDF5¶
1.1.5 新版功能.
Pillow provides a stub driver for HDF5 files.
To add read or write support to your application, use
PIL.Hdf5StubImagePlugin.register_handler()
.
WMF¶
Pillow can identify playable 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")
Writing Your Own Image Plugin¶
The Pillow uses a plug-in model which allows you to add your own
decoders to the library, without any changes to the library
itself. Such plug-ins usually have names like
XxxImagePlugin.py
, where Xxx
is a unique format name
(usually an abbreviation).
警告
Pillow >= 2.1.0 no longer automatically imports any file
in the Python path with a name ending in
ImagePlugin.py
. You will need to import your
image plugin manually.
Pillow decodes files in 2 stages:
- It loops over the available image plugins in the loaded order, and
calls the plugin’s
accept
function with the first 16 bytes of the file. If theaccept
function returns true, the plugin’s_open
method is called to set up the image metadata and image tiles. The_open
method is not for decoding the actual image data. - When the image data is requested, the
ImageFile.load
method is called, which sets up a decoder for each tile and feeds the data to it.
An image plug-in should contain a format handler derived from 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, which contain a decoder name, extents of the tile, and
any decoder-specific data. The format handler 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.
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))
]
Image.register_open(SpamImageFile.format, SpamImageFile)
Image.register_extension(SpamImageFile.format, ".spam")
Image.register_extension(SpamImageFile.format, ".spa") # dos version
The format handler must always set the
size
and mode
attributes. If these are not set, the file cannot be opened. To
simplify the plugin, the calling code considers exceptions like
SyntaxError
, KeyError
, IndexError
,
EOFError
and struct.error
as a failure to identify
the file.
Note that the image plugin must be explicitly registered using
PIL.Image.register_open()
. Although not required, it is also a good
idea to register any extensions used by this format.
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.
Decoders¶
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.frombytes()
function, use the following syntax:
image = Image.frombytes(
mode, size, data, "raw",
raw mode, stride, orientation
)
When used in a tile descriptor, the parameter field should look like:
(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
- 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 | description |
---|---|
1 |
1-bit bilevel, stored with the leftmost pixel in the most significant bit. 0 means black, 1 means white. |
1;I |
1-bit inverted bilevel, stored with the leftmost pixel in the most significant bit. 0 means white, 1 means black. |
1;R |
1-bit reversed bilevel, stored with the leftmost pixel in the least significant bit. 0 means black, 1 means white. |
L |
8-bit greyscale. 0 means black, 255 means white. |
L;I |
8-bit inverted greyscale. 0 means white, 255 means black. |
P |
8-bit palette-mapped image. |
RGB |
24-bit true colour, stored as (red, green, blue). |
BGR |
24-bit true colour, stored as (blue, green, red). |
RGBX |
24-bit true colour, stored as (red, green, blue, pad). The pad pixels may vary. |
RGB;L |
24-bit true colour, line interleaved (first all red pixels, then 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.
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 | description |
---|---|
F |
32-bit native floating point. |
F;8 |
8-bit unsigned integer. |
F;8S |
8-bit signed integer. |
F;16 |
16-bit little endian unsigned integer. |
F;16S |
16-bit little endian signed integer. |
F;16B |
16-bit big endian unsigned integer. |
F;16BS |
16-bit big endian signed integer. |
F;16N |
16-bit native unsigned integer. |
F;16NS |
16-bit native signed integer. |
F;32 |
32-bit little endian unsigned integer. |
F;32S |
32-bit little endian signed integer. |
F;32B |
32-bit big endian unsigned integer. |
F;32BS |
32-bit big endian signed integer. |
F;32N |
32-bit native unsigned integer. |
F;32NS |
32-bit native signed integer. |
F;32F |
32-bit little endian floating point. |
F;32BF |
32-bit big endian floating point. |
F;32NF |
32-bit native floating point. |
F;64F |
64-bit little endian floating point. |
F;64BF |
64-bit big endian floating point. |
F;64NF |
64-bit native floating point. |
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 PIL.Image.frombytes()
function, use
the following syntax:
image = Image.frombytes(
mode, size, data, "bit",
bits, pad, fill, sign, orientation
)
When used in a tile descriptor, the parameter field should look like:
(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.
Writing Your Own File Decoder in C¶
There are 3 stages in a file decoder’s lifetime:
- Setup: Pillow looks for a function in the decoder registry, falling
back to a function named
[decodername]_decoder
on the internal core image object. That function is called with theargs
tuple from thetile
setup in the_open
method. - Decoding: The decoder’s decode function is repeatedly called with chunks of image data.
- Cleanup: If the decoder has registered a cleanup function, it will be called at the end of the decoding process, even if there was an exception raised.
Setup¶
The current conventions are that the decoder setup function is named
PyImaging_[Decodername]DecoderNew
and defined in decode.c
. The
python binding for it is named [decodername]_decoder
and is setup
from within the _imaging.c
file in the codecs section of the
function array.
The setup function needs to call PyImaging_DecoderNew
and at the
very least, set the decode
function pointer. The fields of
interest in this object are:
- decode
- Function pointer to the decode function, which has access to
im
,state
, and the buffer of data to be added to the image. - cleanup
- Function pointer to the cleanup function, has access to
state
. - im
- The target image, will be set by Pillow.
- state
- An ImagingCodecStateInstance, will be set by Pillow. The context member is an opaque struct that can be used by the decoder to store any format specific state or options.
- pulls_fd
EXPERIMENTAL – WARNING, interface may change. If set to 1,
state->fd
will be a pointer to the Python file like object. The decoder may use the functions incodec_fd.c
to read directly from the file like object rather than have the data pushed through a buffer. Note that this implementation may be refactored until this warning is removed.3.3.0 新版功能.
Decoding¶
The decode function is called with the target (core) image, the decoder state structure, and a buffer of data to be decoded.
Experimental – If pulls_fd
is set, then the decode function
is called once, with an empty buffer. It is the decoder’s
responsibility to decode the entire tile in that one call. The rest of
this section only applies if pulls_fd
is not set.
It is the decoder’s responsibility to pull as much data as possible out of the buffer and return the number of bytes consumed. The next call to the decoder will include the previous unconsumed tail. The decoder function will be called multiple times as the data is read from the file like object.
If an error occurs, set state->errcode
and return -1.
Return -1 on success, without setting the errcode.
Cleanup¶
The cleanup function is called after the decoder returns a negative value, or if there is a read error from the file. This function should free any allocated memory and release any resources from external libraries.
Writing Your Own File Decoder in Python¶
Python file decoders should derive from
PIL.ImageFile.PyDecoder
and should at least override the
decode method. File decoders should be registered using
PIL.Image.register_decoder()
. As in the C implementation of
the file decoders, there are three stages in the lifetime of a
Python-based file decoder:
- Setup: Pillow looks for the decoder in the registry, then instantiates the class.
- Decoding: The decoder instance’s
decode
method is repeatedly called with a buffer of data to be interpreted. - Cleanup: The decoder instance’s
cleanup
method is called.
参考¶
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.
Examples¶
Open, rotate, and display an image (using the default viewer)¶
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).
from PIL import Image
im = Image.open("bride.jpg")
im.rotate(45).show()
Create thumbnails¶
The following script creates nice thumbnails of all JPEG images in the current directory preserving aspect ratios with 128x128 max resolution.
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)
im.save(file + ".thumbnail", "JPEG")
Functions¶
-
PIL.Image.
open
(fp, mode='r')[源代码]¶ Opens and identifies the given image file.
This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the
load()
method). Seenew()
. See File Handling in Pillow.参数: - fp – A filename (string), pathlib.Path object or a file object.
The file object must implement
read()
,seek()
, andtell()
methods, and be opened in binary mode. - mode – The mode. If given, this argument must be “r”.
返回: An
Image
object.引发: IOError – If the file cannot be found, or the image cannot be opened and identified.
警告
To protect against potential DOS attacks caused by “decompression bombs” (i.e. malicious files which decompress into a huge amount of data and are designed to crash or cause disruption by using up a lot of memory), Pillow will issue a
DecompressionBombWarning
if the image is over a certain limit. If desired, the warning can be turned into an error withwarnings.simplefilter('error', Image.DecompressionBombWarning)
or suppressed entirely withwarnings.simplefilter('ignore', Image.DecompressionBombWarning)
. See also the logging documentation to have warnings output to the logging facility instead of stderr.- fp – A filename (string), pathlib.Path object or a file object.
The file object must implement
Image processing¶
-
PIL.Image.
alpha_composite
(im1, im2)[源代码]¶ Alpha composite im2 over im1.
参数: - im1 – The first image. Must have mode RGBA.
- im2 – The second image. Must have mode RGBA, and the same size as the first image.
返回: An
Image
object.
-
PIL.Image.
blend
(im1, im2, alpha)[源代码]¶ Creates a new image by interpolating between two input images, using a constant alpha.:
out = image1 * (1.0 - alpha) + image2 * alpha
参数: - im1 – The first image.
- im2 – The second image. Must have the same mode and size as the first image.
- alpha – The interpolation alpha factor. If alpha is 0.0, a copy of the first image is returned. If alpha is 1.0, a copy of the second image is returned. There are no restrictions on the alpha value. If necessary, the result is clipped to fit into the allowed output range.
返回: An
Image
object.
-
PIL.Image.
composite
(image1, image2, mask)[源代码]¶ Create composite image by blending images using a transparency mask.
参数: - image1 – The first image.
- image2 – The second image. Must have the same mode and size as the first image.
- mask – A mask image. This image can have mode “1”, “L”, or “RGBA”, and must have the same size as the other two images.
-
PIL.Image.
eval
(image, *args)[源代码]¶ Applies the function (which should take one argument) to each pixel in the given image. If the image has more than one band, the same function is applied to each band. Note that the function is evaluated once for each possible pixel value, so you cannot use random components or other generators.
参数: - image – The input image.
- function – A function object, taking one integer argument.
返回: An
Image
object.
Constructing images¶
-
PIL.Image.
new
(mode, size, color=0)[源代码]¶ Creates a new image with the given mode and size.
参数: - mode – The mode to use for the new image. See: 模式.
- size – A 2-tuple, containing (width, height) in pixels.
- color – What color to use for the image. Default is black. If given, this should be a single integer or floating point value for single-band modes, and a tuple for multi-band modes (one value per band). When creating RGB images, you can also use color strings as supported by the ImageColor module. If the color is None, the image is not initialised.
返回: An
Image
object.
-
PIL.Image.
fromarray
(obj, mode=None)[源代码]¶ Creates an image memory from an object exporting the array interface (using the buffer protocol).
If obj is not contiguous, then the tobytes method is called and
frombuffer()
is used.If you have an image in NumPy:
from PIL import Image import numpy as np im = Image.open('hopper.jpg') a = np.asarray(im)
Then this can be used to convert it to a Pillow image:
im = Image.fromarray(a)
参数: - obj – Object with array interface
- mode – Mode to use (will be determined from type if None) See: 模式.
返回: An image object.
1.1.6 新版功能.
-
PIL.Image.
frombytes
(mode, size, data, decoder_name='raw', *args)[源代码]¶ Creates a copy of an image memory from pixel data in a buffer.
In its simplest form, this function takes three arguments (mode, size, and unpacked pixel data).
You can also use any pixel decoder supported by PIL. For more information on available decoders, see the section Writing Your Own File Decoder.
Note that this function decodes pixel data only, not entire images. If you have an entire image in a string, wrap it in a
BytesIO
object, and useopen()
to load it.参数: - mode – The image mode. See: 模式.
- size – The image size.
- data – A byte buffer containing raw data for the given mode.
- decoder_name – What decoder to use.
- args – Additional parameters for the given decoder.
返回: An
Image
object.
-
PIL.Image.
frombuffer
(mode, size, data, decoder_name='raw', *args)[源代码]¶ Creates an image memory referencing pixel data in a byte buffer.
This function is similar to
frombytes()
, but uses data in the byte buffer, where possible. This means that changes to the original buffer object are reflected in this image). Not all modes can share memory; supported modes include “L”, “RGBX”, “RGBA”, and “CMYK”.Note that this function decodes pixel data only, not entire images. If you have an entire image file in a string, wrap it in a BytesIO object, and use
open()
to load it.In the current version, the default parameters used for the “raw” decoder differs from that used for
frombytes()
. This is a bug, and will probably be fixed in a future release. The current release issues a warning if you do this; to disable the warning, you should provide the full set of parameters. See below for details.参数: - mode – The image mode. See: 模式.
- size – The image size.
- data – A bytes or other buffer object containing raw data for the given mode.
- decoder_name – What decoder to use.
- args –
Additional parameters for the given decoder. For the default encoder (“raw”), it’s recommended that you provide the full set of parameters:
frombuffer(mode, size, data, "raw", mode, 0, 1)
返回: An
Image
object.1.1.4 新版功能.
Registering plugins¶
注解
These functions are for use by plugin authors. Application authors can ignore them.
-
PIL.Image.
register_open
(id, factory, accept=None)[源代码]¶ Register an image file plugin. This function should not be used in application code.
参数: - id – An image format identifier.
- factory – An image file factory method.
- accept – An optional function that can be used to quickly reject images having another format.
-
PIL.Image.
register_decoder
(name, decoder)[源代码]¶ Registers an image decoder. This function should not be used in application code.
参数: - name – The name of the decoder
- decoder – A callable(mode, args) that returns an ImageFile.PyDecoder object
4.1.0 新版功能.
-
PIL.Image.
register_mime
(id, mimetype)[源代码]¶ Registers an image MIME type. This function should not be used in application code.
参数: - id – An image format identifier.
- mimetype – The image MIME type for this format.
-
PIL.Image.
register_save
(id, driver)[源代码]¶ Registers an image save function. This function should not be used in application code.
参数: - id – An image format identifier.
- driver – A function to save images in this format.
The Image Class¶
-
class
PIL.Image.
Image
[源代码]¶ This class represents an image object. To create
Image
objects, use the appropriate factory functions. There’s hardly ever any reason to call the Image constructor directly.
An instance of the Image
class has the following
methods. Unless otherwise stated, all methods return a new instance of the
Image
class, holding the resulting image.
-
Image.
alpha_composite
(im, dest=(0, 0), source=(0, 0))[源代码]¶ ‘In-place’ analog of Image.alpha_composite. Composites an image onto this image.
参数: - im – image to composite over this one
- dest – Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image.
- source – Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle
Performance Note: Not currently implemented in-place in the core layer.
-
Image.
convert
(mode=None, matrix=None, dither=None, palette=0, colors=256)[源代码]¶ Returns a converted copy of this image. For the “P” mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette.
The current version supports all possible conversions between “L”, “RGB” and “CMYK.” The matrix argument only supports “L” and “RGB”.
When translating a color image to greyscale (mode “L”), the library uses the ITU-R 601-2 luma transform:
L = R * 299/1000 + G * 587/1000 + B * 114/1000
The default method of converting a greyscale (“L”) or “RGB” image into a bilevel (mode “1”) image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is NONE, all values larger than 128 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the
point()
method.When converting from “RGBA” to “P” without a matrix argument, this passes the operation to
quantize()
, and dither and palette are ignored.参数: - mode – The requested mode. See: 模式.
- matrix – An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values.
- dither – Dithering method, used when converting from mode “RGB” to “P” or from “RGB” or “L” to “1”. Available methods are NONE or FLOYDSTEINBERG (default). Note that this is not used when matrix is supplied.
- palette – Palette to use when converting from mode “RGB” to “P”. Available palettes are WEB or ADAPTIVE.
- colors – Number of colors to use for the ADAPTIVE palette. Defaults to 256.
返回类型: 返回: An
Image
object.
The following example converts an RGB image (linearly calibrated according to ITU-R 709, using the D65 luminant) to the CIE XYZ color space:
rgb2xyz = (
0.412453, 0.357580, 0.180423, 0,
0.212671, 0.715160, 0.072169, 0,
0.019334, 0.119193, 0.950227, 0)
out = im.convert("RGB", rgb2xyz)
-
Image.
copy
()[源代码]¶ Copies this image. Use this method if you wish to paste things into an image, but still retain the original.
返回类型: Image
返回: An Image
object.
-
Image.
crop
(box=None)[源代码]¶ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See 坐标系统.
Note: Prior to Pillow 3.4.0, this was a lazy operation.
参数: box – The crop rectangle, as a (left, upper, right, lower)-tuple. 返回类型: Image
返回: An Image
object.
This crops the input image with the provided coordinates:
from PIL import Image
im = Image.open("hopper.jpg")
# The crop method from the Image module takes four coordinates as input.
# The right can also be represented as (left+width)
# and lower can be represented as (upper+height).
(left, upper, right, lower) = (20, 20, 100, 100)
# Here the image "im" is cropped and assigned to new variable im_crop
im_crop = im.crop((left, upper, right, lower))
-
Image.
draft
(mode, size)[源代码]¶ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it, or to extract a 128x192 version from a PCD file.
Note that this method modifies the
Image
object in place. If the image has already been loaded, this method has no effect.Note: This method is not implemented for most images. It is currently implemented only for JPEG and PCD images.
参数: - mode – The requested mode.
- size – The requested size.
-
Image.
filter
(filter)[源代码]¶ Filters this image using the given filter. For a list of available filters, see the
ImageFilter
module.参数: filter – Filter kernel. 返回: An Image
object.
This blurs the input image using a filter from the ImageFilter
module:
from PIL import Image, ImageFilter
im = Image.open("hopper.jpg")
# Blur the input image using the filter ImageFilter.BLUR
im_blurred = im.filter(filter=ImageFilter.BLUR)
-
Image.
getbands
()[源代码]¶ Returns a tuple containing the name of each band in this image. For example, getbands on an RGB image returns (“R”, “G”, “B”).
返回: A tuple containing band names. 返回类型: tuple
This helps to get the bands of the input image:
from PIL import Image
im = Image.open("hopper.jpg")
print(im.getbands()) # Returns ('R', 'G', 'B')
-
Image.
getbbox
()[源代码]¶ Calculates the bounding box of the non-zero regions in the image.
返回: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See 坐标系统. If the image is completely empty, this method returns None.
This helps to get the bounding box coordinates of the input image:
from PIL import Image
im = Image.open("hopper.jpg")
print(im.getbbox())
# Returns four coordinates in the format (left, upper, right, lower)
-
Image.
getcolors
(maxcolors=256)[源代码]¶ Returns a list of colors used in this image.
参数: maxcolors – Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. 返回: An unsorted list of (count, pixel) values.
-
Image.
getdata
(band=None)[源代码]¶ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.
Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata()).
参数: band – What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the “R” band from an “RGB” image). 返回: A sequence-like object.
-
Image.
getextrema
()[源代码]¶ Gets the the minimum and maximum pixel values for each band in the image.
返回: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band.
-
Image.
getpalette
()[源代码]¶ Returns the image palette as a list.
返回: A list of color values [r, g, b, …], or None if the image has no palette.
-
Image.
getpixel
(xy)[源代码]¶ Returns the pixel value at a given position.
参数: xy – The coordinate, given as (x, y). See 坐标系统. 返回: The pixel value. If the image is a multi-layer image, this method returns a tuple.
-
Image.
histogram
(mask=None, extrema=None)[源代码]¶ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an “RGB” image contains 768 values).
A bilevel image (mode “1”) is treated as a greyscale (“L”) image by this method.
If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode “1”) or a greyscale image (“L”).
参数: mask – An optional mask. 返回: A list containing pixel counts.
-
Image.
paste
(im, box=None, mask=None)[源代码]¶ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See 坐标系统. If a 4-tuple is given, the size of the pasted image must match the size of the region.
If the modes don’t match, the pasted image is converted to the mode of this image (see the
convert()
method for details).Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module.
If a mask is given, this method updates only the regions indicated by the mask. You can use either “1”, “L” or “RGBA” images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them.
See
alpha_composite()
if you want to combine images with respect to their alpha channels.参数: - im – Source image or pixel value (integer or tuple).
- box –
An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it’s treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner.
If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image.
- mask – An optional mask image.
-
Image.
point
(lut, mode=None)[源代码]¶ Maps this image through a lookup table or function.
参数: - lut – A lookup table, containing 256 (or 65536 if self.mode==”I” and mode == “L”) values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image.
- mode – Output mode (default is same as input). In the current version, this can only be used if the source image has mode “L” or “P”, and the output has mode “1” or the source image mode is “I” and the output mode is “L”.
返回: An
Image
object.
-
Image.
putalpha
(alpha)[源代码]¶ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it’s converted to “LA” or “RGBA”. The new layer must be either “L” or “1”.
参数: alpha – The new alpha layer. This can either be an “L” or “1” image having the same size as this image, or an integer or other color value.
-
Image.
putdata
(data, scale=1.0, offset=0.0)[源代码]¶ Copies pixel data to this image. This method copies data from a sequence object into the image, starting at the upper left corner (0, 0), and continuing until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: pixel = value*scale + offset.
参数: - data – A sequence object.
- scale – An optional scale value. The default is 1.0.
- offset – An optional offset value. The default is 0.0.
-
Image.
putpalette
(data, rawmode='RGB')[源代码]¶ Attaches a palette to this image. The image must be a “P” or “L” image, and the palette sequence must contain 768 integer values, where each group of three values represent the red, green, and blue values for the corresponding pixel index. Instead of an integer sequence, you can use an 8-bit string.
参数: - data – A palette sequence (either a list or a string).
- rawmode – The raw mode of the palette.
-
Image.
putpixel
(xy, value)[源代码]¶ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P images.
Note that this method is relatively slow. For more extensive changes, use
paste()
or theImageDraw
module instead.See:
参数: - xy – The pixel coordinate, given as (x, y). See 坐标系统.
- value – The pixel value.
-
Image.
quantize
(colors=256, method=None, kmeans=0, palette=None)[源代码]¶ Convert the image to ‘P’ mode with the specified number of colors.
参数: - colors – The desired number of colors, <= 256
- method – 0 = median cut 1 = maximum coverage 2 = fast octree 3 = libimagequant
- kmeans – Integer
- palette – Quantize to the palette of given
PIL.Image.Image
.
返回: A new image
-
Image.
resize
(size, resample=0, box=None)[源代码]¶ Returns a resized copy of this image.
参数: - size – The requested size in pixels, as a 2-tuple: (width, height).
- resample – An optional resampling filter. This can be
one of
PIL.Image.NEAREST
,PIL.Image.BOX
,PIL.Image.BILINEAR
,PIL.Image.HAMMING
,PIL.Image.BICUBIC
orPIL.Image.LANCZOS
. If omitted, or if the image has mode “1” or “P”, it is setPIL.Image.NEAREST
. See: 滤波器. - box – An optional 4-tuple of floats giving the region of the source image which should be scaled. The values should be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used.
返回: An
Image
object.
This resizes the given image from (width, height)
to (width/2, height/2)
:
from PIL import Image
im = Image.open("hopper.jpg")
# Provide the target width and height of the image
(width, height) = (im.width // 2, im.height // 2)
im_resized = im.resize((width, height))
-
Image.
remap_palette
(dest_map, source_palette=None)[源代码]¶ Rewrites the image to reorder the palette.
参数: - dest_map – A list of indexes into the original palette. e.g. [1,0] would swap a two item palette, and list(range(255)) is the identity transform.
- source_palette – Bytes or None.
返回: An
Image
object.
-
Image.
rotate
(angle, resample=0, expand=0, center=None, translate=None, fillcolor=None)[源代码]¶ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre.
参数: - angle – In degrees counter clockwise.
- resample – An optional resampling filter. This can be
one of
PIL.Image.NEAREST
(use nearest neighbour),PIL.Image.BILINEAR
(linear interpolation in a 2x2 environment), orPIL.Image.BICUBIC
(cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode “1” or “P”, it is setPIL.Image.NEAREST
. See 滤波器. - expand – Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation.
- center – Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image.
- translate – An optional post-rotate translation (a 2-tuple).
- fillcolor – An optional color for area outside the rotated image.
返回: An
Image
object.
This rotates the input image by theta
degrees counter clockwise:
from PIL import Image
im = Image.open("hopper.jpg")
# Rotate the image by 60 degrees counter clockwise
theta = 60
# Angle is in degrees counter clockwise
im_rotated = im.rotate(angle=theta)
-
Image.
save
(fp, format=None, **params)[源代码]¶ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible.
Keyword options can be used to provide additional instructions to the writer. If a writer doesn’t recognise an option, it is silently ignored. The available options are described in the image format documentation for each writer.
You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the
seek
,tell
, andwrite
methods, and be opened in binary mode.参数: - fp – A filename (string), pathlib.Path object or file object.
- format – Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used.
- params – Extra parameters to the image writer.
返回: None
引发: - ValueError – If the output format could not be determined from the file name. Use the format option to solve this.
- IOError – If the file could not be written. The file may have been created, and may contain partial data.
-
Image.
seek
(frame)[源代码]¶ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an EOFError exception. When a sequence file is opened, the library automatically seeks to frame 0.
Note that in the current version of the library, most sequence formats only allows you to seek to the next frame.
See
tell()
.参数: frame – Frame number, starting at 0. 引发: EOFError – If the call attempts to seek beyond the end of the sequence.
-
Image.
show
(title=None, command=None)[源代码]¶ Displays this image. This method is mainly intended for debugging purposes.
On Unix platforms, this method saves the image to a temporary PPM file, and calls either the xv utility or the display utility, depending on which one can be found.
On macOS, this method saves the image to a temporary BMP file, and opens it with the native Preview application.
On Windows, it saves the image to a temporary BMP file, and uses the standard BMP display utility to show it (usually Paint).
参数: - title – Optional title to use for the image window, where possible.
- command – command used to show the image
-
Image.
split
()[源代码]¶ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an “RGB” image creates three new images each containing a copy of one of the original bands (red, green, blue).
If you need only one band,
getchannel()
method can be more convenient and faster.返回: A tuple containing bands.
-
Image.
getchannel
(channel)[源代码]¶ Returns an image containing a single channel of the source image.
参数: channel – What channel to return. Could be index (0 for “R” channel of “RGB”) or channel name (“A” for alpha channel of “RGBA”). 返回: An image in “L” mode. 4.3.0 新版功能.
-
Image.
thumbnail
(size, resample=3)[源代码]¶ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the
draft()
method to configure the file reader (where applicable), and finally resizes the image.Note that this function modifies the
Image
object in place. If you need to use the full resolution image as well, apply this method to acopy()
of the original image.参数: - size – Requested size.
- resample – Optional resampling filter. This can be one
of
PIL.Image.NEAREST
,PIL.Image.BILINEAR
,PIL.Image.BICUBIC
, orPIL.Image.LANCZOS
. If omitted, it defaults toPIL.Image.BICUBIC
. (wasPIL.Image.NEAREST
prior to version 2.5.0)
返回: None
-
Image.
tobitmap
(name='image')[源代码]¶ Returns the image converted to an X11 bitmap.
注解
This method only works for mode “1” images.
参数: name – The name prefix to use for the bitmap variables. 返回: A string containing an X11 bitmap. 引发: ValueError – If the mode is not “1”
-
Image.
tobytes
(encoder_name='raw', *args)[源代码]¶ Return image as a bytes object.
警告
This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use
save()
, with a BytesIO parameter for in-memory data.参数: - encoder_name – What encoder to use. The default is to use the standard “raw” encoder.
- args – Extra arguments to the encoder.
返回类型: A bytes object.
-
Image.
transform
(size, method, data=None, resample=0, fill=1, fillcolor=None)[源代码]¶ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform.
参数: - size – The output size.
- method –
The transformation method. This is one of
PIL.Image.EXTENT
(cut out a rectangular subregion),PIL.Image.AFFINE
(affine transform),PIL.Image.PERSPECTIVE
(perspective transform),PIL.Image.QUAD
(map a quadrilateral to a rectangle), orPIL.Image.MESH
(map a number of source quadrilaterals in one operation).It may also be an
ImageTransformHandler
object:class Example(Image.ImageTransformHandler): def transform(size, method, data, resample, fill=1): # Return result
It may also be an object with a
getdata()
method that returns a tuple supplying new method and data values:class Example(object): def getdata(self): method = Image.EXTENT data = (0, 0, 100, 100) return method, data
- data – Extra data to the transformation method.
- resample – Optional resampling filter. It can be one of
PIL.Image.NEAREST
(use nearest neighbour),PIL.Image.BILINEAR
(linear interpolation in a 2x2 environment), orPIL.Image.BICUBIC
(cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode “1” or “P”, it is set toPIL.Image.NEAREST
. - fill – If method is an
ImageTransformHandler
object, this is one of the arguments passed to it. Otherwise, it is unused. - fillcolor – Optional fill color for the area outside the transform in the output image.
返回: An
Image
object.
-
Image.
transpose
(method)[源代码]¶ Transpose image (flip or rotate in 90 degree steps)
参数: method – One of PIL.Image.FLIP_LEFT_RIGHT
,PIL.Image.FLIP_TOP_BOTTOM
,PIL.Image.ROTATE_90
,PIL.Image.ROTATE_180
,PIL.Image.ROTATE_270
,PIL.Image.TRANSPOSE
orPIL.Image.TRANSVERSE
.返回: Returns a flipped or rotated copy of this image.
This flips the input image by using the Image.FLIP_LEFT_RIGHT
method.
from PIL import Image
im = Image.open("hopper.jpg")
# Flip the image from left to right
im_flipped = im.transpose(method=Image.FLIP_LEFT_RIGHT)
# To flip the image from top to bottom,
# use the method "Image.FLIP_TOP_BOTTOM"
-
Image.
verify
()[源代码]¶ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file.
-
Image.
load
()[源代码]¶ Allocates storage for the image and loads the pixel data. In normal cases, you don’t need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time.
If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See File Handling in Pillow for more information.
返回: An image access object. 返回类型: PixelAccess Class or PIL.PyAccess
-
Image.
close
()[源代码]¶ Closes the file pointer, if possible.
This operation will destroy the image core and release its memory. The image data will be unusable afterward.
This function is only required to close images that have not had their file read and closed by the
load()
method. See File Handling in Pillow for more information.
Attributes¶
Instances of the Image
class have the following attributes:
-
PIL.Image.
filename
¶ The filename or path of the source file. Only images created with the factory function
open
have a filename attribute. If the input is a file like object, the filename attribute is set to an empty string.Type: string
-
PIL.Image.
format
¶ The file format of the source file. For images created by the library itself (via a factory function, or by running a method on an existing image), this attribute is set to
None
.Type: string
orNone
-
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 模式 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” or “PA”, this should be an instance of the
ImagePalette
class. Otherwise, it should be set toNone
.Type: ImagePalette
orNone
-
PIL.Image.
info
¶ A dictionary holding data associated with the image. This dictionary is used by file handlers to pass on various non-image information read from the file. See documentation for the various file handlers for details.
Most methods ignore the dictionary when returning new images; since the keys are not standardized, it’s not possible for a method to know if the operation affects the dictionary. If you need the information later on, keep a reference to the info dictionary returned from the open method.
Unless noted elsewhere, this dictionary does not affect saving files.
Type: dict
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”).
Functions¶
Most channel operations take one or two image arguments and returns a new image. Unless otherwise noted, the result of a channel operation is always clipped to the range 0 to MAX (which is 255 for all modes supported by the operations in this module).
-
PIL.ImageChops.
add
(image1, image2, scale=1.0, offset=0)[源代码]¶ Adds two images, dividing the result by scale and adding the offset. If omitted, scale defaults to 1.0, and offset to 0.0. At least one of the images must have mode “1”.
out = ((image1 + image2) / scale + offset)
返回类型: Image
-
PIL.ImageChops.
add_modulo
(image1, image2)[源代码]¶ Add two images, without clipping the result. At least one of the images must have mode “1”.
out = ((image1 + image2) % MAX)
返回类型: Image
-
PIL.ImageChops.
blend
(image1, image2, alpha)[源代码]¶ Blend images using constant transparency weight. Alias for
PIL.Image.Image.blend()
.返回类型: Image
-
PIL.ImageChops.
composite
(image1, image2, mask)[源代码]¶ Create composite using transparency mask. Alias for
PIL.Image.Image.composite()
.返回类型: Image
-
PIL.ImageChops.
darker
(image1, image2)[源代码]¶ Compares the two images, pixel by pixel, and returns a new image containing the darker values. At least one of the images must have mode “1”.
out = min(image1, image2)
返回类型: Image
-
PIL.ImageChops.
difference
(image1, image2)[源代码]¶ Returns the absolute value of the pixel-by-pixel difference between the two images. At least one of the images must have mode “1”.
out = abs(image1 - image2)
返回类型: Image
-
PIL.ImageChops.
duplicate
(image)[源代码]¶ Copy a channel. Alias for
PIL.Image.Image.copy()
.返回类型: Image
-
PIL.ImageChops.
lighter
(image1, image2)[源代码]¶ Compares the two images, pixel by pixel, and returns a new image containing the lighter values. At least one of the images must have mode “1”.
out = max(image1, image2)
返回类型: Image
-
PIL.ImageChops.
logical_and
(image1, image2)[源代码]¶ Logical AND between two images. At least one of the images must have mode “1”.
out = ((image1 and image2) % MAX)
返回类型: Image
-
PIL.ImageChops.
logical_or
(image1, image2)[源代码]¶ Logical OR between two images. At least one of the images must have mode “1”.
out = ((image1 or image2) % MAX)
返回类型: Image
-
PIL.ImageChops.
logical_xor
(image1, image2)[源代码]¶ Logical XOR between two images. At least one of the images must have mode “1”.
out = ((bool(image1) != bool(image2)) % MAX)
返回类型: Image
-
PIL.ImageChops.
multiply
(image1, image2)[源代码]¶ Superimposes two images on top of each other.
If you multiply an image with a solid black image, the result is black. If you multiply with a solid white image, the image is unaffected. At least one of the images must have mode “1”.
out = image1 * image2 / MAX
返回类型: Image
-
PIL.ImageChops.
offset
(image, xoffset, yoffset=None)¶ Returns a copy of the image where data has been offset by the given distances. Data wraps around the edges. If yoffset is omitted, it is assumed to be equal to xoffset.
-
PIL.ImageChops.
screen
(image1, image2)[源代码]¶ Superimposes two inverted images on top of each other. At least one of the images must have mode “1”.
out = MAX - ((MAX - image1) * (MAX - image2) / MAX)
返回类型: Image
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.new()
and the ImageDraw
module, among
others.
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)
andrgb(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. - Hue-Saturation-Value (HSV) functions, given as
hsv(hue, saturation%, value%)
where hue and saturation are the same as HSL, and value is between 0% and 100% (black=0%, normal=100%). For example,hsv(0,100%,100%)
is pure red. This format is also known as Hue-Saturation-Brightness (HSB), and can be given ashsb(hue, saturation%, brightness%)
, where each of the values are used as they are in HSV. - Common HTML color names. The
ImageColor
module provides some 140 standard color names, based on the colors supported by the X Window system and most web browsers. color names are case insensitive. For example,red
andRed
both specify pure red.
ImageCms
Module¶
The ImageCms
module provides color profile management
support using the LittleCMS2 color management engine, based on Kevin
Cazabon’s PyCMS library.
-
class
PIL.ImageCms.
ImageCmsTransform
(input, output, input_mode, output_mode, intent=0, proof=None, proof_intent=3, flags=0)[源代码] Transform. This can be used with the procedural API, or with the standard Image.point() method.
Will return the output profile in the output.info[‘icc_profile’].
-
exception
PIL.ImageCms.
PyCMSError
[源代码] (pyCMS) Exception class. This is used for all errors in the pyCMS API.
-
PIL.ImageCms.
applyTransform
(im, transform, inPlace=0)[源代码] (pyCMS) Applies a transform to a given image.
If im.mode != transform.inMode, a PyCMSError is raised.
If inPlace == TRUE and transform.inMode != transform.outMode, a PyCMSError is raised.
If im.mode, transfer.inMode, or transfer.outMode is not supported by pyCMSdll or the profiles you used for the transform, a PyCMSError is raised.
If an error occurs while the transform is being applied, a PyCMSError is raised.
This function applies a pre-calculated transform (from ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles()) to an image. The transform can be used for multiple images, saving considerable calculation time if doing the same conversion multiple times.
If you want to modify im in-place instead of receiving a new image as the return value, set inPlace to TRUE. This can only be done if transform.inMode and transform.outMode are the same, because we can’t change the mode in-place (the buffer sizes for some modes are different). The default behavior is to return a new Image object of the same dimensions in mode transform.outMode.
参数: - im – A PIL Image object, and im.mode must be the same as the inMode supported by the transform.
- transform – A valid CmsTransform class object
- inPlace – Bool (1 == True, 0 or None == False). If True, im is modified in place and None is returned, if False, a new Image object with the transform applied is returned (and im is not changed). The default is False.
返回: Either None, or a new PIL Image object, depending on the value of inPlace. The profile will be returned in the image’s info[‘icc_profile’].
引发: PyCMSError –
-
PIL.ImageCms.
buildProofTransform
(inputProfile, outputProfile, proofProfile, inMode, outMode, renderingIntent=0, proofRenderingIntent=3, flags=16384)[源代码] (pyCMS) Builds an ICC transform mapping from the inputProfile to the outputProfile, but tries to simulate the result that would be obtained on the proofProfile device.
If the input, output, or proof profiles specified are not valid filenames, a PyCMSError will be raised.
If an error occurs during creation of the transform, a PyCMSError will be raised.
If inMode or outMode are not a mode supported by the outputProfile (or by pyCMS), a PyCMSError will be raised.
This function builds and returns an ICC transform from the inputProfile to the outputProfile, but tries to simulate the result that would be obtained on the proofProfile device using renderingIntent and proofRenderingIntent to determine what to do with out-of-gamut colors. This is known as “soft-proofing”. It will ONLY work for converting images that are in inMode to images that are in outMode color format (PIL mode, i.e. “RGB”, “RGBA”, “CMYK”, etc.).
Usage of the resulting transform object is exactly the same as with ImageCms.buildTransform().
Proof profiling is generally used when using an output device to get a good idea of what the final printed/displayed image would look like on the proofProfile device when it’s quicker and easier to use the output device for judging color. Generally, this means that the output device is a monitor, or a dye-sub printer (etc.), and the simulated device is something more expensive, complicated, or time consuming (making it difficult to make a real print for color judgement purposes).
Soft-proofing basically functions by adjusting the colors on the output device to match the colors of the device being simulated. However, when the simulated device has a much wider gamut than the output device, you may obtain marginal results.
参数: - inputProfile – String, as a valid filename path to the ICC input profile you wish to use for this transform, or a profile object
- outputProfile – String, as a valid filename path to the ICC output (monitor, usually) profile you wish to use for this transform, or a profile object
- proofProfile – String, as a valid filename path to the ICC proof profile you wish to use for this transform, or a profile object
- inMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”, “RGBA”, “CMYK”, etc.)
- outMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”, “RGBA”, “CMYK”, etc.)
- renderingIntent –
Integer (0-3) specifying the rendering intent you wish to use for the input->proof (simulated) transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT) ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1 ImageCms.INTENT_SATURATION = 2 ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3see the pyCMS documentation for details on rendering intents and what they do.
- proofRenderingIntent –
Integer (0-3) specifying the rendering intent you wish to use for proof->output transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT) ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1 ImageCms.INTENT_SATURATION = 2 ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3see the pyCMS documentation for details on rendering intents and what they do.
- flags – Integer (0-…) specifying additional flags
返回: A CmsTransform class object.
引发: PyCMSError –
-
PIL.ImageCms.
buildProofTransformFromOpenProfiles
(inputProfile, outputProfile, proofProfile, inMode, outMode, renderingIntent=0, proofRenderingIntent=3, flags=16384) (pyCMS) Builds an ICC transform mapping from the inputProfile to the outputProfile, but tries to simulate the result that would be obtained on the proofProfile device.
If the input, output, or proof profiles specified are not valid filenames, a PyCMSError will be raised.
If an error occurs during creation of the transform, a PyCMSError will be raised.
If inMode or outMode are not a mode supported by the outputProfile (or by pyCMS), a PyCMSError will be raised.
This function builds and returns an ICC transform from the inputProfile to the outputProfile, but tries to simulate the result that would be obtained on the proofProfile device using renderingIntent and proofRenderingIntent to determine what to do with out-of-gamut colors. This is known as “soft-proofing”. It will ONLY work for converting images that are in inMode to images that are in outMode color format (PIL mode, i.e. “RGB”, “RGBA”, “CMYK”, etc.).
Usage of the resulting transform object is exactly the same as with ImageCms.buildTransform().
Proof profiling is generally used when using an output device to get a good idea of what the final printed/displayed image would look like on the proofProfile device when it’s quicker and easier to use the output device for judging color. Generally, this means that the output device is a monitor, or a dye-sub printer (etc.), and the simulated device is something more expensive, complicated, or time consuming (making it difficult to make a real print for color judgement purposes).
Soft-proofing basically functions by adjusting the colors on the output device to match the colors of the device being simulated. However, when the simulated device has a much wider gamut than the output device, you may obtain marginal results.
参数: - inputProfile – String, as a valid filename path to the ICC input profile you wish to use for this transform, or a profile object
- outputProfile – String, as a valid filename path to the ICC output (monitor, usually) profile you wish to use for this transform, or a profile object
- proofProfile – String, as a valid filename path to the ICC proof profile you wish to use for this transform, or a profile object
- inMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”, “RGBA”, “CMYK”, etc.)
- outMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”, “RGBA”, “CMYK”, etc.)
- renderingIntent –
Integer (0-3) specifying the rendering intent you wish to use for the input->proof (simulated) transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT) ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1 ImageCms.INTENT_SATURATION = 2 ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3see the pyCMS documentation for details on rendering intents and what they do.
- proofRenderingIntent –
Integer (0-3) specifying the rendering intent you wish to use for proof->output transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT) ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1 ImageCms.INTENT_SATURATION = 2 ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3see the pyCMS documentation for details on rendering intents and what they do.
- flags – Integer (0-…) specifying additional flags
返回: A CmsTransform class object.
引发: PyCMSError –
-
PIL.ImageCms.
buildTransform
(inputProfile, outputProfile, inMode, outMode, renderingIntent=0, flags=0)[源代码] (pyCMS) Builds an ICC transform mapping from the inputProfile to the outputProfile. Use applyTransform to apply the transform to a given image.
If the input or output profiles specified are not valid filenames, a PyCMSError will be raised. If an error occurs during creation of the transform, a PyCMSError will be raised.
If inMode or outMode are not a mode supported by the outputProfile (or by pyCMS), a PyCMSError will be raised.
This function builds and returns an ICC transform from the inputProfile to the outputProfile using the renderingIntent to determine what to do with out-of-gamut colors. It will ONLY work for converting images that are in inMode to images that are in outMode color format (PIL mode, i.e. “RGB”, “RGBA”, “CMYK”, etc.).
Building the transform is a fair part of the overhead in ImageCms.profileToProfile(), so if you’re planning on converting multiple images using the same input/output settings, this can save you time. Once you have a transform object, it can be used with ImageCms.applyProfile() to convert images without the need to re-compute the lookup table for the transform.
The reason pyCMS returns a class object rather than a handle directly to the transform is that it needs to keep track of the PIL input/output modes that the transform is meant for. These attributes are stored in the “inMode” and “outMode” attributes of the object (which can be manually overridden if you really want to, but I don’t know of any time that would be of use, or would even work).
参数: - inputProfile – String, as a valid filename path to the ICC input profile you wish to use for this transform, or a profile object
- outputProfile – String, as a valid filename path to the ICC output profile you wish to use for this transform, or a profile object
- inMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”, “RGBA”, “CMYK”, etc.)
- outMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”, “RGBA”, “CMYK”, etc.)
- renderingIntent –
Integer (0-3) specifying the rendering intent you wish to use for the transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT) ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1 ImageCms.INTENT_SATURATION = 2 ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3see the pyCMS documentation for details on rendering intents and what they do.
- flags – Integer (0-…) specifying additional flags
返回: A CmsTransform class object.
引发: PyCMSError –
-
PIL.ImageCms.
buildTransformFromOpenProfiles
(inputProfile, outputProfile, inMode, outMode, renderingIntent=0, flags=0) (pyCMS) Builds an ICC transform mapping from the inputProfile to the outputProfile. Use applyTransform to apply the transform to a given image.
If the input or output profiles specified are not valid filenames, a PyCMSError will be raised. If an error occurs during creation of the transform, a PyCMSError will be raised.
If inMode or outMode are not a mode supported by the outputProfile (or by pyCMS), a PyCMSError will be raised.
This function builds and returns an ICC transform from the inputProfile to the outputProfile using the renderingIntent to determine what to do with out-of-gamut colors. It will ONLY work for converting images that are in inMode to images that are in outMode color format (PIL mode, i.e. “RGB”, “RGBA”, “CMYK”, etc.).
Building the transform is a fair part of the overhead in ImageCms.profileToProfile(), so if you’re planning on converting multiple images using the same input/output settings, this can save you time. Once you have a transform object, it can be used with ImageCms.applyProfile() to convert images without the need to re-compute the lookup table for the transform.
The reason pyCMS returns a class object rather than a handle directly to the transform is that it needs to keep track of the PIL input/output modes that the transform is meant for. These attributes are stored in the “inMode” and “outMode” attributes of the object (which can be manually overridden if you really want to, but I don’t know of any time that would be of use, or would even work).
参数: - inputProfile – String, as a valid filename path to the ICC input profile you wish to use for this transform, or a profile object
- outputProfile – String, as a valid filename path to the ICC output profile you wish to use for this transform, or a profile object
- inMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”, “RGBA”, “CMYK”, etc.)
- outMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”, “RGBA”, “CMYK”, etc.)
- renderingIntent –
Integer (0-3) specifying the rendering intent you wish to use for the transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT) ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1 ImageCms.INTENT_SATURATION = 2 ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3see the pyCMS documentation for details on rendering intents and what they do.
- flags – Integer (0-…) specifying additional flags
返回: A CmsTransform class object.
引发: PyCMSError –
-
PIL.ImageCms.
createProfile
(colorSpace, colorTemp=-1)[源代码] (pyCMS) Creates a profile.
If colorSpace not in [“LAB”, “XYZ”, “sRGB”], a PyCMSError is raised
If using LAB and colorTemp != a positive integer, a PyCMSError is raised.
If an error occurs while creating the profile, a PyCMSError is raised.
Use this function to create common profiles on-the-fly instead of having to supply a profile on disk and knowing the path to it. It returns a normal CmsProfile object that can be passed to ImageCms.buildTransformFromOpenProfiles() to create a transform to apply to images.
参数: - colorSpace – String, the color space of the profile you wish to create. Currently only “LAB”, “XYZ”, and “sRGB” are supported.
- colorTemp – Positive integer for the white point for the profile, in degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50 illuminant if omitted (5000k). colorTemp is ONLY applied to LAB profiles, and is ignored for XYZ and sRGB.
返回: A CmsProfile class object
引发: PyCMSError –
-
PIL.ImageCms.
getDefaultIntent
(profile)[源代码] (pyCMS) Gets the default intent name for the given profile.
If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.
If an error occurs while trying to obtain the default intent, a PyCMSError is raised.
Use this function to determine the default (and usually best optimized) rendering intent for this profile. Most profiles support multiple rendering intents, but are intended mostly for one type of conversion. If you wish to use a different intent than returned, use ImageCms.isIntentSupported() to verify it will work first.
参数: profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. 返回: Integer 0-3 specifying the default rendering intent for this profile. ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT) ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1 ImageCms.INTENT_SATURATION = 2 ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3- see the pyCMS documentation for details on rendering intents and what
- they do.
引发: PyCMSError –
-
PIL.ImageCms.
getOpenProfile
(profileFilename)[源代码] (pyCMS) Opens an ICC profile file.
The PyCMSProfile object can be passed back into pyCMS for use in creating transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
If profileFilename is not a valid filename for an ICC profile, a PyCMSError will be raised.
参数: profileFilename – String, as a valid filename path to the ICC profile you wish to open, or a file-like object. 返回: A CmsProfile class object. 引发: PyCMSError –
-
PIL.ImageCms.
getProfileCopyright
(profile)[源代码] (pyCMS) Gets the copyright for the given profile.
If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.
If an error occurs while trying to obtain the copyright tag, a PyCMSError is raised
Use this function to obtain the information stored in the profile’s copyright tag.
参数: profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. 返回: A string containing the internal profile information stored in an ICC tag. 引发: PyCMSError –
-
PIL.ImageCms.
getProfileDescription
(profile)[源代码] (pyCMS) Gets the description for the given profile.
If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.
If an error occurs while trying to obtain the description tag, a PyCMSError is raised
Use this function to obtain the information stored in the profile’s description tag.
参数: profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. 返回: A string containing the internal profile information stored in an ICC tag. 引发: PyCMSError –
-
PIL.ImageCms.
getProfileInfo
(profile)[源代码] (pyCMS) Gets the internal product information for the given profile.
If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.
If an error occurs while trying to obtain the info tag, a PyCMSError is raised
Use this function to obtain the information stored in the profile’s info tag. This often contains details about the profile, and how it was created, as supplied by the creator.
参数: profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. 返回: A string containing the internal profile information stored in an ICC tag. 引发: PyCMSError –
-
PIL.ImageCms.
getProfileManufacturer
(profile)[源代码] (pyCMS) Gets the manufacturer for the given profile.
If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.
If an error occurs while trying to obtain the manufacturer tag, a PyCMSError is raised
Use this function to obtain the information stored in the profile’s manufacturer tag.
参数: profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. 返回: A string containing the internal profile information stored in an ICC tag. 引发: PyCMSError –
-
PIL.ImageCms.
getProfileModel
(profile)[源代码] (pyCMS) Gets the model for the given profile.
If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.
If an error occurs while trying to obtain the model tag, a PyCMSError is raised
Use this function to obtain the information stored in the profile’s model tag.
参数: profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. 返回: A string containing the internal profile information stored in an ICC tag. 引发: PyCMSError –
-
PIL.ImageCms.
getProfileName
(profile)[源代码] (pyCMS) Gets the internal product name for the given profile.
If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised If an error occurs while trying to obtain the name tag, a PyCMSError is raised.
Use this function to obtain the INTERNAL name of the profile (stored in an ICC tag in the profile itself), usually the one used when the profile was originally created. Sometimes this tag also contains additional information supplied by the creator.
参数: profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile. 返回: A string containing the internal name of the profile as stored in an ICC tag. 引发: PyCMSError –
-
PIL.ImageCms.
get_display_profile
(handle=None)[源代码] (experimental) Fetches the profile for the current display device. :returns: None if the profile is not known.
-
PIL.ImageCms.
isIntentSupported
(profile, intent, direction)[源代码] (pyCMS) Checks if a given intent is supported.
Use this function to verify that you can use your desired renderingIntent with profile, and that profile can be used for the input/output/proof profile as you desire.
Some profiles are created specifically for one “direction”, can cannot be used for others. Some profiles can only be used for certain rendering intents… so it’s best to either verify this before trying to create a transform with them (using this function), or catch the potential PyCMSError that will occur if they don’t support the modes you select.
参数: - profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile.
- intent –
Integer (0-3) specifying the rendering intent you wish to use with this profile
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT) ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1 ImageCms.INTENT_SATURATION = 2 ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3- see the pyCMS documentation for details on rendering intents and what
- they do.
- direction –
Integer specifying if the profile is to be used for input, output, or proof
INPUT = 0 (or use ImageCms.DIRECTION_INPUT) OUTPUT = 1 (or use ImageCms.DIRECTION_OUTPUT) PROOF = 2 (or use ImageCms.DIRECTION_PROOF)
返回: 1 if the intent/direction are supported, -1 if they are not.
引发: PyCMSError –
-
PIL.ImageCms.
profileToProfile
(im, inputProfile, outputProfile, renderingIntent=0, outputMode=None, inPlace=0, flags=0)[源代码] (pyCMS) Applies an ICC transformation to a given image, mapping from inputProfile to outputProfile.
If the input or output profiles specified are not valid filenames, a PyCMSError will be raised. If inPlace == TRUE and outputMode != im.mode, a PyCMSError will be raised. If an error occurs during application of the profiles, a PyCMSError will be raised. If outputMode is not a mode supported by the outputProfile (or by pyCMS), a PyCMSError will be raised.
This function applies an ICC transformation to im from inputProfile’s color space to outputProfile’s color space using the specified rendering intent to decide how to handle out-of-gamut colors.
OutputMode can be used to specify that a color mode conversion is to be done using these profiles, but the specified profiles must be able to handle that mode. I.e., if converting im from RGB to CMYK using profiles, the input profile must handle RGB data, and the output profile must handle CMYK data.
参数: - im – An open PIL image object (i.e. Image.new(…) or Image.open(…), etc.)
- inputProfile – String, as a valid filename path to the ICC input profile you wish to use for this image, or a profile object
- outputProfile – String, as a valid filename path to the ICC output profile you wish to use for this image, or a profile object
- renderingIntent –
Integer (0-3) specifying the rendering intent you wish to use for the transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT) ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1 ImageCms.INTENT_SATURATION = 2 ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3see the pyCMS documentation for details on rendering intents and what they do.
- outputMode – A valid PIL mode for the output image (i.e. “RGB”, “CMYK”, etc.). Note: if rendering the image “inPlace”, outputMode MUST be the same mode as the input, or omitted completely. If omitted, the outputMode will be the same as the mode of the input image (im.mode)
- inPlace – Boolean (1 = True, None or 0 = False). If True, the original image is modified in-place, and None is returned. If False (default), a new Image object is returned with the transform applied.
- flags – Integer (0-…) specifying additional flags
返回: Either None or a new PIL image object, depending on value of inPlace
引发: PyCMSError –
-
PIL.ImageCms.
versions
()[源代码] (pyCMS) Fetches versions.
CmsProfile¶
The ICC color profiles are wrapped in an instance of the class
CmsProfile
. The specification ICC.1:2010 contains more
information about the meaning of the values in ICC profiles.
For convenience, all XYZ-values are also given as xyY-values (so they can be easily displayed in a chromaticity diagram, for example).
-
class
PIL.ImageCms.
CmsProfile
¶ -
creation_date
¶ Date and time this profile was first created (see 7.2.1 of ICC.1:2010).
Type: datetime.datetime
orNone
-
icc_version
¶ Same as
version
, but in encoded format (see 7.2.4 of ICC.1:2010).
-
device_class
¶ 4-character string identifying the profile class. One of
scnr
,mntr
,prtr
,link
,spac
,abst
,nmcl
(see 7.2.5 of ICC.1:2010 for details).Type: string
-
xcolor_space
¶ 4-character string (padded with whitespace) identifying the color space, e.g.
XYZ␣
,RGB␣
orCMYK
(see 7.2.6 of ICC.1:2010 for details).Note that the deprecated attribute
color_space
contains an interpreted (non-padded) variant of this (but can be empty on unknown input).Type: string
-
connection_space
¶ 4-character string (padded with whitespace) identifying the color space on the B-side of the transform (see 7.2.7 of ICC.1:2010 for details).
Note that the deprecated attribute
pcs
contains an interpreted (non-padded) variant of this (but can be empty on unknown input).Type: string
-
header_flags
¶ The encoded header flags of the profile (see 7.2.11 of ICC.1:2010 for details).
Type: int
-
header_manufacturer
¶ 4-character string (padded with whitespace) identifying the device manufacturer, which shall match the signature contained in the appropriate section of the ICC signature registry found at www.color.org (see 7.2.12 of ICC.1:2010).
Type: string
-
header_model
¶ 4-character string (padded with whitespace) identifying the device model, which shall match the signature contained in the appropriate section of the ICC signature registry found at www.color.org (see 7.2.13 of ICC.1:2010).
Type: string
-
attributes
¶ Flags used to identify attributes unique to the particular device setup for which the profile is applicable (see 7.2.14 of ICC.1:2010 for details).
Type: int
-
rendering_intent
¶ The rendering intent to use when combining this profile with another profile (usually overridden at run-time, but provided here for DeviceLink and embedded source profiles, see 7.2.15 of ICC.1:2010).
One of
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC
,ImageCms.INTENT_PERCEPTUAL
,ImageCms.INTENT_RELATIVE_COLORIMETRIC
andImageCms.INTENT_SATURATION
.Type: int
-
profile_id
¶ A sequence of 16 bytes identifying the profile (via a specially constructed MD5 sum), or 16 binary zeroes if the profile ID has not been calculated (see 7.2.18 of ICC.1:2010).
Type: bytes
-
copyright
¶ The text copyright information for the profile (see 9.2.21 of ICC.1:2010).
Type: unicode
orNone
-
manufacturer
¶ The (English) display string for the device manufacturer (see 9.2.22 of ICC.1:2010).
Type: unicode
orNone
-
model
¶ The (English) display string for the device model of the device for which this profile is created (see 9.2.23 of ICC.1:2010).
Type: unicode
orNone
-
profile_description
¶ The (English) display string for the profile description (see 9.2.41 of ICC.1:2010).
Type: unicode
orNone
-
target
¶ The name of the registered characterization data set, or the measurement data for a characterization target (see 9.2.14 of ICC.1:2010).
Type: unicode
orNone
-
red_colorant
¶ The first column in the matrix used in matrix/TRC transforms (see 9.2.44 of ICC.1:2010).
Type: ((X, Y, Z), (x, y, Y))
orNone
-
green_colorant
¶ The second column in the matrix used in matrix/TRC transforms (see 9.2.30 of ICC.1:2010).
Type: ((X, Y, Z), (x, y, Y))
orNone
-
blue_colorant
¶ The third column in the matrix used in matrix/TRC transforms (see 9.2.4 of ICC.1:2010).
Type: ((X, Y, Z), (x, y, Y))
orNone
-
luminance
¶ The absolute luminance of emissive devices in candelas per square metre as described by the Y channel (see 9.2.32 of ICC.1:2010).
Type: ((X, Y, Z), (x, y, Y))
orNone
-
chromaticity
¶ The data of the phosphor/colorant chromaticity set used (red, green and blue channels, see 9.2.16 of ICC.1:2010).
Type: ((x, y, Y), (x, y, Y), (x, y, Y))
orNone
-
chromatic_adaption
¶ The chromatic adaption matrix converts a color measured using the actual illumination conditions and relative to the actual adopted white, to an color relative to the PCS adopted white, with complete adaptation from the actual adopted white chromaticity to the PCS adopted white chromaticity (see 9.2.15 of ICC.1:2010).
Two matrices are returned, one in (X, Y, Z) space and one in (x, y, Y) space.
Type: 2-tuple of 3-tuple, the first with (X, Y, Z) and the second with (x, y, Y) values
-
colorant_table
¶ This tag identifies the colorants used in the profile by a unique name and set of PCSXYZ or PCSLAB values (see 9.2.19 of ICC.1:2010).
Type: list of strings
-
colorant_table_out
¶ This tag identifies the colorants used in the profile by a unique name and set of PCSLAB values (for DeviceLink profiles only, see 9.2.19 of ICC.1:2010).
Type: list of strings
-
colorimetric_intent
¶ 4-character string (padded with whitespace) identifying the image state of PCS colorimetry produced using the colorimetric intent transforms (see 9.2.20 of ICC.1:2010 for details).
Type: string
orNone
-
perceptual_rendering_intent_gamut
¶ 4-character string (padded with whitespace) identifying the (one) standard reference medium gamut (see 9.2.37 of ICC.1:2010 for details).
Type: string
orNone
-
saturation_rendering_intent_gamut
¶ 4-character string (padded with whitespace) identifying the (one) standard reference medium gamut (see 9.2.37 of ICC.1:2010 for details).
Type: string
orNone
-
technology
¶ 4-character string (padded with whitespace) identifying the device technology (see 9.2.47 of ICC.1:2010 for details).
Type: string
orNone
-
media_black_point
¶ This tag specifies the media black point and is used for generating absolute colorimetry.
This tag was available in ICC 3.2, but it is removed from version 4.
Type: ((X, Y, Z), (x, y, Y))
orNone
-
media_white_point_temperature
¶ Calculates the white point temperature (see the LCMS documentation for more information).
Type: float
orNone
-
viewing_condition
¶ The (English) display string for the viewing conditions (see 9.2.48 of ICC.1:2010).
Type: unicode
orNone
-
screening_description
¶ The (English) display string for the screening conditions.
This tag was available in ICC 3.2, but it is removed from version 4.
Type: unicode
orNone
-
red_primary
¶ The XYZ-transformed of the RGB primary color red (1, 0, 0).
Type: ((X, Y, Z), (x, y, Y))
orNone
-
green_primary
¶ The XYZ-transformed of the RGB primary color green (0, 1, 0).
Type: ((X, Y, Z), (x, y, Y))
orNone
-
blue_primary
¶ The XYZ-transformed of the RGB primary color blue (0, 0, 1).
Type: ((X, Y, Z), (x, y, Y))
orNone
-
is_matrix_shaper
¶ True if this profile is implemented as a matrix shaper (see documentation on LCMS).
Type: bool
-
clut
¶ Returns a dictionary of all supported intents and directions for the CLUT model.
The dictionary is indexed by intents (
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC
,ImageCms.INTENT_PERCEPTUAL
,ImageCms.INTENT_RELATIVE_COLORIMETRIC
andImageCms.INTENT_SATURATION
).The values are 3-tuples indexed by directions (
ImageCms.DIRECTION_INPUT
,ImageCms.DIRECTION_OUTPUT
,ImageCms.DIRECTION_PROOF
).The elements of the tuple are booleans. If the value is
True
, that intent is supported for that direction.Type: dict
of boolean 3-tuples
-
intent_supported
¶ Returns a dictionary of all supported intents and directions.
The dictionary is indexed by intents (
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC
,ImageCms.INTENT_PERCEPTUAL
,ImageCms.INTENT_RELATIVE_COLORIMETRIC
andImageCms.INTENT_SATURATION
).The values are 3-tuples indexed by directions (
ImageCms.DIRECTION_INPUT
,ImageCms.DIRECTION_OUTPUT
,ImageCms.DIRECTION_PROOF
).The elements of the tuple are booleans. If the value is
True
, that intent is supported for that direction.Type: dict
of boolean 3-tuples
-
color_space
¶ Deprecated but retained for backwards compatibility. Interpreted value of
xcolor_space
. May be the empty string if value could not be decoded.Type: string
-
pcs
¶ Deprecated but retained for backwards compatibility. Interpreted value of
connection_space
. May be the empty string if value could not be decoded.Type: string
-
product_model
¶ Deprecated but retained for backwards compatibility. ASCII-encoded value of
model
.Type: string
-
product_manufacturer
¶ Deprecated but retained for backwards compatibility. ASCII-encoded value of
manufacturer
.Type: string
-
product_copyright
¶ Deprecated but retained for backwards compatibility. ASCII-encoded value of
copyright
.Type: string
-
product_description
¶ Deprecated but retained for backwards compatibility. ASCII-encoded value of
profile_description
.Type: string
-
product_desc
¶ Deprecated but retained for backwards compatibility. ASCII-encoded value of
profile_description
.This alias of
product_description
used to contain a derived informative string about the profile, depending on the value of the description, copyright, manufacturer and model fields).Type: string
There is one function defined on the class:
-
is_intent_supported
(intent, direction)¶ Returns if the intent is supported for the given direction.
Note that you can also get this information for all intents and directions with
intent_supported
.参数: - intent – One of
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC
,ImageCms.INTENT_PERCEPTUAL
,ImageCms.INTENT_RELATIVE_COLORIMETRIC
andImageCms.INTENT_SATURATION
. - direction – One of
ImageCms.DIRECTION_INPUT
,ImageCms.DIRECTION_OUTPUT
andImageCms.DIRECTION_PROOF
返回: Boolean if the intent and direction is supported.
- intent – One of
-
ImageDraw
Module¶
The ImageDraw
module provides simple 2D graphics for
Image
objects. You can use this module to create new
images, annotate or retouch existing images, and to generate graphics on the
fly for web use.
For a more advanced drawing library for PIL, see the aggdraw module.
Example: Draw a gray cross over an image¶
from PIL import Image, ImageDraw
im = Image.open("hopper.jpg")
draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=128)
draw.line((0, im.size[1], im.size[0], 0), fill=128)
# write to stdout
im.save(sys.stdout, "PNG")
Concepts¶
Coordinates¶
The graphics interface uses the same coordinate system as PIL itself, with (0, 0) in the upper left corner. Any pixels drawn outside of the image bounds will be discarded.
Colors¶
To specify colors, you can use numbers or tuples just as you would use with
PIL.Image.new()
or PIL.Image.Image.putpixel()
. For “1”,
“L”, and “I” images, use integers. For “RGB” images, use a 3-tuple containing
integer values. For “F” images, use integer or floating point values.
For palette images (mode “P”), use integers as color indexes. In 1.1.4 and later, you can also use RGB 3-tuples or color names (see below). The drawing layer will automatically assign color indexes, as long as you don’t draw with more than 256 colors.
Color Names¶
See Color Names for the color names supported by Pillow.
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 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.
Example: Draw Partial Opacity Text¶
from PIL import Image, ImageDraw, ImageFont
# get an image
base = Image.open('Pillow/Tests/images/hopper.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()
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.
参数: - 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.
Methods¶
-
PIL.ImageDraw.ImageDraw.
getfont
()¶ Get the current default font.
返回: An image font.
-
PIL.ImageDraw.ImageDraw.
arc
(xy, start, end, fill=None, width=0)¶ Draws an arc (a portion of a circle outline) between the start and end angles, inside the given bounding box.
参数: - xy – Two points to define the bounding box. Sequence of
[(x0, y0), (x1, y1)]
or[x0, y0, x1, y1]
, wherex1 >= x0
andy1 >= y0
. - 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.
- width –
The line width, in pixels.
5.3.0 新版功能.
- xy – Two points to define the bounding box. Sequence of
-
PIL.ImageDraw.ImageDraw.
bitmap
(xy, bitmap, fill=None)¶ Draws a bitmap (mask) at the given position, using the current fill color for the non-zero portions. The bitmap should be a valid transparency mask (mode “1”) or matte (mode “L” or “RGBA”).
This is equivalent to doing
image.paste(xy, color, bitmap)
.To paste pixel data into an image, use the
paste()
method on the image itself.
-
PIL.ImageDraw.ImageDraw.
chord
(xy, start, end, fill=None, outline=None, width=0)¶ Same as
arc()
, but connects the end points with a straight line.参数: - xy – Two points to define the bounding box. Sequence of
[(x0, y0), (x1, y1)]
or[x0, y0, x1, y1]
, wherex1 >= x0
andy1 >= y0
. - outline – Color to use for the outline.
- fill – Color to use for the fill.
- width –
The line width, in pixels.
5.3.0 新版功能.
- xy – Two points to define the bounding box. Sequence of
-
PIL.ImageDraw.ImageDraw.
ellipse
(xy, fill=None, outline=None, width=0)¶ Draws an ellipse inside the given bounding box.
参数: - xy – Two points to define the bounding box. Sequence of either
[(x0, y0), (x1, y1)]
or[x0, y0, x1, y1]
, wherex1 >= x0
andy1 >= y0
. - outline – Color to use for the outline.
- fill – Color to use for the fill.
- width –
The line width, in pixels.
5.3.0 新版功能.
- xy – Two points to define the bounding box. Sequence of either
-
PIL.ImageDraw.ImageDraw.
line
(xy, fill=None, width=0, joint=None)¶ Draws a line between the coordinates in the xy list.
参数: - 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.
1.1.5 新版功能.
注解
This option was broken until version 1.1.6.
- joint –
- Joint type between a sequence of lines. It can be “curve”,
- for rounded edges, or None.
5.3.0 新版功能.
- xy – Sequence of either 2-tuples like
-
PIL.ImageDraw.ImageDraw.
pieslice
(xy, start, end, fill=None, outline=None, width=0)¶ Same as arc, but also draws straight lines between the end points and the center of the bounding box.
参数: - xy – Two points to define the bounding box. Sequence of
[(x0, y0), (x1, y1)]
or[x0, y0, x1, y1]
, wherex1 >= x0
andy1 >= y0
. - 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 fill.
- outline – Color to use for the outline.
- width –
The line width, in pixels.
5.3.0 新版功能.
- xy – Two points to define the bounding box. Sequence of
-
PIL.ImageDraw.ImageDraw.
point
(xy, fill=None)¶ Draws points (individual pixels) at the given coordinates.
参数: - 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.
- xy – Sequence of either 2-tuples like
-
PIL.ImageDraw.ImageDraw.
polygon
(xy, fill=None, outline=None)¶ Draws a polygon.
The polygon outline consists of straight lines between the given coordinates, plus a straight line between the last and the first coordinate.
参数: - 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.
- xy – Sequence of either 2-tuples like
-
PIL.ImageDraw.ImageDraw.
rectangle
(xy, fill=None, outline=None, width=0)¶ Draws a rectangle.
参数: - xy – Two points to define the bounding box. Sequence of either
[(x0, y0), (x1, y1)]
or[x0, y0, x1, y1]
. The second point is just outside the drawn rectangle. - outline – Color to use for the outline.
- fill – Color to use for the fill.
- width –
The line width, in pixels.
5.3.0 新版功能.
- xy – Two points to define the bounding box. Sequence of either
-
PIL.ImageDraw.ImageDraw.
shape
(shape, fill=None, outline=None)¶ 警告
This method is experimental.
Draw a shape.
-
PIL.ImageDraw.ImageDraw.
text
(xy, text, fill=None, font=None, anchor=None, spacing=0, align="left", direction=None, features=None, language=None, stroke_width=0, stroke_fill=None)¶ Draws the string at the given position.
参数: - xy – Top left corner of the text.
- text – Text to be drawn. If it contains any newline characters, the text is passed on to multiline_text()
- fill – Color to use for the text.
- font – An
ImageFont
instance. - spacing – If the text is passed on to multiline_text(), the number of pixels between lines.
- align – If the text is passed on to multiline_text(), “left”, “center” or “right”.
- direction –
Direction of the text. It can be ‘rtl’ (right to left), ‘ltr’ (left to right) or ‘ttb’ (top to bottom). Requires libraqm.
4.2.0 新版功能.
- features –
A list of OpenType font features to be used during text layout. This is usually used to turn on optional font features that are not enabled by default, for example ‘dlig’ or ‘ss01’, but can be also used to turn off default font features for example ‘-liga’ to disable ligatures or ‘-kern’ to disable kerning. To get all supported features, see https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm.
4.2.0 新版功能.
- language –
Language of the text. Different languages may use different glyph shapes or ligatures. This parameter tells the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a BCP 47 language code <https://www.w3.org/International/articles/language-tags/> Requires libraqm.
6.0.0 新版功能.
- stroke_width –
The width of the text stroke.
6.2.0 新版功能.
- stroke_fill –
- Color to use for the text stroke. If not given, will default to
- the
fill
parameter.
6.2.0 新版功能.
-
PIL.ImageDraw.ImageDraw.
multiline_text
(xy, text, fill=None, font=None, anchor=None, spacing=0, align="left", direction=None, features=None, language=None)¶ Draws the string at the given position.
参数: - xy – Top left corner of the text.
- text – Text to be drawn.
- fill – Color to use for the text.
- font – An
ImageFont
instance. - spacing – The number of pixels between lines.
- align – “left”, “center” or “right”.
- direction –
Direction of the text. It can be ‘rtl’ (right to left), ‘ltr’ (left to right) or ‘ttb’ (top to bottom). Requires libraqm.
4.2.0 新版功能.
- features –
A list of OpenType font features to be used during text layout. This is usually used to turn on optional font features that are not enabled by default, for example ‘dlig’ or ‘ss01’, but can be also used to turn off default font features for example ‘-liga’ to disable ligatures or ‘-kern’ to disable kerning. To get all supported features, see https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm.
4.2.0 新版功能.
- language –
Language of the text. Different languages may use different glyph shapes or ligatures. This parameter tells the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a BCP 47 language code <https://www.w3.org/International/articles/language-tags/> Requires libraqm.
6.0.0 新版功能.
-
PIL.ImageDraw.ImageDraw.
textsize
(text, font=None, spacing=4, direction=None, features=None, language=None, stroke_width=0)¶ Return the size of the given string, in pixels.
参数: - text – Text to be measured. If it contains any newline characters, the text is passed on to multiline_textsize()
- font – An
ImageFont
instance. - spacing – If the text is passed on to multiline_textsize(), the number of pixels between lines.
- direction –
Direction of the text. It can be ‘rtl’ (right to left), ‘ltr’ (left to right) or ‘ttb’ (top to bottom). Requires libraqm.
4.2.0 新版功能.
- features –
A list of OpenType font features to be used during text layout. This is usually used to turn on optional font features that are not enabled by default, for example ‘dlig’ or ‘ss01’, but can be also used to turn off default font features for example ‘-liga’ to disable ligatures or ‘-kern’ to disable kerning. To get all supported features, see https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm.
4.2.0 新版功能.
- language –
Language of the text. Different languages may use different glyph shapes or ligatures. This parameter tells the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a BCP 47 language code <https://www.w3.org/International/articles/language-tags/> Requires libraqm.
6.0.0 新版功能.
- stroke_width –
The width of the text stroke.
6.2.0 新版功能.
-
PIL.ImageDraw.ImageDraw.
multiline_textsize
(text, font=None, spacing=4, direction=None, features=None, language=None, stroke_width=0)¶ Return the size of the given string, in pixels.
参数: - text – Text to be measured.
- font – An
ImageFont
instance. - spacing – The number of pixels between lines.
- direction –
Direction of the text. It can be ‘rtl’ (right to left), ‘ltr’ (left to right) or ‘ttb’ (top to bottom). Requires libraqm.
4.2.0 新版功能.
- features –
A list of OpenType font features to be used during text layout. This is usually used to turn on optional font features that are not enabled by default, for example ‘dlig’ or ‘ss01’, but can be also used to turn off default font features for example ‘-liga’ to disable ligatures or ‘-kern’ to disable kerning. To get all supported features, see https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist Requires libraqm.
4.2.0 新版功能.
- language –
Language of the text. Different languages may use different glyph shapes or ligatures. This parameter tells the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a BCP 47 language code <https://www.w3.org/International/articles/language-tags/> Requires libraqm.
6.0.0 新版功能.
- stroke_width –
The width of the text stroke.
6.2.0 新版功能.
-
PIL.ImageDraw.
getdraw
(im=None, hints=None)¶ 警告
This method is experimental.
A more advanced 2D drawing interface for PIL images, based on the WCK interface.
参数: - im – The image to draw in.
- hints – An optional list of hints.
返回: A (drawing context, drawing resource factory) tuple.
-
PIL.ImageDraw.
floodfill
(image, xy, value, border=None, thresh=0)¶ 警告
This method is experimental.
Fills a bounded region with a given color.
参数: - image – Target image.
- xy – Seed position (a 2-item coordinate tuple).
- value – Fill color.
- border – Optional border value. If given, the region consists of pixels with a color different from the border color. If not given, the region consists of pixels having the same color as the seed pixel.
- thresh – Optional threshold value which specifies a maximum tolerable difference of a pixel value from the ‘background’ in order for it to be replaced. Useful for filling regions of non- homogeneous, but similar, colors.
ImageEnhance
Module¶
The ImageEnhance
module contains a number of classes that can be used
for image enhancement.
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.
Classes¶
All enhancement classes implement a common interface, containing a single method:
-
class
PIL.ImageEnhance.
_Enhance
¶ -
.. py:method:: enhance(factor)
Returns an enhanced image.
param factor: A floating point value controlling the enhancement. Factor 1.0 always returns a copy of the original image, lower factors mean less color (brightness, contrast, etc), and higher values more. There are no restrictions on this value.
-
class
PIL.ImageEnhance.
Color
(image)¶ Adjust image color balance.
This class can be used to adjust the colour balance of an image, in a manner similar to the controls on a colour TV set. An enhancement factor of 0.0 gives a black and white image. A factor of 1.0 gives the original image.
-
class
PIL.ImageEnhance.
Contrast
(image)¶ Adjust image contrast.
This class can be used to control the contrast of an image, similar to the contrast control on a TV set. An enhancement factor of 0.0 gives a solid grey image. A factor of 1.0 gives the original image.
-
class
PIL.ImageEnhance.
Brightness
(image)¶ Adjust image brightness.
This class can be used to control the brightness of an image. An enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the original image.
-
class
PIL.ImageEnhance.
Sharpness
(image)¶ Adjust image sharpness.
This class can be used to adjust the sharpness of an image. An enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the original image, and a factor of 2.0 gives a sharpened image.
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.
Example: Parse an image¶
from PIL import ImageFile
fp = open("hopper.pgm", "rb")
p = ImageFile.Parser()
while 1:
s = fp.read(1024)
if not s:
break
p.feed(s)
im = p.close()
im.save("copy.jpg")
Parser
¶
-
class
PIL.ImageFile.
Parser
[源代码]¶ Incremental image parser. This class implements the standard feed/close consumer interface.
-
close
()[源代码]¶ (Consumer) Close the stream.
返回: An image object. 引发: IOError – If the parser failed to parse the image file either because it cannot be identified or cannot be decoded.
-
PyDecoder
¶
-
class
PIL.ImageFile.
PyDecoder
[源代码]¶ Python implementation of a format decoder. Override this class and add the decoding logic in the decode method.
See Writing Your Own File Decoder in Python
-
decode
(buffer)[源代码]¶ Override to perform the decoding process.
参数: buffer – A bytes object with the data to be decoded. If handles_eof is set, then buffer will be empty and self.fd will be set. 返回: A tuple of (bytes consumed, errcode). If finished with decoding return <0 for the bytes consumed. Err codes are from ERRORS
-
init
(args)[源代码]¶ Override to perform decoder specific initialization
参数: args – Array of args items from the tile entry 返回: None
-
set_as_raw
(data, rawmode=None)[源代码]¶ Convenience method to set the internal image from a stream of raw data
参数: - data – Bytes to be set
- rawmode – The rawmode to be used for the decoder. If not specified, it will default to the mode of the image
返回: None
-
ImageFilter
Module¶
The ImageFilter
module contains definitions for a pre-defined set of
filters, which can be be used with the Image.filter()
method.
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)
Filters¶
The current version of the library provides the following set of predefined image enhancement filters:
- BLUR
- CONTOUR
- DETAIL
- EDGE_ENHANCE
- EDGE_ENHANCE_MORE
- EMBOSS
- FIND_EDGES
- SHARPEN
- SMOOTH
- SMOOTH_MORE
-
class
PIL.ImageFilter.
Color3DLUT
(size, table, channels=3, target_mode=None, **kwargs)[源代码]¶ Three-dimensional color lookup table.
Transforms 3-channel pixels using the values of the channels as coordinates in the 3D lookup table and interpolating the nearest elements.
This method allows you to apply almost any color transformation in constant time by using pre-calculated decimated tables.
5.2.0 新版功能.
参数: - size – Size of the table. One int or tuple of (int, int, int). Minimal size in any dimension is 2, maximum is 65.
- table – Flat lookup table. A list of
channels * size**3
float elements or a list ofsize**3
channels-sized tuples with floats. Channels are changed first, then first dimension, then second, then third. Value 0.0 corresponds lowest value of output, 1.0 highest. - channels – Number of channels in the table. Could be 3 or 4. Default is 3.
- target_mode – A mode for the result image. Should have not less
than
channels
channels. Default isNone
, which means that mode wouldn’t be changed.
-
classmethod
generate
(size, callback, channels=3, target_mode=None)[源代码]¶ Generates new LUT using provided callback.
参数: - size – Size of the table. Passed to the constructor.
- callback – Function with three parameters which correspond
three color channels. Will be called
size**3
times with values from 0.0 to 1.0 and should return a tuple withchannels
elements. - channels – The number of channels which should return callback.
- target_mode – Passed to the constructor of the resulting lookup table.
-
transform
(callback, with_normals=False, channels=None, target_mode=None)[源代码]¶ Transforms the table values using provided callback and returns a new LUT with altered values.
参数: - callback – A function which takes old lookup table values
and returns a new set of values. The number
of arguments which function should take is
self.channels
or3 + self.channels
ifwith_normals
flag is set. Should return a tuple ofself.channels
orchannels
elements if it is set. - with_normals – If true,
callback
will be called with coordinates in the color cube as the first three arguments. Otherwise,callback
will be called only with actual color values. - channels – The number of channels in the resulting lookup table.
- target_mode – Passed to the constructor of the resulting lookup table.
- callback – A function which takes old lookup table values
and returns a new set of values. The number
of arguments which function should take is
-
class
PIL.ImageFilter.
BoxBlur
(radius)[源代码]¶ Blurs the image by setting each pixel to the average value of the pixels in a square box extending radius pixels in each direction. Supports float radius of arbitrary size. Uses an optimized implementation which runs in linear time relative to the size of the image for any radius value.
参数: radius – Size of the box in one direction. Radius 0 does not blur, returns an identical image. Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total.
-
class
PIL.ImageFilter.
UnsharpMask
(radius=2, percent=150, threshold=3)[源代码]¶ Unsharp mask filter.
See Wikipedia’s entry on digital unsharp masking for an explanation of the parameters.
参数: - radius – Blur Radius
- percent – Unsharp strength, in percent
- threshold – Threshold controls the minimum brightness change that will be sharpened
-
class
PIL.ImageFilter.
Kernel
(size, kernel, scale=None, offset=0)[源代码]¶ Create a convolution kernel. The current version only supports 3x3 and 5x5 integer and floating point kernels.
In the current version, kernels can only be applied to “L” and “RGB” images.
参数: - 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.
参数: - 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.
参数: 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.
参数: 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.
参数: size – The kernel size, in pixels.
-
class
PIL.ImageFilter.
ModeFilter
(size=3)[源代码]¶ Create a mode filter. Picks the most frequent pixel value in a box with the given size. Pixel values that occur only once or twice are ignored; if no pixel value occurs more than twice, the original pixel value is preserved.
参数: size – The kernel size, in pixels.
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 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
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)
Functions¶
-
PIL.ImageFont.
load
(filename)[源代码]¶ Load a font file. This function loads a font object from the given bitmap font file, and returns the corresponding font object.
参数: filename – Name of font file. 返回: A font object. 引发: IOError – If the file could not be read.
-
PIL.ImageFont.
load_path
(filename)[源代码]¶ Load font file. Same as
load()
, but searches for a bitmap font along the Python path.参数: filename – Name of font file. 返回: A font object. 引发: IOError – If the file could not be read.
-
PIL.ImageFont.
truetype
(font=None, size=10, index=0, encoding='', layout_engine=None)[源代码]¶ Load a TrueType or OpenType font from a file or file-like object, and create a font object. This function loads a font object from the given file or file-like object, and creates a font object for a font of the given size.
This function requires the _imagingft service.
参数: - font – A filename or file-like object containing a TrueType font.
Under Windows, if the file is not found in this filename,
the loader also looks in Windows
fonts/
directory. - size – The requested size, in points.
- index – Which font face to load (default is first available face).
- encoding – Which font encoding to use (default is Unicode). Common encodings are “unic” (Unicode), “symb” (Microsoft Symbol), “ADOB” (Adobe Standard), “ADBE” (Adobe Expert), and “armn” (Apple Roman). See the FreeType documentation for more information.
- layout_engine – Which layout engine to use, if available: ImageFont.LAYOUT_BASIC or ImageFont.LAYOUT_RAQM.
返回: A font object.
引发: IOError – If the file could not be read.
- font – A filename or file-like object containing a TrueType font.
Under Windows, if the file is not found in this filename,
the loader also looks in Windows
ImageGrab
Module (macOS and Windows only)¶
The ImageGrab
module can be used to copy the contents of the screen
or the clipboard to a PIL image memory.
注解
The current version works on macOS and Windows only.
1.1.3 新版功能.
-
PIL.ImageGrab.
grab
(bbox=None, include_layered_windows=False)¶ Take a snapshot of the screen. The pixels inside the bounding box are returned as an “RGB” image on Windows or “RGBA” on macOS. If the bounding box is omitted, the entire screen is copied.
1.1.3 新版功能: (Windows), 3.0.0 (macOS)
参数: - bbox – What region to copy. Default is the entire screen.
- include_layered_windows – Includes layered windows. Windows OS only.
返回: An image
-
PIL.ImageGrab.
grabclipboard
()¶ Take a snapshot of the clipboard image, if any.
1.1.4 新版功能: (Windows), 3.3.0 (macOS)
返回: On Windows, 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. On Mac, an image, or None if the clipboard does not contain image data.
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.
Example: Using the ImageMath
module¶
from PIL 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 thesplit()
method ormerge()
function.参数: - expression – A string which uses the standard Python expression syntax. In addition to the standard operators, you can also use the functions described below.
- environment – A dictionary that maps image names to Image instances. You can use one or more keyword arguments instead of a dictionary, as shown in the above example. Note that the names must be valid Python identifiers.
返回: An image, an integer value, a floating point value, or a pixel tuple, depending on the expression.
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”).
-
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.
ImageMorph
Module¶
The ImageMorph
module provides morphology operations on images.
-
class
PIL.ImageMorph.
LutBuilder
(patterns=None, op_name=None)[源代码] 基类:
object
A class for building a MorphLut from a descriptive language
The input patterns is a list of a strings sequences like these:
4:(... .1. 111)->1
(whitespaces including linebreaks are ignored). The option 4 describes a series of symmetry operations (in this case a 4-rotation), the pattern is described by:
- . or X - Ignore
- 1 - Pixel is on
- 0 - Pixel is off
The result of the operation is described after “->” string.
The default is to return the current pixel value, which is returned if no other match is found.
Operations:
- 4 - 4 way rotation
- N - Negate
- 1 - Dummy op for no other operation (an op must always be given)
- M - Mirroring
Example:
lb = LutBuilder(patterns = ["4:(... .1. 111)->1"]) lut = lb.build_lut()
-
add_patterns
(patterns)[源代码]
-
build_default_lut
()[源代码]
-
build_lut
()[源代码] Compile all patterns into a morphology lut.
TBD :Build based on (file) morphlut:modify_lut
-
get_lut
()[源代码]
-
class
PIL.ImageMorph.
MorphOp
(lut=None, op_name=None, patterns=None)[源代码] 基类:
object
A class for binary morphological operators
-
apply
(image)[源代码] Run a single morphological operation on an image
Returns a tuple of the number of changed pixels and the morphed image
-
get_on_pixels
(image)[源代码] Get a list of all turned on pixels in a binary image
Returns a list of tuples of (x,y) coordinates of all matching pixels. See 坐标系统.
-
load_lut
(filename)[源代码] Load an operator from an mrl file
-
match
(image)[源代码] Get a list of coordinates matching the morphological operation on an image.
Returns a list of tuples of (x,y) coordinates of all matching pixels. See 坐标系统.
-
save_lut
(filename)[源代码] Save an operator to an mrl file
-
set_lut
(lut)[源代码] Set the lut from an external source
-
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.
1.1.3 新版功能.
-
PIL.ImageOps.
autocontrast
(image, cutoff=0, ignore=None)[源代码]¶ Maximize (normalize) image contrast. This function calculates a histogram of the input image, removes cutoff percent of the lightest and darkest pixels from the histogram, and remaps the image so that the darkest pixel becomes black (0), and the lightest becomes white (255).
参数: - image – The image to process.
- cutoff – How many percent to cut off from the histogram.
- ignore – The background pixel value (use None for no background).
返回: An image.
-
PIL.ImageOps.
colorize
(image, black, white, mid=None, blackpoint=0, whitepoint=255, midpoint=127)[源代码]¶ Colorize grayscale image. This function calculates a color wedge which maps all black pixels in the source image to the first color and all white pixels to the second color. If mid is specified, it uses three-color mapping. The black and white arguments should be RGB tuples or color names; optionally you can use three-color mapping by also specifying mid. Mapping positions for any of the colors can be specified (e.g. blackpoint), where these parameters are the integer value corresponding to where the corresponding color should be mapped. These parameters must have logical order, such that blackpoint <= midpoint <= whitepoint (if mid is specified).
参数: - image – The image to colorize.
- black – The color to use for black input pixels.
- white – The color to use for white input pixels.
- mid – The color to use for midtone input pixels.
- blackpoint – an int value [0, 255] for the black mapping.
- whitepoint – an int value [0, 255] for the white mapping.
- midpoint – an int value [0, 255] for the midtone mapping.
返回: An image.
-
PIL.ImageOps.
crop
(image, border=0)[源代码]¶ Remove border from image. The same amount of pixels are removed from all four sides. This function works on all image modes.
参见
参数: - image – The image to crop.
- border – The number of pixels to remove.
返回: An image.
-
PIL.ImageOps.
deform
(image, deformer, resample=2)[源代码]¶ Deform the image.
参数: - image – The image to deform.
- deformer – A deformer object. Any object that implements a getmesh method can be used.
- resample – An optional resampling filter. Same values possible as in the PIL.Image.transform function.
返回: An image.
-
PIL.ImageOps.
equalize
(image, mask=None)[源代码]¶ Equalize the image histogram. This function applies a non-linear mapping to the input image, in order to create a uniform distribution of grayscale values in the output image.
参数: - image – The image to equalize.
- mask – An optional mask. If given, only the pixels selected by the mask are included in the analysis.
返回: An image.
-
PIL.ImageOps.
expand
(image, border=0, fill=0)[源代码]¶ Add border to the image
参数: - image – The image to expand.
- border – Border width, in pixels.
- fill – Pixel fill value (a color value). Default is 0 (black).
返回: An image.
-
PIL.ImageOps.
fit
(image, size, method=0, bleed=0.0, centering=(0.5, 0.5))[源代码]¶ Returns a sized and cropped version of the image, cropped to the requested aspect ratio and size.
This function was contributed by Kevin Cazabon.
参数: - image – The image to size and crop.
- size – The requested output size in pixels, given as a (width, height) tuple.
- method – What resampling method to use. Default is
PIL.Image.NEAREST
. - bleed – Remove a border around the outside of the image from all four edges. The value is a decimal percentage (use 0.01 for one percent). The default value is 0 (no border). Cannot be greater than or equal to 0.5.
- centering – Control the cropping position. Use (0.5, 0.5) for center cropping (e.g. if cropping the width, take 50% off of the left side, and therefore 50% off the right side). (0.0, 0.0) will crop from the top left corner (i.e. if cropping the width, take all of the crop off of the right side, and if cropping the height, take all of it off the bottom). (1.0, 0.0) will crop from the bottom left corner, etc. (i.e. if cropping the width, take all of the crop off the left side, and if cropping the height take none from the top, and therefore all off the bottom).
返回: An image.
-
PIL.ImageOps.
flip
(image)[源代码]¶ Flip the image vertically (top to bottom).
参数: image – The image to flip. 返回: An image.
-
PIL.ImageOps.
grayscale
(image)[源代码]¶ Convert the image to grayscale.
参数: image – The image to convert. 返回: An image.
-
PIL.ImageOps.
invert
(image)[源代码]¶ Invert (negate) the image.
参数: image – The image to invert. 返回: An image.
-
PIL.ImageOps.
mirror
(image)[源代码]¶ Flip image horizontally (left to right).
参数: image – The image to mirror. 返回: An image.
ImagePalette
Module¶
The ImagePalette
module contains a class of the same name to
represent the color palette of palette mapped images.
注解
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.
-
class
PIL.ImagePalette.
ImagePalette
(mode='RGB', palette=None, size=0)[源代码]¶ Color palette for palette mapped images
参数: - mode – The mode to use for the Palette. See: 模式. Defaults to “RGB”
- palette – An optional palette. If given, it must be a bytearray,
an array or a list of ints between 0-255 and of length
size
times the number of colors inmode
. The list must be aligned by channel (All R values must be contiguous in the list before G and B values.) Defaults to 0 through 255 per channel. - size – An optional palette size. If given, it cannot be equal to or greater than 256. Defaults to 0.
-
getdata
()[源代码]¶ Get palette contents in format suitable for the low-level
im.putpalette
primitive.警告
This method is experimental.
-
tostring
()¶ Convert palette to bytes.
警告
This method is experimental.
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.
参数: 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.
返回: (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), …].
参数: 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.返回: 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
ImageQt
Module¶
The ImageQt
module contains support for creating PyQt4, PyQt5, PySide or
PySide2 QImage objects from PIL images.
Qt 4 reached end-of-life on 2015-12-19. Its Python bindings are also EOL: PyQt4 since 2018-08-31 and PySide since 2015-10-14.
Support for PyQt4 and PySide is deprecated since Pillow 6.0.0 and will be removed in a future version. Please upgrade to PyQt5 or PySide2.
1.1.6 新版功能.
-
class
ImageQt.
ImageQt
(image)¶ Creates an
ImageQt
object from a PILImage
object. This class is a subclass of QtGui.QImage, which means that you can pass the resulting objects directly to PyQt4/PyQt5/PySide 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.
ImageSequence
Module¶
The ImageSequence
module contains a wrapper class that lets you
iterate over the frames of an image sequence.
Extracting frames from an animation¶
from PIL import Image, ImageSequence
im = Image.open("animation.fli")
index = 1
for frame in ImageSequence.Iterator(im):
frame.save("frame%d.png" % index)
index += 1
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.
参数: - image – A PIL image, or a precalculated histogram.
- mask – An optional mask.
-
extrema
¶ Min/max values for each band in the image.
注解
This relies on the
histogram()
method, and simply returns the low and high bins used. This is correct for images with 8 bits per channel, but fails for other modes such asI
orF
. Instead, usegetextrema()
to return per-band extrema for the image. This is more correct and efficient because, for non-8-bit modes, the histogram method usesgetextrema()
to determine the bins used.
-
count
¶ Total number of pixels for each band in the image.
-
sum
¶ Sum of all pixels for each band in the image.
-
sum2
¶ Squared sum of all pixels for each band in the image.
-
mean
¶ Average (arithmetic mean) pixel level for each band in the image.
-
median
¶ Median pixel level for each band in the image.
-
rms
¶ RMS (root-mean-square) for each band in the image.
-
var
¶ Variance for each band in the image.
-
stddev
¶ Standard deviation for each band in the image.
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.
-
class
PIL.ImageTk.
BitmapImage
(image=None, **kw)[源代码]¶ A Tkinter-compatible bitmap image. This can be used everywhere Tkinter expects an image object.
The given image must have mode “1”. Pixels having value 0 are treated as transparent. Options, if any, are passed on to Tkinter. The most commonly used option is foreground, which is used to specify the color for the non-transparent parts. See the Tkinter documentation for information on how to specify colours.
参数: image – A PIL image.
-
class
PIL.ImageTk.
PhotoImage
(image=None, size=None, **kw)[源代码]¶ A Tkinter-compatible photo image. This can be used everywhere Tkinter expects an image object. If the image is an RGBA image, pixels having alpha 0 are treated as transparent.
The constructor takes either a PIL image, or a mode and a size. Alternatively, you can use the file or data options to initialize the photo image object.
参数: - image – Either a PIL image, or a mode string. If a mode string is used, a size must also be given.
- size – If the first argument is a mode string, this defines the size of the image.
- file – A filename to load the image from (using
Image.open(file)
). - data – An 8-bit string containing image data (as loaded from an image file).
-
paste
(im, box=None)[源代码]¶ Paste a PIL image into the photo image. Note that this can be very slow if the photo image is displayed.
参数: - im – A PIL image. The size must match the target region. If the mode does not match, the image is converted to the mode of the bitmap image.
- box – A 4-tuple defining the left, upper, right, and lower pixel coordinate. See 坐标系统. If None is given instead of a tuple, all of the image is assumed.
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)
-
class
PIL.ImageWin.
Dib
(image, size=None)[源代码]¶ A Windows bitmap with the given mode and size. The mode can be one of “1”, “L”, “P”, or “RGB”.
If the display requires a palette, this constructor creates a suitable palette and associates it with the image. For an “L” image, 128 greylevels are allocated. For an “RGB” image, a 6x6x6 colour cube is used, together with 20 greylevels.
To make sure that palettes work properly under Windows, you must call the palette method upon certain events from Windows.
参数: - image – Either a PIL image, or a mode string. If a mode string is used, a size must also be given. The mode can be one of “1”, “L”, “P”, or “RGB”.
- size – If the first argument is a mode string, this defines the size of the image.
-
draw
(handle, dst, src=None)[源代码]¶ Same as expose, but allows you to specify where to draw the image, and what part of it to draw.
The destination and source areas are given as 4-tuple rectangles. If the source is omitted, the entire image is copied. If the source and the destination have different sizes, the image is resized as necessary.
-
expose
(handle)[源代码]¶ Copy the bitmap contents to a device context.
参数: handle – Device context (HDC), cast to a Python integer, or an HDC or HWND instance. In PythonWin, you can use the CDC.GetHandleAttrib()
to get a suitable handle.
-
frombytes
(buffer)[源代码]¶ Load display memory contents from byte data.
参数: buffer – A buffer containing display data (usually data returned from <b>tobytes</b>)
-
paste
(im, box=None)[源代码]¶ Paste a PIL image into the bitmap image.
参数: - im – A PIL image. The size must match the target region. If the mode does not match, the image is converted to the mode of the bitmap image.
- box – A 4-tuple defining the left, upper, right, and lower pixel coordinate. See 坐标系统. If None is given instead of a tuple, all of the image is assumed.
-
query_palette
(handle)[源代码]¶ Installs the palette associated with the image in the given device context.
This method should be called upon QUERYNEWPALETTE and PALETTECHANGED events from Windows. If this method returns a non-zero value, one or more display palette entries were changed, and the image should be redrawn.
参数: handle – Device context (HDC), cast to a Python integer, or an HDC or HWND instance. 返回: A true value if one or more entries were changed (this indicates that the image should be redrawn).
ExifTags
Module¶
The ExifTags
module exposes two dictionaries which
provide constants and clear-text names for various well-known EXIF tags.
-
class
PIL.ExifTags.
TAGS
¶ The TAG dictionary maps 16-bit integer EXIF tag enumerations to descriptive string names. For instance:
>>> 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'
TiffTags
Module¶
The TiffTags
module exposes many of the standard TIFF
metadata tag numbers, names, and type information.
-
PIL.TiffTags.
lookup
(tag)[源代码]¶ 参数: tag – Integer tag number 返回: Taginfo namedtuple, From the TAGS_V2
info if possible, otherwise just populating the value and name fromTAGS
. If the tag is not recognized, “unknown” is returned for the name
3.1.0 新版功能.
-
class
PIL.TiffTags.
TagInfo
[源代码]¶ -
__init__
(self, value=None, name="unknown", type=None, length=0, enum=None)¶ 参数: - value – Integer Tag Number
- name – Tag Name
- type – Integer type from
PIL.TiffTags.TYPES
- length – Array length: 0 == variable, 1 == single value, n = fixed
- enum – Dict of name:integer value options for an enumeration
-
3.0.0 新版功能.
-
PIL.TiffTags.
TAGS_V2
¶ The
TAGS_V2
dictionary maps 16-bit integer tag numbers toPIL.TagTypes.TagInfo
tuples for metadata fields defined in the TIFF spec.
3.0.0 新版功能.
-
PIL.TiffTags.
TAGS
¶ The
TAGS
dictionary maps 16-bit integer TIFF tag number to descriptive string names. For instance:>>> from PIL.TiffTags import TAGS >>> TAGS[0x010e] 'ImageDescription'
This dictionary contains a superset of the tags in TAGS_V2, common EXIF tags, and other well known metadata tags.
-
PIL.TiffTags.
TYPES
¶ The
TYPES
dictionary maps the TIFF type short integer to a human readable type name.
PSDraw
Module¶
The PSDraw
module provides simple print support for Postscript
printers. You can print text, graphics and images through this module.
-
class
PIL.PSDraw.
PSDraw
(fp=None)[源代码]¶ Sets up printing to the given file. If fp is omitted,
sys.stdout
is assumed.-
line
(xy0, xy1)[源代码]¶ Draws a line between the two points. Coordinates are given in Postscript point coordinates (72 points per inch, (0, 0) is the lower left corner of the page).
-
rectangle
(box)[源代码]¶ Draws a rectangle.
参数: box – A 4-tuple of integers whose order and function is currently undocumented.
Hint: the tuple is passed into this format string:
%d %d M %d %d 0 Vr
-
PixelAccess
Class¶
The PixelAccess class provides read and write access to
PIL.Image
data at a pixel level.
注解
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.
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)
Access using negative indexes is also possible.
px[-1,-1] = (0,0,0)
print (px[-1,-1])
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
参数: - xy – The pixel coordinate, given as (x, y).
- color – The pixel value according to its mode. e.g. tuple (r, g, b) for RGB mode)
-
__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. In addition to this, RGB and RGBA tuples are accepted for P images.
参数: - xy – The pixel coordinate, given as (x, y).
- color – The pixel value according to its mode. e.g. tuple (r, g, b) for RGB mode)
-
getpixel(self, xy):
- Returns the pixel at x,y. The pixel is returned as a single
value for single band images or a tuple for multiple band images
param xy: The pixel coordinate, given as (x, y). returns: a pixel value for single band images, a tuple of pixel values for multiband images.
-
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.
注解
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.
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)
Access using negative indexes is also possible.
px[-1,-1] = (0,0,0)
print (px[-1,-1])
PyAccess
Class¶
PIL Package (autodoc of remaining modules)¶
Reference for modules whose documentation has not yet been ported or written can be found here.
ContainerIO
Module¶
-
class
PIL.ContainerIO.
ContainerIO
(file, offset, length)[源代码]¶ 基类:
object
-
read
(n=0)[源代码]¶ Read data.
参数: n – Number of bytes to read. If omitted or zero, read until end of region. 返回: An 8-bit string.
-
GdImageFile
Module¶
GimpGradientFile
Module¶
GimpPaletteFile
Module¶
ImageShow
Module¶
ImageTransform
Module¶
-
class
PIL.ImageTransform.
AffineTransform
(data)[源代码]¶ 基类:
PIL.ImageTransform.Transform
Define an affine image transform.
This function takes a 6-tuple (a, b, c, d, e, f) which contain the first two rows from an affine transform matrix. For each pixel (x, y) in the output image, the new value is taken from a position (a x + b y + c, d x + e y + f) in the input image, rounded to nearest pixel.
This function can be used to scale, translate, rotate, and shear the original image.
See
transform()
参数: matrix – A 6-tuple (a, b, c, d, e, f) containing the first two rows from an affine transform matrix. -
method
= 0¶
-
-
class
PIL.ImageTransform.
ExtentTransform
(data)[源代码]¶ 基类:
PIL.ImageTransform.Transform
Define a transform to extract a subregion from an image.
Maps a rectangle (defined by two corners) from the image to a rectangle of the given size. The resulting image will contain data sampled from between the corners, such that (x0, y0) in the input image will end up at (0,0) in the output image, and (x1, y1) at size.
This method can be used to crop, stretch, shrink, or mirror an arbitrary rectangle in the current image. It is slightly slower than crop, but about as fast as a corresponding resize operation.
See
transform()
参数: bbox – A 4-tuple (x0, y0, x1, y1) which specifies two points in the input image’s coordinate system. See 坐标系统. -
method
= 1¶
-
-
class
PIL.ImageTransform.
MeshTransform
(data)[源代码]¶ 基类:
PIL.ImageTransform.Transform
Define a mesh image transform. A mesh transform consists of one or more individual quad transforms.
See
transform()
参数: data – A list of (bbox, quad) tuples. -
method
= 4¶
-
-
class
PIL.ImageTransform.
QuadTransform
(data)[源代码]¶ 基类:
PIL.ImageTransform.Transform
Define a quad image transform.
Maps a quadrilateral (a region defined by four corners) from the image to a rectangle of the given size.
See
transform()
参数: xy – An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain the upper left, lower left, lower right, and upper right corner of the source quadrilateral. -
method
= 3¶
-
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.: https://en.wikipedia.org/wiki/Chroma_subsampling)
Possible subsampling values are 0, 1 and 2 that correspond to 4:4:4, 4:2:2 and 4:2:0.
You can get the subsampling of a JPEG with the JpegImagePlugin.get_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.: https://en.wikipedia.org/wiki/Quantization_matrix#Quantization_matrices, https://en.wikipedia.org/wiki/JPEG#Quantization)
You can get the quantization tables of a JPEG with:
im.quantization
This will return a dict with a number of arrays. You can pass this dict directly as the qtables argument when saving a JPEG.
The tables format between im.quantization and quantization in presets differ in 3 ways:
- The base container of the preset is a list with sublists instead of dict. dict[0] -> list[0], dict[1] -> list[1], …
- Each table in a preset is a list instead of an array.
- The zigzag order is remove in the preset (needed by libjpeg >= 6a).
You can convert the dict format to the preset format with the JpegImagePlugin.convert_dict_qtables(dict_qtables) function.
Libjpeg ref.: https://web.archive.org/web/20120328125543/http://www.jpegcameras.com/libjpeg/libjpeg-3.html
PaletteFile
Module¶
PngImagePlugin.iTXt
Class¶
PngImagePlugin.PngInfo
Class¶
-
class
PIL.PngImagePlugin.
PngInfo
[源代码]¶ 基类:
object
PNG chunk container (for use with save(pnginfo=))
-
add
(cid, data)[源代码]¶ Appends an arbitrary chunk. Use with caution.
参数: - cid – a byte string, 4 bytes long.
- data – a byte string of the encoded data
-
add_itxt
(key, value, lang='', tkey='', zip=False)[源代码]¶ Appends an iTXt chunk.
参数: - key – latin-1 encodable text key name
- value – value for this key
- lang – language code
- tkey – UTF-8 version of the key name
- zip – compression flag
-
add_text
(key, value, zip=False)[源代码]¶ Appends a text chunk.
参数: - key – latin-1 encodable text key name
- value – value for this key, text or an
PIL.PngImagePlugin.iTXt
instance - zip – compression flag
-
WalImageFile
Module¶
_binary
Module¶
-
PIL._binary.
i16le
(c, o=0)[源代码]¶ Converts a 2-bytes (16 bits) string to an unsigned integer.
c: string containing bytes to convert o: offset of bytes to convert in string
-
PIL._binary.
i32le
(c, o=0)[源代码]¶ Converts a 4-bytes (32 bits) string to an unsigned integer.
c: string containing bytes to convert o: offset of bytes to convert in string
Plugin reference¶
BmpImagePlugin
Module¶
-
class
PIL.BmpImagePlugin.
BmpImageFile
(fp=None, filename=None)[源代码]¶ 基类:
PIL.ImageFile.ImageFile
Image plugin for the Windows Bitmap format (BMP)
-
BITFIELDS
= 3¶
-
COMPRESSIONS
= {'BITFIELDS': 3, 'JPEG': 4, 'PNG': 5, 'RAW': 0, 'RLE4': 2, 'RLE8': 1}¶
-
JPEG
= 4¶
-
PNG
= 5¶
-
RAW
= 0¶
-
RLE4
= 2¶
-
RLE8
= 1¶
-
format
= 'BMP'¶
-
format_description
= 'Windows Bitmap'¶
-
-
class
PIL.BmpImagePlugin.
DibImageFile
(fp=None, filename=None)[源代码]¶ 基类:
PIL.BmpImagePlugin.BmpImageFile
-
format
= 'DIB'¶
-
format_description
= 'Windows Bitmap'¶
-
BufrStubImagePlugin
Module¶
CurImagePlugin
Module¶
-
class
PIL.CurImagePlugin.
CurImageFile
(fp=None, filename=None)[源代码]¶ 基类:
PIL.BmpImagePlugin.BmpImageFile
-
format
= 'CUR'¶
-
format_description
= 'Windows Cursor'¶
-
DcxImagePlugin
Module¶
-
class
PIL.DcxImagePlugin.
DcxImageFile
(fp=None, filename=None)[源代码]¶ 基类:
PIL.PcxImagePlugin.PcxImageFile
-
format
= 'DCX'¶
-
format_description
= 'Intel DCX'¶
-
is_animated
¶
-
n_frames
¶
-
seek
(frame)[源代码]¶ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an EOFError exception. When a sequence file is opened, the library automatically seeks to frame 0.
Note that in the current version of the library, most sequence formats only allows you to seek to the next frame.
See
tell()
.参数: frame – Frame number, starting at 0. 引发: EOFError – If the call attempts to seek beyond the end of the sequence.
-
EpsImagePlugin
Module¶
-
class
PIL.EpsImagePlugin.
EpsImageFile
(fp=None, filename=None)[源代码]¶ 基类:
PIL.ImageFile.ImageFile
EPS File Parser for the Python Imaging Library
-
format
= 'EPS'¶
-
format_description
= 'Encapsulated Postscript'¶
-
mode_map
= {1: 'L', 2: 'LAB', 3: 'RGB', 4: 'CMYK'}¶
-
FitsStubImagePlugin
Module¶
FliImagePlugin
Module¶
-
class
PIL.FliImagePlugin.
FliImageFile
(fp=None, filename=None)[源代码]¶ 基类:
PIL.ImageFile.ImageFile
-
format
= 'FLI'¶
-
format_description
= 'Autodesk FLI/FLC Animation'¶
-
is_animated
¶
-
n_frames
¶
-
seek
(frame)[源代码]¶ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an EOFError exception. When a sequence file is opened, the library automatically seeks to frame 0.
Note that in the current version of the library, most sequence formats only allows you to seek to the next frame.
See
tell()
.参数: frame – Frame number, starting at 0. 引发: EOFError – If the call attempts to seek beyond the end of the sequence.
-
FpxImagePlugin
Module¶
GbrImagePlugin
Module¶
GifImagePlugin
Module¶
-
class
PIL.GifImagePlugin.
GifImageFile
(fp=None, filename=None)[源代码]¶ 基类:
PIL.ImageFile.ImageFile
-
format
= 'GIF'¶
-
format_description
= 'Compuserve GIF'¶
-
global_palette
= None¶
-
is_animated
¶
-
n_frames
¶
-
seek
(frame)[源代码]¶ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an EOFError exception. When a sequence file is opened, the library automatically seeks to frame 0.
Note that in the current version of the library, most sequence formats only allows you to seek to the next frame.
See
tell()
.参数: frame – Frame number, starting at 0. 引发: EOFError – If the call attempts to seek beyond the end of the sequence.
-
-
PIL.GifImagePlugin.
getdata
(im, offset=(0, 0), **params)[源代码]¶ Legacy Method
Return a list of strings representing this image. The first string is a local image header, the rest contains encoded image data.
参数: - im – Image object
- offset – Tuple of (x, y) pixels. Defaults to (0,0)
- **params – E.g. duration or other encoder info parameters
返回: List of Bytes containing gif encoded frame data
GribStubImagePlugin
Module¶
Hdf5StubImagePlugin
Module¶
IcnsImagePlugin
Module¶
-
class
PIL.IcnsImagePlugin.
IcnsFile
(fobj)[源代码]¶ 基类:
object
-
SIZES
= {(16, 16, 1): [(b'icp4', <function read_png_or_jpeg2000>), (b'is32', <function read_32>), (b's8mk', <function read_mk>)], (16, 16, 2): [(b'ic11', <function read_png_or_jpeg2000>)], (32, 32, 1): [(b'icp5', <function read_png_or_jpeg2000>), (b'il32', <function read_32>), (b'l8mk', <function read_mk>)], (32, 32, 2): [(b'ic12', <function read_png_or_jpeg2000>)], (48, 48, 1): [(b'ih32', <function read_32>), (b'h8mk', <function read_mk>)], (64, 64, 1): [(b'icp6', <function read_png_or_jpeg2000>)], (128, 128, 1): [(b'ic07', <function read_png_or_jpeg2000>), (b'it32', <function read_32t>), (b't8mk', <function read_mk>)], (128, 128, 2): [(b'ic13', <function read_png_or_jpeg2000>)], (256, 256, 1): [(b'ic08', <function read_png_or_jpeg2000>)], (256, 256, 2): [(b'ic14', <function read_png_or_jpeg2000>)], (512, 512, 1): [(b'ic09', <function read_png_or_jpeg2000>)], (512, 512, 2): [(b'ic10', <function read_png_or_jpeg2000>)]}¶
-
-
class
PIL.IcnsImagePlugin.
IcnsImageFile
(fp=None, filename=None)[源代码]¶ 基类:
PIL.ImageFile.ImageFile
PIL image support for Mac OS .icns files. Chooses the best resolution, but will possibly load a different size image if you mutate the size attribute before calling ‘load’.
The info dictionary has a key ‘sizes’ that is a list of sizes that the icns file has.
-
format
= 'ICNS'¶
-
format_description
= 'Mac OS icns resource'¶
-
size
¶
-
IcoImagePlugin
Module¶
-
class
PIL.IcoImagePlugin.
IcoImageFile
(fp=None, filename=None)[源代码]¶ 基类:
PIL.ImageFile.ImageFile
PIL read-only image support for Microsoft Windows .ico files.
By default the largest resolution image in the file will be loaded. This can be changed by altering the ‘size’ attribute before calling ‘load’.
The info dictionary has a key ‘sizes’ that is a list of the sizes available in the icon file.
Handles classic, XP and Vista icon formats.
This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis <casadebender@gmail.com>. https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
-
format
= 'ICO'¶
-
format_description
= 'Windows Icon'¶
-
size
¶
-
ImImagePlugin
Module¶
-
class
PIL.ImImagePlugin.
ImImageFile
(fp=None, filename=None)[源代码]¶ 基类:
PIL.ImageFile.ImageFile
-
format
= 'IM'¶
-
format_description
= 'IFUNC Image Memory'¶
-
is_animated
¶
-
n_frames
¶
-
seek
(frame)[源代码]¶ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an EOFError exception. When a sequence file is opened, the library automatically seeks to frame 0.
Note that in the current version of the library, most sequence formats only allows you to seek to the next frame.
See
tell()
.参数: frame – Frame number, starting at 0. 引发: EOFError – If the call attempts to seek beyond the end of the sequence.
-
ImtImagePlugin
Module¶
IptcImagePlugin
Module¶
-
class
PIL.IptcImagePlugin.
IptcImageFile
(fp=None, filename=None)[源代码]¶ 基类:
PIL.ImageFile.ImageFile
-
format
= 'IPTC'¶
-
format_description
= 'IPTC/NAA'¶
-
JpegImagePlugin
Module¶
Jpeg2KImagePlugin
Module¶
McIdasImagePlugin
Module¶
MicImagePlugin
Module¶
MspImagePlugin
Module¶
-
class
PIL.MspImagePlugin.
MspDecoder
(mode, *args)[源代码]¶ -
-
decode
(buffer)[源代码]¶ Override to perform the decoding process.
参数: buffer – A bytes object with the data to be decoded. If handles_eof is set, then buffer will be empty and self.fd will be set. 返回: A tuple of (bytes consumed, errcode). If finished with decoding return <0 for the bytes consumed. Err codes are from ERRORS
-
PcdImagePlugin
Module¶
PcxImagePlugin
Module¶
PdfImagePlugin
Module¶
PixarImagePlugin
Module¶
PngImagePlugin
Module¶
-
PIL.PngImagePlugin.
getchunks
(im, **params)[源代码]¶ Return a list of PNG chunks representing this image.
-
PIL.PngImagePlugin.
is_cid
()¶ Matches zero or more characters at the beginning of the string.
-
class
PIL.PngImagePlugin.
PngImageFile
(fp=None, filename=None)[源代码] 基类:
PIL.ImageFile.ImageFile
-
format
= 'PNG'¶
-
format_description
= 'Portable network graphics'¶
-
load_end
()[源代码] internal: finished reading image data
-
load_prepare
()[源代码] internal: prepare to read PNG file
-
load_read
(read_bytes)[源代码] internal: read more image data
-
text
¶
-
verify
()[源代码] Verify PNG file
-
PpmImagePlugin
Module¶
PsdImagePlugin
Module¶
-
class
PIL.PsdImagePlugin.
PsdImageFile
(fp=None, filename=None)[源代码]¶ 基类:
PIL.ImageFile.ImageFile
-
format
= 'PSD'¶
-
format_description
= 'Adobe Photoshop'¶
-
is_animated
¶
-
n_frames
¶
-
seek
(layer)[源代码]¶ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an EOFError exception. When a sequence file is opened, the library automatically seeks to frame 0.
Note that in the current version of the library, most sequence formats only allows you to seek to the next frame.
See
tell()
.参数: frame – Frame number, starting at 0. 引发: EOFError – If the call attempts to seek beyond the end of the sequence.
-
SgiImagePlugin
Module¶
-
class
PIL.SgiImagePlugin.
SGI16Decoder
(mode, *args)[源代码]¶ -
-
decode
(buffer)[源代码]¶ Override to perform the decoding process.
参数: buffer – A bytes object with the data to be decoded. If handles_eof is set, then buffer will be empty and self.fd will be set. 返回: A tuple of (bytes consumed, errcode). If finished with decoding return <0 for the bytes consumed. Err codes are from ERRORS
-
SpiderImagePlugin
Module¶
-
class
PIL.SpiderImagePlugin.
SpiderImageFile
(fp=None, filename=None)[源代码]¶ 基类:
PIL.ImageFile.ImageFile
-
format
= 'SPIDER'¶
-
format_description
= 'Spider 2D image'¶
-
is_animated
¶
-
n_frames
¶
-
seek
(frame)[源代码]¶ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an EOFError exception. When a sequence file is opened, the library automatically seeks to frame 0.
Note that in the current version of the library, most sequence formats only allows you to seek to the next frame.
See
tell()
.参数: frame – Frame number, starting at 0. 引发: EOFError – If the call attempts to seek beyond the end of the sequence.
-
SunImagePlugin
Module¶
TgaImagePlugin
Module¶
TiffImagePlugin
Module¶
-
class
PIL.TiffImagePlugin.
AppendingTiffWriter
(fn, new=False)[源代码]¶ 基类:
object
-
Tags
= {273, 288, 324, 519, 520, 521}¶
-
fieldSizes
= [0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8]¶
-
-
class
PIL.TiffImagePlugin.
IFDRational
(value, denominator=1)[源代码]¶ 基类:
numbers.Rational
Implements a rational class where 0/0 is a legal value to match the in the wild use of exif rationals.
e.g., DigitalZoomRatio - 0.00/0.00 indicates that no digital zoom was used
-
denominator
¶
-
limit_rational
(max_denominator)[源代码]¶ 参数: max_denominator – Integer, the maximum denominator value 返回: Tuple of (numerator, denominator)
-
numerator
¶
-
-
PIL.TiffImagePlugin.
ImageFileDirectory
¶
-
class
PIL.TiffImagePlugin.
ImageFileDirectory_v1
(*args, **kwargs)[源代码]¶ 基类:
PIL.TiffImagePlugin.ImageFileDirectory_v2
This class represents the legacy interface to a TIFF tag directory.
Exposes a dictionary interface of the tags in the directory:
ifd = ImageFileDirectory_v1() ifd[key] = 'Some Data' ifd.tagtype[key] = 2 print(ifd[key]) ('Some Data',)
Also contains a dictionary of tag types as read from the tiff image file, ~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype.
Values are returned as a tuple.
3.0.0 版后已移除.
-
classmethod
from_v2
(original)[源代码]¶ Returns an
ImageFileDirectory_v1
instance with the same data as is contained in the originalImageFileDirectory_v2
instance.返回: ImageFileDirectory_v1
-
tagdata
¶
-
to_v2
()[源代码]¶ Returns an
ImageFileDirectory_v2
instance with the same data as is contained in the originalImageFileDirectory_v1
instance.返回: ImageFileDirectory_v2
-
classmethod
-
class
PIL.TiffImagePlugin.
ImageFileDirectory_v2
(ifh=b'II*x00x00x00x00x00', prefix=None)[源代码]¶ 基类:
collections.abc.MutableMapping
This class represents a TIFF tag directory. To speed things up, we don’t decode tags unless they’re asked for.
Exposes a dictionary interface of the tags in the directory:
ifd = ImageFileDirectory_v2() ifd[key] = 'Some Data' ifd.tagtype[key] = 2 print(ifd[key]) 'Some Data'
Individual values are returned as the strings or numbers, sequences are returned as tuples of the values.
The tiff metadata type of each item is stored in a dictionary of tag types in ~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype. The types are read from a tiff file, guessed from the type added, or added manually.
Data Structures:
- self.tagtype = {}
- Key: numerical tiff tag number
- Value: integer corresponding to the data type from
- ~PIL.TiffTags.TYPES`
3.0.0 新版功能.
-
legacy_api
¶
-
load_double
(data, legacy_api=True)¶
-
load_float
(data, legacy_api=True)¶
-
load_long
(data, legacy_api=True)¶
-
load_short
(data, legacy_api=True)¶
-
load_signed_byte
(data, legacy_api=True)¶
-
load_signed_long
(data, legacy_api=True)¶
-
load_signed_short
(data, legacy_api=True)¶
-
named
()[源代码]¶ 返回: dict of name|key: value Returns the complete tag dictionary, with named tags where possible.
-
offset
¶
-
prefix
¶
-
write_double
(*values)¶
-
write_float
(*values)¶
-
write_long
(*values)¶
-
write_short
(*values)¶
-
write_signed_byte
(*values)¶
-
write_signed_long
(*values)¶
-
write_signed_short
(*values)¶
- self.tagtype = {}
WebPImagePlugin
Module¶
-
class
PIL.WebPImagePlugin.
WebPImageFile
(fp=None, filename=None)[源代码]¶ 基类:
PIL.ImageFile.ImageFile
-
format
= 'WEBP'¶
-
format_description
= 'WebP image'¶
-
is_animated
¶
-
n_frames
¶
-
seek
(frame)[源代码]¶ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an EOFError exception. When a sequence file is opened, the library automatically seeks to frame 0.
Note that in the current version of the library, most sequence formats only allows you to seek to the next frame.
See
tell()
.参数: frame – Frame number, starting at 0. 引发: EOFError – If the call attempts to seek beyond the end of the sequence.
-
WmfImagePlugin
Module¶
XVThumbImagePlugin
Module¶
XbmImagePlugin
Module¶
Internal Reference Docs¶
File Handling in Pillow¶
When opening a file as an image, Pillow requires a filename, pathlib.Path
object, or a file-like object. Pillow uses the filename or Path
to open a
file, so for the rest of this article, they will all be treated as a file-like
object.
The first four of these items are equivalent, the last is dangerous and may fail:
from PIL import Image
import io
import pathlib
im = Image.open('test.jpg')
im2 = Image.open(pathlib.Path('test.jpg'))
f = open('test.jpg', 'rb')
im3 = Image.open(f)
with open('test.jpg', 'rb') as f:
im4 = Image.open(io.BytesIO(f.read()))
# Dangerous FAIL:
with open('test.jpg', 'rb') as f:
im5 = Image.open(f)
im5.load() # FAILS, closed file
If a filename or a path-like object is passed to Pillow, then the resulting
file object opened by Pillow may also be closed by Pillow after the
Image.Image.load()
method is called, provided the associated image does not
have multiple frames.
Pillow cannot in general close and reopen a file, so any access to that file needs to be prior to the close.
Issues¶
- Using the file context manager to provide a file-like object to Pillow is dangerous unless the context of the image is limited to the context of the file.
Image Lifecycle¶
Image.open()
Filenames andPath
objects are opened as a file. Metadata is read from the open file. The file is left open for further usage.Image.Image.load()
When the pixel data from the image is required,load()
is called. The current frame is read into memory. The image can now be used independently of the underlying image file.If a filename or a
Path
object was passed toImage.open()
, then the file object was opened by Pillow and is considered to be used exclusively by Pillow. So if the image is a single-frame image, the file will be closed in this method after the frame is read. If the image is a multi-frame image, (e.g. multipage TIFF and animated GIF) the image file is left open so thatImage.Image.seek()
can load the appropriate frame.Image.Image.close()
Closes the file and destroys the core image object. This is used in the Pillow context manager support. e.g.:with Image.open('test.jpg') as img: ... # image operations here.
The lifecycle of a single-frame image is relatively simple. The file
must remain open until the load()
or close()
function is
called.
Multi-frame images are more complicated. The load()
method is not
a terminal method, so it should not close the underlying file. In general,
Pillow does not know if there are going to be any requests for additional
data until the caller has explicitly closed the image.
Complications¶
TiffImagePlugin
has some code to pass the underlying file descriptor into libtiff (if working on an actual file). Since libtiff closes the file descriptor internally, it is duplicated prior to passing it into libtiff.I don’t think that there’s any way to make this safe without changing the lazy loading:
# Dangerous FAIL: with open('test.jpg', 'rb') as f: im5 = Image.open(f) im5.load() # FAILS, closed file
Proposed File Handling¶
Image.Image.load()
should close the image file, unless there are multiple frames.Image.Image.seek()
should never close the image file.- Users of the library should call
Image.Image.close()
on any multi-frame image to ensure that the underlying file is closed.
Limits¶
This page is documentation to the various fundamental size limits in the Pillow implementation.
Internal Limits¶
- Image sizes cannot be negative. These are checked both in
Storage.c
andImage.py
- Image sizes may be 0. (Although not in 3.4)
- Maximum pixel dimensions are limited to INT32, or 2^31 by the sizes in the image header.
- Individual allocations are limited to 2GB in
Storage.c
- The 2GB allocation puts an upper limit to the xsize of the image of either 2^31 for ‘L’ or 2^29 for ‘RGB’
- Individual memory mapped segments are limited to 2GB in map.c based
on the overflow checks. This requires that any memory mapped image
is smaller than 2GB, as calculated by
y*stride
(so 2Gpx for ‘L’ images, and .5Gpx for ‘RGB’ - Any call to internal python size functions for buffers or strings are currently returned as int32, not py_ssize_t. This limits the maximum buffer to 2GB for operations like frombytes and frombuffer.
- This also limits the size of buffers converted using a decoder. (decode.c:127)
Format Size Limits¶
- ICO: Max size is 256x256
- Webp: 16383x16383 (underlying library size limit: https://developers.google.com/speed/webp/docs/api)
Block Allocator¶
Previous Design¶
Historically there have been two image allocators in Pillow:
ImagingAllocateBlock
and ImagingAllocateArray
. The first works
for images smaller than 16MB of data and allocates one large chunk of
memory of im->linesize * im->ysize
bytes. The second works for
large images and makes one allocation for each scan line of size
im->linesize
bytes. This makes for a very sharp transition
between one allocation and potentially thousands of small allocations,
leading to unpredictable performance penalties around the transition.
New Design¶
ImagingAllocateArray
now allocates space for images as a chain of
blocks with a maximum size of 16MB. If there is a memory allocation
error, it falls back to allocating a 4KB block, or at least one scan
line. This is now the default for all internal allocations.
ImagingAllocateBlock
is now only used for those cases when we are
specifically requesting a single segment of memory for sharing with
other code.
Memory Pools¶
There is now a memory pool to contain a supply of recently freed blocks, which can then be reused without going back to the OS for a fresh allocation. This caching of free blocks is currently disabled by default, but can be enabled and tweaked using three environment variables:
PILLOW_ALIGNMENT
, in bytes. Specifies the alignment of memory allocations. Valid values are powers of 2 between 1 and 128, inclusive. Defaults to 1.PILLOW_BLOCK_SIZE
, in bytes, K, or M. Specifies the maximum block size forImagingAllocateArray
. Valid values are integers, with an optional k or m suffix. Defaults to 16M.PILLOW_BLOCKS_MAX
Specifies the number of freed blocks to retain to fill future memory requests. Any freed blocks over this threshold will be returned to the OS immediately. Defaults to 0.
移植¶
将现有的基于 PIL 的代码移植到 Pillow
Pillow 是对 Python Imaging Library 的功能性替代。要想用 Pillow 运行现有的与 PIL 兼容的代码,需要从 PIL
命名空间导入 Image
模块,而不是全局的命名空间。
修改:
import Image
为:
from PIL import Image
_imaging
模块已经被移除。可以用以下方式导入:
from PIL.Image import core as _imaging
图像插件加载机制已更改。Pillow 不再自动导入 Python 路径中名称以 ImagePlugin.py
结尾的任何文件。你将需要手动导入图像插件。
如果由于任何原因(包括 Python 和扩展程序代码之间版本不匹配)无法加载核心扩展程序,Pillow 将会引发异常。之前,如果核心扩展不可用,则 PIL 仅允许 Python 代码运行。
关于Pillow¶
目标¶
分支作者的目标是通过以下方式促进和支持 PIL 积极发展:
- 通过 Travis CI 和 AppVeyor 进行持续集成测试
- 在 GitHub 上公开的开发活动
- 定期发布到 Python Package Index
许可¶
同 PIL 一样,Pillow 许可为 open source PIL Software License
为什么建立分支¶
PIL 和 setuptools 不兼容。详细解释请参看 this Image-SIG post 。另外,PIL 当前每两年(或更长时间)一次的发行频率太低,不能容纳报告问题的数量和频率。。
PIL现状¶
注解
在 Pillow 2.0.0 之前,很少更改图像代码。Pillow 2.0.0 增加了对 Python 3 的支持,并包括许多贡献者提交的错误修复。
距离上一个 PIL 版本(2009年的 1.1.7 )已有相当长的时间,发行新版本的 PIL 的可能性也随时间降低。但是,我们尚未听到官方宣称要终结 PIL。因此,如果你任然希望支持 PIL,首先 报告问题,然后开放 Pillow tickets。
请提供第一个 ticket 的链接以方便我们在上游跟踪问题。