注解
本文档是对 Pillow 官方文档的中文翻译,译者:phyng(Github),开始于2014-05-21。
警告
受限于译者英文水平以及技术水平,译文难免有很多别扭甚至错误的地方,只能作为大致参考,请尽量 RTEM(Read The English Manual)。
Pillow 是一个对 PIL 友好的分支,作者是 Alex Clark 和贡献者。而 PIL 是一个 Python 图像处理库,作者是 Fredrik Lundh 和贡献者.
注解
上面一排图片无法完整显示四个的话考虑下 FGFW。
使用 Pillow 前先阅读 安装说明.
你可以从 Pillow 的 Github 获取源码或者做出贡献 https://github.com/python-imaging/Pillow. 你也可以从 PyPI 下载。
警告
Pillow >= 2.1.0 不支持 “import _imaging”。请使用 “from PIL.Image import core as _imaging” 代替。
警告
Pillow >= 1.0 不支持 “import Image”. 请使用 “from PIL import Image” 代替。
警告
PIL 和 Pillow 现在不能共存。 如果你想使用 Pillow, 请首先移除 PIL 。
注解
Pillow >= 2.0.0 支持 Python 版本 2.6, 2.7, 3.2, 3.3, 3.4
注解
Pillow < 2.0.0 支持 Python 版本 2.4, 2.5, 2.6, 2.7.
注解
下面的指南将会安装支持大多数格式的 Pillow。 查看 外部库 了解安装外部库的信息。这个页面包含了特定平台的安装。
你可以使用 pip 命令安装Pillow:
$ pip install Pillow
或者 easy_install (for installing Python Eggs, as pip does not support them):
$ easy_install Pillow
或者从 PyPI 下载 compressed archive from PyPI ,解压,进入目录运行:
$ python setup.py install
Pillow 的许多功能需要外部库的支持:
如果机器上已经使用标准方法在标准目录安装了这些库 (e.g. /usr or /usr/local), 那么不需要进行多余的配置了。如果它们安装在非标准目录,你可能需要配置 setuptools 以使用这些目录。 (i.e. by editing setup.py and/or setup.cfg). 当你安装好依赖包之后, 运行:
$ pip install Pillow
注解
Fedora, Debian/Ubuntu, and ArchLinux 已经包含了 Pillow。
注解
你 不需要 安装所有的外部库如果你只想让 Pillow 基本能运行。
我们不为 Linux 提供二进制文件 如果你不是从源码构建的 Python , 那么先确定你安装了 Python 开发环境,在 Debian 或 Ubuntu:
$ sudo apt-get install python-dev python-setuptools
或者使用 Python 3:
$ sudo apt-get install python3-dev python3-setuptools
在 Fedora , 命令是:
$ sudo yum install python-devel
在 Ubuntu 10.04 LTS 安装依赖包:
$ sudo apt-get install libtiff4-dev libjpeg62-dev zlib1g-dev \
libfreetype6-dev tcl8.5-dev tk8.5-dev python-tk
在 Ubuntu 12.04 LTS 或者 Raspian Wheezy 7.0 安装依赖包:
$ sudo apt-get install libtiff4-dev libjpeg8-dev zlib1g-dev \
libfreetype6-dev liblcms2-dev libwebp-dev tcl8.5-dev tk8.5-dev python-tk
在 Fedora 20 安装依赖包:
$ sudo yum install libtiff-devel libjpeg-devel libzip-devel freetype-devel \
lcms2-devel libwebp-devel tcl-devel tk-devel
注解
你 不需要 安装所有的外部库如果你只想让 Pillow 基本能运行。
我们不为 OS X 提供二进制文件,所以你需要先安装 Xcode 才能安装 Pillow 。 (XCode 4.2 on 10.6 可以和官方 Python 二进制版本使用。或者使用任意版本 XCode 自己编译 Python。)
安装依赖包最简单的方法是使用 Homebrew。安装 Homebrew 之后,运行:
$ brew install libtiff libjpeg webp little-cms2
如果你已经构建了Python,可以运行:
$ pip install Pillow
我们在 PyPI 提供 Windows 二进制文件,使用 Python Wheels:
注解
实验性. 需要 setuptools >=0.8 以及 pip >=1.4.1
$ pip install --use-wheel Pillow
如果上面都不行,尝试安装指定版本:
$ pip install --use-wheel Pillow==2.3.0
下面是平台支持情况,一般来说,我们致力于支持大多数平台。
注解
如果你在某平台测试过,编辑这个文件然后在 Github 提交 request 。
Operating system | Supported | Tested Python versions | Tested Pillow versions | Tested processors |
Mac OS X 10.8 Mountain Lion | Yes | 2.6,2.7,3.2,3.3 | x86-64 | |
Mac OS X 10.7 Lion | Yes | 2.6,2.7,3.2,3.3 | 2.2.0 | x86-64 |
Redhat Linux 6 | Yes | 2.6 | x86 | |
CentOS 6.3 | Yes | 2.7,3.3 | x86 | |
Fedora 20 | Yes | 2.7,3.3 | 2.3.0 | x86-64 |
Ubuntu Linux 10.04 LTS | Yes | 2.6 | 2.3.0 | x86,x86-64 |
Ubuntu Linux 12.04 LTS | Yes | 2.6,2.7,3.2,3.3,PyPy2.1 2.7,3.2 |
2.3.0 2.3.0 |
x86,x86-64 ppc |
Ubuntu Linux 13.10 | Yes | 2.7,3.2,3.3 | 2.3.0 | x86 |
Raspian Wheezy | Yes | 2.7,3.2 | 2.3.0 | arm |
Gentoo Linux | Yes | 2.7,3.2 | 2.1.0 | x86-64 |
Windows 7 Pro | Yes | 2.7,3.2,3.3 | 2.2.1 | x86-64 |
Windows Server 2008 R2 Enterprise | Yes | 3.3 | x86-64 | |
Windows 8 Pro | Yes | 2.6,2.7,3.2,3.3,3.4a3 | 2.2.0 | x86,x86-64 |
Windows 8.1 Pro | Yes | 2.6,2.7,3.2,3.3,3.4 | 2.3.0, 2.4.0 | x86,x86-64 |
分支作者的愿景是通过以下途径活跃 PIL 的开发:
和PIL一样,Pillow 使用 MIT-like PIL Software License
Software License
The Python Imaging Library (PIL) is
Copyright © 1997-2011 by Secret Labs AB
Copyright © 1995-2011 by Fredrik Lundh
By obtaining, using, and/or copying this software and/or its associated documentation, you agree that you have read, understood, and will comply with the following terms and conditions:
Permission to use, copy, modify, and distribute this software and its associated documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appears in all copies, and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Secret Labs AB or the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission.
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PIL 不兼容setuptools,请阅读 this Image-SIG post 获取更多解释。而且 PIL 计划一年更新两次太慢了不能解决大量issues报告。
注解
Pillow 2.0.0 之前,Pillow相对于 PIL 更改很少。Pillow 2.0.0 开始增加 Python 3 的支持进行了很多 Bug 修正。
距离上次 PIL 发布更新的时间越久,PIL 更新的可能性越小。然而,PIL官方还没有正式宣布PIL死亡,如果你还想支持 PIL 可以先报告给 PIL: report issues here first, 然后报告给 Pillow: open the corresponding Pillow tickets here.
报告给 Pillow 的时候请带上 PIL 的链接方便我们跟踪。
Python Imaging Library ( PIL ) 给 Python 增加了图像处理能力。
这个库提供了广泛的文件格式支持,高效的内部展现,以及十分强大的图像处理能力。
让我们看看这个库的几种可能用法:
现在的版本包含了 Tk PhotoImage 和 BitmapImage 接口, 以及 Windows DIB interface ,这有助于在 Windows 下使用。
为了方便测试,还提供了 show() 方法,可以保存图像到磁盘并显示。
这个库包含了基本的图像处理功能,包括点操作,使用内置卷积内核过滤,色彩空间转换。
这个库还支持更改图像大小、旋转、自由变换。
有一个直方图方法允许你统计图像,这可以用于对比度增强和全局统计分析。
注解
译者注:编程名词和专业名词尽量不翻译,比如bands, modes等请参考 概念 。
PIL最重要的类是 Image class, 你可以通过多种方法创建这个类的实例;你可以从文件加载图像,或者处理其他图像, 或者从 scratch 创建。
要从文件加载图像,使用 open() 函数, 在 Image 模块:
>>> from PIL import Image
>>> im = Image.open("lena.ppm")
加载成功将返回一个 Image 对象。 你现在可以使用示例属性检查文件内容:
>>> from __future__ import print_function
>>> print(im.format, im.size, im.mode)
PPM (512, 512) RGB
format 这个属性标识了图像来源。如果图像不是从文件读取它的值就是None。size属性是一个二元tuple,包含width和height(宽度和高度,单位都是px)。 mode 属性定义了图像bands的数量和名称,以及像素类型和深度。常见的modes 有 “L” (luminance) 表示灰度图像, “RGB” 表示真彩色图像, and “CMYK” 表示出版图像。
如果文件打开错误,返回 IOError 错误。
只要你有了 Image 类的实例,你就可以通过类的方法处理图像。比如,下列方法可以显示图像:
>>> im.show()
注解
标准的 show() 效率并不高,它需要保存图像到临时文件然后通过 xv 显示图像。你需要先安装 xv ,显示图像有助于调试和测试。
下面的部分提供了这个库其他函数的概览。
PIL 模块支持大量图片格式。使用在 Image 模块的 open() 函数从磁盘读取文件。你不需要知道文件格式就能打开它,这个库能够根据文件内容自动确定文件格式。
要保存文件,使用 Image 类的 save() 方法。保存文件的时候文件名变得重要了。除非你指定格式,否则这个库将会以文件名的扩展名作为格式保存。
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() 方法的第二个参数可以指定文件格式,如果你使用非标准的扩展名你必须这样做:
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 类包含的方法允许你操作图像部分选区。使用:py:meth:~PIL.Image.Image.crop 方法获取图像的一个子矩形选区。
box = (100, 100, 400, 400)
region = im.crop(box)
矩形选区有一个4元元组定义,分别表示左、上、右、下的坐标。这个库以左上角为坐标原点,单位是px,所以上诉代码复制了一个 300x300 pixels 的矩形选区。这个选区现在可以被处理并且粘贴到原图。
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(part2, (0, 0, xsize-delta, ysize))
image.paste(part1, (xsize-delta, 0, xsize, ysize))
return image
For more advanced tricks, the paste method can also take a transparency mask as an optional argument. In this mask, the value 255 indicates that the pasted image is opaque in that position (that is, the pasted image should be used as is). The value 0 means that the pasted image is completely transparent. Values in-between indicate different levels of transparency.
The Python Imaging Library also allows you to work with the individual bands of an multi-band image, such as an RGB image. The split method creates a set of new images, each containing one band from the original multi-band image. The merge function takes a mode and a tuple of images, and combines them into a new image. The following sample swaps the three bands of an RGB image:
The PIL.Image.Image class contains methods to resize() and rotate() an image. The former takes a tuple giving the new size, the latter the angle in degrees counter-clockwise.
out = im.resize((128, 128))
out = im.rotate(45) # degrees counter-clockwise
To rotate the image in 90 degree steps, you can either use the rotate() method or the transpose() method. The latter can also be used to flip an image around its horizontal or vertical axis.
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)
There’s no difference in performance or result between transpose(ROTATE) and corresponding rotate() operations.
A more general form of image transformations can be carried out via the transform() method.
The Python Imaging Library allows you to convert images between different pixel representations using the convert() method.
im = Image.open("lena.ppm").convert("L")
The library supports transformations between each supported mode and the “L” and “RGB” modes. To convert between other modes, you may have to use an intermediate image (typically an “RGB” image).
The Python Imaging Library provides a number of methods and modules that can be used to enhance images.
The ImageFilter module contains a number of pre-defined enhancement filters that can be used with the filter() method.
from PIL import ImageFilter
out = im.filter(ImageFilter.DETAIL)
The point() method can be used to translate the pixel values of an image (e.g. image contrast manipulation). In most cases, a function object expecting one argument can be passed to the this method. Each pixel is processed according to that function:
# multiply each pixel by 1.2
out = im.point(lambda i: i * 1.2)
Using the above technique, you can quickly apply any simple expression to an image. You can also combine the point() and paste() methods to selectively modify an image:
# split the image into individual bands
source = im.split()
R, G, B = 0, 1, 2
# select regions where red is less than 100
mask = source[R].point(lambda i: i < 100 and 255)
# process the green band
out = source[G].point(lambda i: i * 0.7)
# paste the processed band back, but only where red was < 100
source[G].paste(out, None, mask)
# build a new multiband image
im = Image.merge(im.mode, source)
Note the syntax used to create the mask:
imout = im.point(lambda i: expression and 255)
Python only evaluates the portion of a logical expression as is necessary to determine the outcome, and returns the last value examined as the result of the expression. So if the expression above is false (0), Python does not look at the second operand, and thus returns 0. Otherwise, it returns 255.
For more advanced image enhancement, you can use the classes in the ImageEnhance module. Once created from an image, an enhancement object can be used to quickly try out different settings.
You can adjust contrast, brightness, color balance and sharpness in this way.
from PIL import ImageEnhance
enh = ImageEnhance.Contrast(im)
enh.enhance(1.3).show("30% more contrast")
The Python Imaging Library contains some basic support for image sequences (also called animation formats). Supported sequence formats include FLI/FLC, GIF, and a few experimental formats. TIFF files can also contain more than one frame.
When you open a sequence file, PIL automatically loads the first frame in the sequence. You can use the seek and tell methods to move between different frames:
from PIL import Image
im = Image.open("animation.gif")
im.seek(1) # skip to the second frame
try:
while 1:
im.seek(im.tell()+1)
# do something to im
except EOFError:
pass # end of sequence
As seen in this example, you’ll get an EOFError exception when the sequence ends.
Note that most drivers in the current version of the library only allow you to seek to the next frame (as in the above example). To rewind the file, you may have to reopen it.
The following iterator class lets you to use the for-statement to loop over the sequence:
class ImageSequence:
def __init__(self, im):
self.im = im
def __getitem__(self, ix):
try:
if ix:
self.im.seek(ix)
return self.im
except EOFError:
raise IndexError # end of sequence
for frame in ImageSequence(im):
# ...do something to frame...
The Python Imaging Library includes functions to print images, text and graphics on Postscript printers. Here’s a simple example:
from PIL import Image
from PIL import PSDraw
im = Image.open("lena.ppm")
title = "lena"
box = (1*72, 2*72, 7*72, 10*72) # in points
ps = PSDraw.PSDraw() # default is sys.stdout
ps.begin_document(title)
# draw the image (75 dpi)
ps.image(box, im, 75)
ps.rectangle(box)
# draw centered title
ps.setfont("HelveticaNarrow-Bold", 36)
w, h, b = ps.textsize(title)
ps.text((4*72-w/2, 1*72-h), title)
ps.end_document()
As described earlier, the open() function of the Image module is used to open an image file. In most cases, you simply pass it the filename as an argument:
im = Image.open("lena.ppm")
If everything goes well, the result is an PIL.Image.Image object. Otherwise, an IOError exception is raised.
You can use a file-like object instead of the filename. The object must implement read(), seek() and tell() methods, and be opened in binary mode.
fp = open("lena.ppm", "rb")
im = Image.open(fp)
To read an image from string data, use the StringIO class:
import StringIO
im = Image.open(StringIO.StringIO(buffer))
Note that the library rewinds the file (using seek(0)) before reading the image header. In addition, seek will also be used when the image data is read (by the load method). If the image file is embedded in a larger file, such as a tar file, you can use the ContainerIO or TarIO modules to access it.
from PIL import TarIO
fp = TarIO.TarIO("Imaging.tar", "Imaging/test/lena.ppm")
im = Image.open(fp)
Some decoders allow you to manipulate the image while reading it from a file. This can often be used to speed up decoding when creating thumbnails (when speed is usually more important than quality) and printing to a monochrome laser printer (when only a greyscale version of the image is needed).
The draft() method manipulates an opened but not yet loaded image so it as closely as possible matches the given mode and size. This is done by reconfiguring the image decoder.
from __future__ import print_function
im = Image.open(file)
print("original =", im.mode, im.size)
im.draft("L", (100, 100))
print("draft =", im.mode, im.size)
This prints something like:
original = RGB (512, 512)
draft = L (128, 128)
Note that the resulting image may not exactly match the requested mode and size. To make sure that the image is not larger than the given size, use the thumbnail method instead.
The Python Imaging Library handles raster images; that is, rectangles of pixel data.
An image can consist of one or more bands of data. The Python Imaging Library allows you to store several bands in a single image, provided they all have the same dimensions and depth.
To get the number and names of bands in an image, use the getbands() method.
The mode of an image defines the type and depth of a pixel in the image. The current release supports the following standard modes:
- 1 (1-bit pixels, black and white, stored with one pixel per byte)
- L (8-bit pixels, black and white)
- P (8-bit pixels, mapped to any other mode using a color palette)
- RGB (3x8-bit pixels, true color)
- RGBA (4x8-bit pixels, true color with transparency mask)
- CMYK (4x8-bit pixels, color separation)
- YCbCr (3x8-bit pixels, color video format)
- I (32-bit signed integer pixels)
- F (32-bit floating point pixels)
PIL also provides limited support for a few special modes, including LA (L with alpha), RGBX (true color with padding) and RGBa (true color with premultiplied alpha). However, PIL doesn’t support user-defined modes; if you to handle band combinations that are not listed above, use a sequence of Image objects.
You can read the mode of an image through the mode attribute. This is a string containing one of the above values.
You can read the image size through the size attribute. This is a 2-tuple, containing the horizontal and vertical size in pixels.
The Python Imaging Library uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner. Note that the coordinates refer to the implied pixel corners; the centre of a pixel addressed as (0, 0) actually lies at (0.5, 0.5).
Coordinates are usually passed to the library as 2-tuples (x, y). Rectangles are represented as 4-tuples, with the upper left corner given first. For example, a rectangle covering all of an 800x600 pixel image is written as (0, 0, 800, 600).
The palette mode (P) uses a color palette to define the actual color for each pixel.
You can attach auxiliary information to an image using the info attribute. This is a dictionary object.
How such information is handled when loading and saving image files is up to the file format handler (see the chapter on 图片文件格式). Most handlers add properties to the info attribute when loading an image, but ignore it when saving images.
For geometry operations that may map multiple input pixels to a single output pixel, the Python Imaging Library provides four different resampling filters.
Calculate the output pixel value using a high-quality resampling filter (a truncated sinc) on all pixels that may contribute to the output value. In the current version of PIL, this filter can only be used with the resize and thumbnail methods.
1.1.3 新版功能.
Note that in the current version of PIL, the ANTIALIAS filter is the only filter that behaves properly when downsampling (that is, when converting a large image to a small one). The BILINEAR and BICUBIC filters use a fixed input environment, and are best used for scale-preserving geometric transforms and upsamping.
Pillow 是对 PIL 的功能增加,想要在 Pillow 下运行 PIL 的代码,只需要: 把这个:
import Image
修改成:
from PIL import Image
注意,:py:mod:`_imaging` 模块已经被移除,现在可以这样导入::
from PIL.Image import core as _imaging
另外,图像插件导入机制已经改变。Pillow 不会自动导入以 ImagePlugin.py 结尾的文件。你需要手动导入。
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.
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()
The following script creates nice 128x128 thumbnails of all JPEG images in the current directory.
from PIL import Image
import glob, os
size = 128, 128
for infile in glob.glob("*.jpg"):
file, ext = os.path.splitext(infile)
im = Image.open(infile)
im.thumbnail(size, Image.ANTIALIAS)
im.save(file + ".thumbnail", "JPEG")
Opens and identifies the given image file.
This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method). See new().
参数: | |
---|---|
返回: | An Image object. |
引发 IOError: | If the file cannot be found, or the image cannot be opened and identified. |
Alpha composite im2 over im1.
参数: |
|
---|---|
返回: | An Image object. |
Creates a new image by interpolating between two input images, using a constant alpha.:
out = image1 * (1.0 - alpha) + image2 * alpha
参数: |
|
---|---|
返回: | An Image object. |
Create composite image by blending images using a transparency mask.
参数: |
|
---|
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.
参数: |
|
---|---|
返回: | An Image object. |
Creates a new image with the given mode and size.
参数: |
|
---|---|
返回: | An Image object. |
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.
参数: |
|
---|---|
返回: | An image memory. |
1.1.6 新版功能.
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 use open() to load it.
参数: |
|
---|---|
返回: | An Image object. |
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 fromstring(). 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.
参数: |
|
---|---|
返回: | An Image object. |
1.1.4 新版功能.
注解
These functions are for use by plugin authors. Application authors can ignore them.
Register an image file plugin. This function should not be used in application code.
参数: |
|
---|
Registers an image MIME type. This function should not be used in application code.
参数: |
|
---|
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.
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 black and white (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 non-zero values are set to 255 (white). To use other thresholds, use the point() method.
参数: |
|
---|---|
返回类型: | |
返回: | 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)
Copies this image. Use this method if you wish to paste things into an image, but still retain the original.
返回类型: | Image |
---|---|
返回: | An Image object. |
Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate.
This is a lazy operation. Changes to the source image may or may not be reflected in the cropped image. To break the connection, call the load() method on the cropped copy.
参数: | box – The crop rectangle, as a (left, upper, right, lower)-tuple. |
---|---|
返回类型: | Image |
返回: | An Image object. |
NYI
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.
参数: |
|
---|
Filters this image using the given filter. For a list of available filters, see the ImageFilter module.
参数: | filter – Filter kernel. |
---|---|
返回: | An Image object. |
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 |
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. If the image is completely empty, this method returns None. |
---|
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. |
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. |
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. |
---|
Returns the pixel value at a given position.
参数: | xy – The coordinate, given as (x, y). |
---|---|
返回: | The pixel value. If the image is a multi-layer image, this method returns a tuple. |
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. |
2.0 版后已移除.
注解
New code should use PIL.ImageChops.offset().
Returns a copy of the image where the 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.
参数: |
|
---|---|
返回: | An Image object. |
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)). 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 can be used for transparency effects.
Note that if you paste an “RGBA” image, the alpha band is ignored. You can work around this by using the same image as both source image and mask.
参数: |
|
---|
Maps this image through a lookup table or function.
参数: |
|
---|---|
返回: | An Image object. |
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. |
---|
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.
参数: |
|
---|
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). |
---|
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.
Note that this method is relatively slow. For more extensive changes, use paste() or the ImageDraw module instead.
See:
参数: |
|
---|
Returns a resized copy of this image.
参数: |
|
---|---|
返回: | An Image object. |
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.
参数: |
|
---|---|
返回: | An Image object. |
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 later in this handbook.
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, and write methods, and be opened in binary mode.
参数: |
|
---|---|
返回: | None |
引发: |
|
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. |
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 the xv utility.
On Windows, it saves the image to a temporary BMP file, and uses the standard BMP display utility to show it (usually Paint).
参数: |
|
---|
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).
返回: | A tuple containing bands. |
---|
Returns the current frame number. See seek().
返回: | Frame number, starting with 0. |
---|
Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the draft() method to configure the file reader (where applicable), and finally resizes the image.
Note that the bilinear and bicubic filters in the current version of PIL are not well-suited for thumbnail generation. You should use PIL.Image.ANTIALIAS unless speed is much more important than quality.
Also note that this function modifies the Image object in place. If you need to use the full resolution image as well, apply this method to a copy() of the original image.
参数: |
|
---|---|
返回: | None |
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” |
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.
参数: |
|
---|---|
返回: | An Image object. |
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, or PIL.Image.ROTATE_270. |
---|---|
返回: | Returns a flipped or rotated copy of this image. |
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.
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. This method will close the file associated with the image.
返回: | An image access object. |
---|
Instances of the Image class have the following attributes:
The file format of the source file. For images created by the library itself (via a factory function, or by running a method on an existing image), this attribute is set to None.
Type : | string or None |
---|
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 |
---|
Image size, in pixels. The size is given as a 2-tuple (width, height).
Type : | (width, height) |
---|
Colour palette table, if any. If mode is “P”, this should be an instance of the ImagePalette class. Otherwise, it should be set to None.
Type : | ImagePalette or None |
---|
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.
Type : | dict |
---|
The ImageChops module contains a number of arithmetical image operations, called channel operations (“chops”). These can be used for various purposes, including special effects, image compositions, algorithmic painting, and more.
For more pre-made operations, see ImageOps.
At this time, most channel operations are only implemented for 8-bit images (e.g. “L” and “RGB”).
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).
Adds two images, dividing the result by scale and adding the offset. If omitted, scale defaults to 1.0, and offset to 0.0.
out = ((image1 + image2) / scale + offset)
返回类型: | Image |
---|
Add two images, without clipping the result.
out = ((image1 + image2) % MAX)
返回类型: | Image |
---|
Blend images using constant transparency weight. Alias for PIL.Image.Image.blend().
返回类型: | Image |
---|
Create composite using transparency mask. Alias for PIL.Image.Image.composite().
返回类型: | Image |
---|
Compares the two images, pixel by pixel, and returns a new image containing the darker values.
out = min(image1, image2)
返回类型: | Image |
---|
Returns the absolute value of the pixel-by-pixel difference between the two images.
out = abs(image1 - image2)
返回类型: | Image |
---|
Copy a channel. Alias for PIL.Image.Image.copy().
返回类型: | Image |
---|
Compares the two images, pixel by pixel, and returns a new image containing the lighter values.
out = max(image1, image2)
返回类型: | Image |
---|
Logical AND between two images.
out = ((image1 and image2) % MAX)
返回类型: | Image |
---|
Logical OR between two images.
out = ((image1 or image2) % MAX)
返回类型: | Image |
---|
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.
out = image1 * image2 / MAX
返回类型: | Image |
---|
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.
参数: |
|
---|---|
返回类型: |
Superimposes two inverted images on top of each other.
out = MAX - ((MAX - image1) * (MAX - image2) / MAX)
返回类型: | Image |
---|
The ImageColor module contains color tables and converters from CSS3-style color specifiers to RGB tuples. This module is used by PIL.Image.Image.new() and the ImageDraw module, among others.
The ImageColor module supports the following string formats:
1.1.4 新版功能.
参数: | color – A color string |
---|---|
返回: | (red, green, blue[, alpha]) |
Same as getrgb(), but converts the RGB value to a greyscale value if the mode is not color or a palette image. If the string cannot be parsed, this function raises a ValueError exception.
1.1.4 新版功能.
参数: | color – A color string |
---|---|
返回: | (graylevel [, alpha]) or (red, green, blue[, alpha]) |
The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.
For a more advanced drawing library for PIL, see the aggdraw module.
from PIL import Image, ImageDraw
im = Image.open("lena.pgm")
draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=128)
draw.line((0, im.size[1], im.size[0], 0), fill=128)
del draw
# write to stdout
im.save(sys.stdout, "PNG")
The graphics interface uses the same coordinate system as PIL itself, with (0, 0) in the upper left corner.
To specify colors, you can use numbers or tuples just as you would use with PIL.Image.Image.new() or PIL.Image.Image.putpixel(). For “1”, “L”, and “I” images, use integers. For “RGB” images, use a 3-tuple containing integer values. For “F” images, use integer or floating point values.
For palette images (mode “P”), use integers as color indexes. In 1.1.4 and later, you can also use RGB 3-tuples or color names (see below). The drawing layer will automatically assign color indexes, as long as you don’t draw with more than 256 colors.
See Color Names for the color names supported by Pillow.
PIL can use bitmap fonts or OpenType/TrueType fonts.
Bitmap fonts are stored in PIL’s own format, where each font typically consists of a two files, one named .pil and the other usually named .pbm. The former contains font metrics, the latter raster data.
To load a bitmap font, use the load functions in the ImageFont module.
To load a OpenType/TrueType font, use the truetype function in the ImageFont module. Note that this function depends on third-party libraries, and may not available in all PIL builds.
Creates an object that can be used to draw in the given image.
Note that the image will be modified in place.
Draws an arc (a portion of a circle outline) between the start and end angles, inside the given bounding box.
参数: |
|
---|
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.
Same as arc(), but connects the end points with a straight line.
参数: |
|
---|
Draws an ellipse inside the given bounding box.
参数: |
|
---|
Draws a line between the coordinates in the xy list.
参数: |
|
---|
Same as arc, but also draws straight lines between the end points and the center of the bounding box.
参数: |
|
---|
Draws points (individual pixels) at the given coordinates.
参数: |
|
---|
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.
参数: |
|
---|
Draws a rectangle.
参数: |
|
---|
警告
This method is experimental.
Draw a shape.
Draws the string at the given position.
参数: |
|
---|
Return the size of the given string, in pixels.
参数: |
|
---|
The Draw class contains a constructor and a number of methods which are provided for backwards compatibility only. For this to work properly, you should either use options on the drawing primitives, or these methods. Do not mix the old and new calling conventions.
1.1.5 版后已移除.
Sets the color to use for subsequent draw and fill operations.
1.1.5 版后已移除.
Sets the fill mode.
If the mode is 0, subsequently drawn shapes (like polygons and rectangles) are outlined. If the mode is 1, they are filled.
1.1.5 版后已移除.
Sets the default font to use for the text method.
参数: | font – An ImageFont instance. |
---|
The ImageEnhance module contains a number of classes that can be used for image enhancement.
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.
All enhancement classes implement a common interface, containing a single method:
Returns an enhanced image.
参数: | 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. |
---|---|
返回类型: | 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.
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.
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.
from PIL import ImageFile
fp = open("lena.pgm", "rb")
p = ImageFile.Parser()
while 1:
s = fp.read(1024)
if not s:
break
p.feed(s)
im = p.close()
im.save("copy.jpg")
Incremental image parser. This class implements the standard feed/close consumer interface.
In Python 2.x, this is an old-style class.
(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. |
The ImageFilter module contains definitions for a pre-defined set of filters, which can be be used with the Image.filter() method.
from PIL import ImageFilter
im1 = im.filter(ImageFilter.BLUR)
im2 = im.filter(ImageFilter.MinFilter(3))
im3 = im.filter(ImageFilter.MinFilter) # same as MinFilter(3)
The current version of the library provides the following set of predefined image enhancement filters:
Gaussian blur filter.
参数: | radius – Blur radius. |
---|
Unsharp mask filter.
See Wikipedia’s entry on digital unsharp masking for an explanation of the parameters.
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.
参数: |
|
---|
Create a rank filter. The rank filter sorts all pixels in a window of the given size, and returns the rank‘th value.
参数: |
|
---|
Create a median filter. Picks the median pixel value in a window with the given size.
参数: | size – The kernel size, in pixels. |
---|
Create a min filter. Picks the lowest pixel value in a window with the given size.
参数: | size – The kernel size, in pixels. |
---|
Create a max filter. Picks the largest pixel value in a window with the given size.
参数: | size – The kernel size, in pixels. |
---|
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. |
---|
The ImageFont module defines a class with the same name. Instances of this class store bitmap fonts, and are used with the PIL.ImageDraw.Draw.text() method.
PIL uses its own font file format to store bitmap fonts. You can use the :command`pilfont` utility to convert BDF and PCF font descriptors (X window font formats) to this format.
Starting with version 1.1.4, PIL can be configured to support TrueType and OpenType fonts (as well as other font formats supported by the FreeType library). For earlier versions, TrueType support is only available as part of the imToolkit package
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)
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. |
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. |
Load a TrueType or OpenType font file, and create a font object. This function loads a font object from the given file, and creates a font object for a font of the given size.
This function requires the _imagingft service.
参数: |
|
---|---|
返回: | A font object. |
引发 IOError: | If the file could not be read. |
返回: | (width, height) |
---|
Create a bitmap for the text.
If the font uses antialiasing, the bitmap should have mode “L” and use a maximum value of 255. Otherwise, it should have mode “1”.
参数: |
|
---|---|
返回: | An internal PIL storage memory instance as defined by the PIL.Image.core interface module. |
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 Windows only.
1.1.3 新版功能.
Take a snapshot of the screen. The pixels inside the bounding box are returned as an “RGB” image. If the bounding box is omitted, the entire screen is copied.
1.1.3 新版功能.
参数: | bbox – What region to copy. Default is the entire screen. |
---|---|
返回: | An image |
Take a snapshot of the clipboard image, if any.
1.1.4 新版功能.
返回: | 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. |
---|
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.
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")
Evaluate expression in the given environment.
In the current version, ImageMath only supports single-layer images. To process multi-band images, use the split() method or merge() function.
参数: |
|
---|---|
返回: | An image, an integer value, a floating point value, or a pixel tuple, depending on the expression. |
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:
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.
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 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.
These functions are applied to each individual pixel.
Absolute value.
Convert image to the given mode. The mode must be given as a string constant.
Convert image to 32-bit floating point. This is equivalent to convert(image, “F”).
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.
Maximum value.
Minimum value.
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 新版功能.
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).
参数: |
|
---|---|
返回: | An image. |
Colorize grayscale image. The black and white arguments should be RGB tuples; this function calculates a color wedge mapping all black pixels in the source image to the first color, and all white pixels to the second color.
参数: |
|
---|---|
返回: | An image. |
Remove border from image. The same amount of pixels are removed from all four sides. This function works on all image modes.
也可以参考
参数: |
|
---|---|
返回: | An image. |
Deform the image.
参数: |
|
---|---|
返回: | An image. |
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.
参数: |
|
---|---|
返回: | An image. |
Add border to the image
参数: |
|
---|---|
返回: | An image. |
Returns a sized and cropped version of the image, cropped to the requested aspect ratio and size.
This function was contributed by Kevin Cazabon.
参数: |
|
---|---|
返回: | An image. |
Flip the image vertically (top to bottom).
参数: | image – The image to flip. |
---|---|
返回: | An image. |
Convert the image to grayscale.
参数: | image – The image to convert. |
---|---|
返回: | An image. |
Invert (negate) the image.
参数: | image – The image to invert. |
---|---|
返回: | An image. |
Flip image horizontally (left to right).
参数: | image – The image to mirror. |
---|---|
返回: | An image. |
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.
Color palette for palette mapped images
Given an rgb tuple, allocate palette entry.
警告
This method is experimental.
Get palette contents in format suitable # for the low-level im.putpalette primitive.
警告
This method is experimental.
Convert palette to bytes.
警告
This method is experimental.
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.
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, ...]. |
---|
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.
Gets the bounding box of the path.
返回: | (x0, y0, x1, y1) |
---|
Maps the path through a function.
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. |
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
The ImageQt module contains support for creating PyQt4 or PyQt5 QImage objects from PIL images.
1.1.6 新版功能.
Creates an ImageQt object from a PIL Image object. This class is a subclass of QtGui.QImage, which means that you can pass the resulting objects directly to PyQt4/5 API functions and methods.
This operation is currently supported for mode 1, L, P, RGB, and RGBA images. To handle other modes, you need to convert the image first.
The ImageSequence module contains a wrapper class that lets you iterate over the frames of an image sequence.
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 = index + 1
The ImageStat module calculates global statistics for an image, or for a region of an image.
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.
参数: |
|
---|
Min/max values for each band in the image.
Total number of pixels.
Sum of all pixels.
Squared sum of all pixels.
Average pixel level.
Median pixel level.
RMS (root-mean-square).
Variance.
Standard deviation.
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.
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. |
---|
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.
参数: |
|
---|
Paste a PIL image into the photo image. Note that this can be very slow if the photo image is displayed.
参数: |
|
---|
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)
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.
参数: |
|
---|
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.
Copy the bitmap contents to a device context.
参数: | handle – Device context (HDC), cast to a Python integer, or a HDC or HWND instance. In PythonWin, you can use the CDC.GetHandleAttrib() to get a suitable handle. |
---|
Load display memory contents from byte data.
参数: | buffer – A buffer containing display data (usually data returned from <b>tobytes</b>) |
---|
Paste a PIL image into the bitmap image.
参数: |
|
---|
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). |
The PSDraw module provides simple print support for Postscript printers. You can print text, graphics and images through this module.
Sets up printing to the given file. If file is omitted, sys.stdout is assumed.
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).
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
|
---|
Reference for modules whose documentation has not yet been ported or written can be found here.
Bases: PIL.FontFile.FontFile
Bases: PIL.Image.ImagePointHandler
Transform. This can be used with the procedural API, or with the standard Image.point() method.
Bases: exceptions.Exception
(pyCMS) Exception class. This is used for all errors in the pyCMS API.
(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 calcuation 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.
参数: |
|
---|---|
返回: | Either None, or a new PIL Image object, depending on the value of inPlace |
引发 PyCMSError: |
(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.
参数: |
|
---|---|
返回: | A CmsTransform class object. |
引发 PyCMSError: |
(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.
参数: |
|
---|---|
返回: | A CmsTransform class object. |
引发 PyCMSError: |
(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).
参数: |
|
---|---|
返回: | A CmsTransform class object. |
引发 PyCMSError: |
(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).
参数: |
|
---|---|
返回: | A CmsTransform class object. |
引发 PyCMSError: |
(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.
参数: |
|
---|---|
返回: | A CmsProfile class object |
引发 PyCMSError: |
(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 optomized) 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.
see the pyCMS documentation for details on rendering intents and what they do. |
引发 PyCMSError: |
(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 vaild 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: |
(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: |
(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: |
(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: |
(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: |
(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: |
(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: |
(experimental) Fetches the profile for the current display device. :returns: None if the profile is not known.
(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.
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.
参数: |
|
---|---|
返回: | 1 if the intent/direction are supported, -1 if they are not. |
引发 PyCMSError: |
(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.
参数: |
|
---|---|
返回: | Either None or a new PIL image object, depending on value of inPlace |
引发 PyCMSError: |
The ImageFileIO module can be used to read an image from a socket, or any other stream device.
Deprecated. New code should use the PIL.ImageFile.Parser class in the PIL.ImageFile module instead.
也可以参考
modules PIL.ImageFile.Parser
Bases: PIL.ImageShow.UnixViewer
Bases: PIL.ImageShow.Viewer
Bases: PIL.ImageShow.UnixViewer
Bases: PIL.ImageTransform.Transform
Bases: PIL.ImageTransform.Transform
Bases: PIL.ImageTransform.Transform
Bases: PIL.ImageTransform.Transform
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 is the practice of encoding images by implementing less resolution for chroma information than for luma information. (ref.: http://en.wikipedia.org/wiki/Chroma_subsampling)
Possible subsampling values are 0, 1 and 2 that correspond to 4:4:4, 4:2:2 and 4:1:1 (or 4:2:0?).
You can get the subsampling of a JPEG with the JpegImagePlugin.get_subsampling(im) function.
They are values use by the DCT (Discrete cosine transform) to remove unnecessary information from the image (the lossy part of the compression). (ref.: http://en.wikipedia.org/wiki/Quantization_matrix#Quantization_matrices, http://en.wikipedia.org/wiki/JPEG#Quantization)
You can get the quantization tables of a JPEG with:
im.quantization
This will return a dict with a number of arrays. You can pass this dict directly as the qtables argument when saving a JPEG.
The tables format between im.quantization and quantization in presets differ in 3 ways:
You can convert the dict format to the preset format with the JpegImagePlugin.convert_dict_qtables(dict_qtables) function.
Libjpeg ref.: http://www.jpegcameras.com/libjpeg/libjpeg-3.html
OleFileIO_PL: Module to read Microsoft OLE2 files (also called Structured Storage or Microsoft Compound Document File Format), such as Microsoft Office documents, Image Composer and FlashPix files, Outlook messages, ... This version is compatible with Python 2.6+ and 3.x
version 0.30 2014-02-04 Philippe Lagadec - http://www.decalage.info
Project website: http://www.decalage.info/python/olefileio
Improved version of the OleFileIO module from PIL library v1.1.6 See: http://www.pythonware.com/products/pil/index.htm
OleFileIO_PL changes are Copyright (c) 2005-2014 by Philippe Lagadec
See source code and LICENSE.txt for information on usage and redistribution.
WARNING: THIS IS (STILL) WORK IN PROGRESS.
OLE container object
This class encapsulates the interface to an OLE 2 structured storage file. Use the {@link listdir} and {@link openstream} methods to access the contents of this file.
Object names are given as a list of strings, one for each subentry level. The root entry should be omitted. For example, the following code extracts all image streams from a Microsoft Image Composer file:
ole = OleFileIO("fan.mic")
for entry in ole.listdir():
if entry[1:2] == "Image":
fin = ole.openstream(entry)
fout = open(entry[0:1], "wb")
while True:
s = fin.read(8192)
if not s:
break
fout.write(s)
You can use the viewer application provided with the Python Imaging Library to view the resulting files (which happens to be standard TIFF files).
Displays a part of FAT in human-readable form for debugging purpose
Displays a sector in a human-readable form, for debugging purpose.
Test if given filename exists as a stream or a storage in the OLE container.
filename: path of stream in storage tree. (see openstream for syntax) return: True if object exist, else False.
Parse standard properties streams, return an OleMetadata object containing all the available metadata. (also stored in the metadata attribute of the OleFileIO object)
new in version 0.25
Return root entry name. Should usually be ‘Root Entry’ or ‘R’ in most implementations.
Return size of a stream in the OLE container, in bytes.
filename: path of stream in storage tree (see openstream for syntax) return: size in bytes (long integer) raise: IOError if file not found, TypeError if this is not a stream.
Test if given filename exists as a stream or a storage in the OLE container, and return its type.
filename: path of stream in storage tree. (see openstream for syntax) return: False if object does not exist, its entry type (>0) otherwise:
- STGTY_STREAM: a stream
- STGTY_STORAGE: a storage
- STGTY_ROOT: the root entry
Return creation time of a stream/storage.
filename: path of stream/storage in storage tree. (see openstream for syntax) return: None if creation time is null, a python datetime object otherwise (UTC timezone)
new in version 0.26
Return modification time of a stream/storage.
filename: path of stream/storage in storage tree. (see openstream for syntax) return: None if modification time is null, a python datetime object otherwise (UTC timezone)
new in version 0.26
Return properties described in substream.
filename: path of stream in storage tree (see openstream for syntax) convert_time: bool, if True timestamps will be converted to Python datetime no_conversion: None or list of int, timestamps not to be converted
(for example total editing time is not a real timestamp)
return: a dictionary of values indexed by id (integer)
Read given sector from file on disk. sect: sector index returns a string containing the sector data.
Return a list of streams stored in this file
streams: bool, include streams if True (True by default) - new in v0.26 storages: bool, include storages if True (False by default) - new in v0.26 (note: the root storage is never included)
Adds the indexes of the given sector to the FAT sect: string containing the first FAT sector, or array of long integers return: index of last FAT sector.
Open an OLE2 file. Reads the header, FAT and directory.
filename: string-like or file-like object
Open a stream as a read-only file object (BytesIO).
return: file object (read-only) raise IOError if filename not found, or if this is not a stream.
Bases: PIL.FontFile.FontFile
Bases: PIL.ContainerIO.ContainerIO
Converts a 2-bytes (16 bits) string to an integer.
c: string containing bytes to convert o: offset of bytes to convert in string
The Python Imaging Library supports a wide variety of raster file formats. Nearly 30 different file formats can be identified and read by the library. Write support is less extensive, but most common interchange and presentation formats are supported.
The open() function identifies files from their contents, not their names, but the save() method looks at the name to determine which format to use, unless the format is given explicitly.
PIL reads and writes Windows and OS/2 BMP files containing 1, L, P, or RGB data. 16-colour images are read as P images. Run-length encoding is not supported.
The open() method sets the following info properties:
PIL identifies EPS files containing image data, and can read files that contain embedded raster images (ImageData descriptors). If Ghostscript is available, other EPS files can be read as well. The EPS driver can also write EPS images.
If Ghostscript is available, you can call the load() method with the following parameter to affect how Ghostscript renders the EPS
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)
PIL reads GIF87a and GIF89a versions of the GIF file format. The library writes run-length encoded GIF87a files. Note that GIF files are always read as grayscale (L) or palette mode (P) images.
The open() method sets the following info properties:
The GIF loader supports the seek() and tell() methods. You can seek to the next frame (im.seek(im.tell() + 1), or rewind the file by seeking to the first frame. Random access is not supported.
The GIF loader creates an image memory the same size as the GIF file’s logical screen size, and pastes the actual pixel data (the local image) into this image. If you only want the actual pixel rectangle, you can manipulate the size and tile attributes before loading the file:
im = Image.open(...)
if im.tile[0][0] == "gif":
# only read the first "local image" from this GIF file
tag, (x0, y0, x1, y1), offset, extra = im.tile[0]
im.size = (x1 - x0, y1 - y0)
im.tile = [(tag, (0, 0) + im.size, offset, extra)]
IM is a format used by LabEye and other applications based on the IFUNC image processing library. The library reads and writes most uncompressed interchange versions of this format.
IM is the only format that can store all internal PIL formats.
PIL reads JPEG, JFIF, and Adobe JPEG files containing L, RGB, or CMYK data. It writes standard and progressive JFIF files.
Using the draft() method, you can speed things up by converting RGB images to L, and resize images to 1/2, 1/4 or 1/8 of their original size while loading them. The draft() method also configures the JPEG decoder to trade some quality for speed.
The open() method sets the following info properties:
The save() method supports the following options:
注解
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.
2.4.0 新版功能.
PIL reads and writes JPEG 2000 files containing L, LA, RGB or RGBA data. It can also read files containing YCbCr data, which it converts on read into RGB or RGBA depending on whether or not there is an alpha channel. PIL supports JPEG 2000 raw codestreams (.j2k files), as well as boxed JPEG 2000 files (.j2p or .jpx files). PIL does not support files whose components have different sampling frequencies.
When loading, if you set the mode on the image prior to the load() method being invoked, you can ask PIL to convert the image to either RGB or RGBA rather than choosing for itself. It is also possible to set reduce to the number of resolutions to discard (each one reduces the size of the resulting image by a factor of 2), and layers to specify the number of quality layers to load.
The save() method supports the following options:
注解
To enable JPEG 2000 support, you need to build and install the OpenJPEG library, version 2.0.0 or higher, before building the Python Imaging Library.
Windows users can install the OpenJPEG binaries available on the OpenJPEG website, but must add them to their PATH in order to use PIL (if you fail to do this, you will get errors about not being able to load the _imaging DLL).
PIL identifies and reads MSP files from Windows 1 and 2. The library writes uncompressed (Windows 1) versions of this format.
PIL reads and writes PCX files containing 1, L, P, or RGB data.
PIL identifies, reads, and writes PNG files containing 1, L, P, RGB, or RGBA data. Interlaced files are supported as of v1.1.7.
The open() method sets the following info properties, when appropriate:
The save() method supports the following options:
注解
To enable PNG support, you need to build and install the ZLIB compression library before building the Python Imaging Library. See the distribution README for details.
PIL reads and writes PBM, PGM and PPM files containing 1, L or RGB data.
PIL reads and writes SPIDER image files of 32-bit floating point data (“F;32F”).
PIL also reads SPIDER stack files containing sequences of SPIDER images. The seek() and tell() methods are supported, and random access is allowed.
The open() method sets the following attributes:
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 home page at Wadsworth Center.
PIL reads and writes TIFF files. It can read both striped and tiled images, pixel and plane interleaved multi-band images, and either uncompressed, or Packbits, LZW, or JPEG compressed images.
If you have libtiff and its headers installed, PIL can read and write many more kinds of compressed TIFF files. If not, PIL will always write uncompressed files.
The open() method sets the following info properties:
Image resolution as an (xdpi, ydpi) tuple, where applicable. You can use the tag attribute to get more detailed information about the image resolution.
1.1.5 新版功能.
In addition, the tag attribute contains a dictionary of decoded TIFF fields. Values are stored as either strings or tuples. Note that only short, long and ASCII tags are correctly unpacked by this release.
The save() method can take the following keyword arguments:
A ImageFileDirectory object or dict object containing tiff tags and values. The TIFF field type is autodetected for Numeric and string values, any other types require using an ImageFileDirectory object and setting the type in tagtype with the appropriate numerical value from TiffTags.TYPES.
2.3.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
resolution
x resolution
y resolution
PIL reads and writes WebP files. The specifics of PIL’s capabilities with this format are currently undocumented.
The save() method supports the following options:
PIL reads and writes X bitmap files (mode 1).
PIL can read XV thumbnail files.
CUR is used to store cursors on Windows. The CUR decoder reads the largest available cursor. Animated cursors are not supported.
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.
PIL reads Autodesk FLI and FLC animations.
The open() method sets the following info properties:
PIL reads Kodak FlashPix files. In the current version, only the highest resolution image is read from the file, and the viewing transform is not taken into account.
注解
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.
The GBR decoder reads GIMP brush files.
The open() method sets the following info properties:
PIL reads uncompressed GD files. Note that this file format cannot be automatically identified, so you must use PIL.GdImageFile.open() to read such a file.
The open() method sets the following info properties:
ICO is used to store icons on Windows. The largest available icon is read.
PIL reads Mac OS X .icns files. By default, the largest available icon is read, though you can override this by setting the size property before calling load(). The open() method sets the following info property:
PIL reads Image Tools images containing L data.
PIL provides limited read support for IPTC/NAA newsphoto files.
PIL identifies and reads 8-bit McIdas area files.
MIC (read only)
PIL identifies and reads Microsoft Image Composer (MIC) files. When opened, the first sprite in the file is loaded. You can use seek() and tell() to read other sprites from the file.
PIL reads PhotoCD files containing RGB data. By default, the 768x512 resolution is read. You can use the draft() method to read the lower resolution versions instead, thus effectively resizing the image to 384x256 or 192x128. Higher resolutions cannot be read by the Python Imaging Library.
PIL identifies and reads PSD files written by Adobe Photoshop 2.5 and 3.0.
PIL reads uncompressed L, RGB, and RGBA files.
PIL reads 24- and 32-bit uncompressed and run-length encoded TGA files.
1.1.4 新版功能.
PIL reads Quake2 WAL texture files.
Note that this file format cannot be automatically identified, so you must use the open function in the WalImageFile module to read files in this format.
By default, a Quake2 standard palette is attached to the texture. To override the palette, use the putpalette method.
PIL reads X pixmap files (mode P) with 256 colors or less.
The open() method sets the following info properties:
PIL provides write-only support for PALM pixmap files.
The format code is Palm, the extension is .palm.
PIL can write PDF (Acrobat) images. Such images are written as binary PDF 1.1 files, using either JPEG or HEX encoding depending on the image mode (and whether JPEG support is available or not).
PIXAR (read only)
PIL provides limited support for PIXAR raster files. The library can identify and read “dumped” RGB files.
The format code is PIXAR.
1.1.3 新版功能.
PIL provides a stub driver for BUFR files.
To add read or write support to your application, use PIL.BufrStubImagePlugin.register_handler().
1.1.5 新版功能.
PIL provides a stub driver for FITS files.
To add read or write support to your application, use PIL.FitsStubImagePlugin.register_handler().
1.1.5 新版功能.
PIL provides a stub driver for GRIB files.
The driver requires the file to start with a GRIB header. If you have files with embedded GRIB data, or files with multiple GRIB fields, your application has to seek to the header before passing the file handle to PIL.
To add read or write support to your application, use PIL.GribStubImagePlugin.register_handler().
1.1.5 新版功能.
PIL provides a stub driver for HDF5 files.
To add read or write support to your application, use PIL.Hdf5StubImagePlugin.register_handler().
PIL identifies MPEG files.
PIL can identify placable WMF files.
In PIL 1.1.4 and earlier, the WMF driver provides some limited rendering support, but not enough to be useful for any real application.
In PIL 1.1.5 and later, the WMF driver is a stub driver. To add WMF read or write support to your application, use PIL.WmfImagePlugin.register_handler() to register a WMF handler.
from PIL import Image
from PIL import WmfImagePlugin
class WmfHandler:
def open(self, im):
...
def load(self, im):
...
return image
def save(self, im, fp, filename):
...
wmf_handler = WmfHandler()
WmfImagePlugin.register_handler(wmf_handler)
im = Image.open("sample.wmf")
The Python Imaging Library uses a plug-in model which allows you to add your own decoders to the library, without any changes to the library itself. Such plug-ins usually have names like XxxImagePlugin.py, where Xxx is a 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 decoder manually.
A decoder plug-in should contain a decoder class, based on the PIL.ImageFile.ImageFile base class. This class should provide an _open() method, which reads the file header and sets up at least the mode and size attributes. To be able to load the file, the method must also create a list of tile descriptors. The class must be explicitly registered, via a call to the Image module.
For performance reasons, it is important that the _open() method quickly rejects files that do not have the appropriate contents.
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("SPAM", SpamImageFile)
Image.register_extension("SPAM", ".spam")
Image.register_extension("SPAM", ".spa") # dos version
The format handler must always set the size and mode attributes. If these are not set, the file cannot be opened. To simplify the decoder, the calling code considers exceptions like SyntaxError, KeyError, and IndexError, as a failure to identify the file.
Note that the decoder must be explicitly registered using PIL.Image.register_open(). Although not required, it is also a good idea to register any extensions used by this format.
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:
Note that the tile attribute contains a list of tile descriptors, not just a single descriptor.
The raw decoder
The raw decoder is used to read uncompressed data from an image file. It can be used with most uncompressed file formats, such as PPM, BMP, uncompressed TIFF, and many others. To use the raw decoder with the PIL.Image.fromstring() function, use the following syntax:
image = Image.fromstring(
mode, size, data, "raw",
raw mode, stride, orientation
)
When used in a tile descriptor, the parameter field should look like:
(raw mode, stride, orientation)
The fields are used as follows:
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 (blue, green, red, pad). |
RGB;L | 24-bit true colour, line interleaved (first all red pixels, the all green pixels, finally all blue pixels). |
Note that for the most common cases, the raw mode is simply the same as the mode.
The Python Imaging Library supports many other decoders, including JPEG, PNG, and PackBits. For details, see the decode.c source file, and the standard plug-in implementations provided with the library.
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. |
If the raw decoder cannot handle your format, PIL also provides a special “bit” decoder that can be used to read various packed formats into a floating point image memory.
To use the bit decoder with the fromstring function, use the following syntax:
image = fromstring(
mode, size, data, "bit",
bits, pad, fill, sign, orientation
)
When used in a tile descriptor, the parameter field should look like:
(bits, pad, fill, sign, orientation)
The fields are used as follows:
Add bytes to the MSB end of the decoder buffer; store pixels from the LSB end.
If omitted, the fill order defaults to 0.
What follows is the original PIL 1.1.7 README file contents.
The Python Imaging Library
$Id$
Release 1.1.7 (November 15, 2009)
====================================================================
The Python Imaging Library 1.1.7
====================================================================
Contents
--------
+ Introduction
+ Support Options
- Commercial support
- Free support
+ Software License
+ Build instructions (all platforms)
- Additional notes for Mac OS X
- Additional notes for Windows
--------------------------------------------------------------------
Introduction
--------------------------------------------------------------------
The Python Imaging Library (PIL) adds image processing capabilities
to your Python environment. This library provides extensive file
format support, an efficient internal representation, and powerful
image processing capabilities.
This source kit has been built and tested with Python 2.0 and newer,
on Windows, Mac OS X, and major Unix platforms. Large parts of the
library also work on 1.5.2 and 1.6.
The main distribution site for this software is:
http://www.pythonware.com/products/pil/
That site also contains information about free and commercial support
options, PIL add-ons, answers to frequently asked questions, and more.
Development versions (alphas, betas) are available here:
http://effbot.org/downloads/
The PIL handbook is not included in this distribution; to get the
latest version, check:
http://www.pythonware.com/library/
http://effbot.org/books/imagingbook/ (drafts)
For installation and licensing details, see below.
--------------------------------------------------------------------
Support Options
--------------------------------------------------------------------
+ Commercial Support
Secret Labs (PythonWare) offers support contracts for companies using
the Python Imaging Library in commercial applications, and in mission-
critical environments. The support contract includes technical support,
bug fixes, extensions to the PIL library, sample applications, and more.
For the full story, check:
http://www.pythonware.com/products/pil/support.htm
+ Free Support
For support and general questions on the Python Imaging Library, send
e-mail to the Image SIG mailing list:
image-sig@python.org
You can join the Image SIG by sending a mail to:
image-sig-request@python.org
Put "subscribe" in the message body to automatically subscribe to the
list, or "help" to get additional information. Alternatively, you can
send your questions to the Python mailing list, python-list@python.org,
or post them to the newsgroup comp.lang.python. DO NOT SEND SUPPORT
QUESTIONS TO PYTHONWARE ADDRESSES.
--------------------------------------------------------------------
Software License
--------------------------------------------------------------------
The Python Imaging Library is
Copyright (c) 1997-2009 by Secret Labs AB
Copyright (c) 1995-2009 by Fredrik Lundh
By obtaining, using, and/or copying this software and/or its
associated documentation, you agree that you have read, understood,
and will comply with the following terms and conditions:
Permission to use, copy, modify, and distribute this software and its
associated documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appears in all
copies, and that both that copyright notice and this permission notice
appear in supporting documentation, and that the name of Secret Labs
AB or the author not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--------------------------------------------------------------------
Build instructions (all platforms)
--------------------------------------------------------------------
For a list of changes in this release, see the CHANGES document.
0. If you're in a hurry, try this:
$ tar xvfz Imaging-1.1.7.tar.gz
$ cd Imaging-1.1.7
$ python setup.py install
If you prefer to know what you're doing, read on.
1. Prerequisites.
If you need any of the features described below, make sure you
have the necessary libraries before building PIL.
feature library
-----------------------------------------------------------------
JPEG support libjpeg (6a or 6b)
http://www.ijg.org
http://www.ijg.org/files/jpegsrc.v6b.tar.gz
ftp://ftp.uu.net/graphics/jpeg/
PNG support zlib (1.2.3 or later is recommended)
http://www.gzip.org/zlib/
OpenType/TrueType freetype2 (2.3.9 or later is recommended)
support
http://www.freetype.org
http://freetype.sourceforge.net
CMS support littleCMS (1.1.5 or later is recommended)
support
http://www.littlecms.com/
If you have a recent Linux version, the libraries provided with the
operating system usually work just fine. If some library is
missing, installing a prebuilt version (jpeg-devel, zlib-devel,
etc) is usually easier than building from source. For example, for
Ubuntu 9.10 (karmic), you can install the following libraries:
sudo apt-get install libjpeg62-dev
sudo apt-get install zlib1g-dev
sudo apt-get install libfreetype6-dev
sudo apt-get install liblcms1-dev
If you're using Mac OS X, you can use the 'fink' tool to install
missing libraries (also see the Mac OS X section below).
Similar tools are available for many other platforms.
2. To build under Python 1.5.2, you need to install the stand-alone
version of the distutils library:
http://www.python.org/sigs/distutils-sig/download.html
You can fetch distutils 1.0.2 from the Python source repository:
svn export http://svn.python.org/projects/python/tags/Distutils-1_0_2/Lib/distutils/
For newer releases, the distutils library is included in the
Python standard library.
NOTE: Version 1.1.7 is not fully compatible with 1.5.2. Some
more recent additions to the library may not work, but the core
functionality is available.
3. If you didn't build Python from sources, make sure you have
Python's build support files on your machine. If you've down-
loaded a prebuilt package (e.g. a Linux RPM), you probably
need additional developer packages. Look for packages named
"python-dev", "python-devel", or similar. For example, for
Ubuntu 9.10 (karmic), use the following command:
sudo apt-get install python-dev
4. When you have everything you need, unpack the PIL distribution
(the file Imaging-1.1.7.tar.gz) in a suitable work directory:
$ cd MyExtensions # example
$ gunzip Imaging-1.1.7.tar.gz
$ tar xvf Imaging-1.1.7.tar
5. Build the library. We recommend that you do an in-place build,
and run the self test before installing.
$ cd Imaging-1.1.7
$ python setup.py build_ext -i
$ python selftest.py
During the build process, the setup.py will display a summary
report that lists what external components it found. The self-
test will display a similar report, with what external components
the tests found in the actual build files:
----------------------------------------------------------------
PIL 1.1.7 SETUP SUMMARY
----------------------------------------------------------------
*** TKINTER support not available (Tcl/Tk 8.5 libraries needed)
--- JPEG support available
--- ZLIB (PNG/ZIP) support available
--- FREETYPE support available
----------------------------------------------------------------
Make sure that the optional components you need are included.
If the build script won't find a given component, you can edit the
setup.py file and set the appropriate ROOT variable. For details,
see instructions in the file.
If the build script finds the component, but the tests cannot
identify it, try rebuilding *all* modules:
$ python setup.py clean
$ python setup.py build_ext -i
6. If the setup.py and selftest.py commands finish without any
errors, you're ready to install the library:
$ python setup.py install
(depending on how Python has been installed on your machine,
you might have to log in as a superuser to run the 'install'
command, or use the 'sudo' command to run 'install'.)
--------------------------------------------------------------------
Additional notes for Mac OS X
--------------------------------------------------------------------
On Mac OS X you will usually install additional software such as
libjpeg or freetype with the "fink" tool, and then it ends up in
"/sw". If you have installed the libraries elsewhere, you may have
to tweak the "setup.py" file before building.
--------------------------------------------------------------------
Additional notes for Windows
--------------------------------------------------------------------
On Windows, you need to tweak the ROOT settings in the "setup.py"
file, to make it find the external libraries. See comments in the
file for details.
Make sure to build PIL and the external libraries with the same
runtime linking options as was used for the Python interpreter
(usually /MD, under Visual Studio).
Note that most Python distributions for Windows include libraries
compiled for Microsoft Visual Studio. You can get the free Express
edition of Visual Studio from:
http://www.microsoft.com/Express/
To build extensions using other tool chains, see the "Using
non-Microsoft compilers on Windows" section in the distutils handbook:
http://www.python.org/doc/current/inst/non-ms-compilers.html
For additional information on how to build extensions using the
popular MinGW compiler, see:
http://mingw.org (compiler)
http://sebsauvage.net/python/mingw.html (build instructions)
http://sourceforge.net/projects/gnuwin32 (prebuilt libraries)
PIL 需要你!请帮助我们维护:
Pillow 是由 Alex Clark 领导的公益项目. 如果你不能支持开发,那么可以从经济上支持。
注解
下面列表是开发者和捐助链接
开发者 | 捐助链接 |
---|---|
Alex Clark (fork author) | http://gittip.com/aclark4life |