pillow
Pillow是PIL的一个派生分支,但如今已经发展成为比PIL本身更具活力的图像处理库。pillow可以说已经取代了PIL,将其封装成python的库(pip即可安装),且支持python2和python3。
Pillow的Github主页:https://github.com/python-pillow/Pillow Pillow的文档: https://pillow.readthedocs.org/en/latest/handbook/index.html
安装它很简单
pip install pillow
这里代码使用的是python3
几个基本的api说明及使用Demo
open
>>> from PIL import Image
>>> im = Image.open("hopper.ppm")
此函数意为从DCC中加载数据流,返回的是一个
Image的对象
format
>>> print(im.format, im.size, im.mode)
PPM (512, 512) RGB
format属性定义了图像的格式,如果图像不是从文件打开的,那么该属性值为None;size属性是一个2-tuple,表示图像的宽和高(单位为像素);mode属性为表示图像的模式,常用的模式为:L为灰度图,RGB为真彩色,CMYK为pre-press图像。如果文件不能打开,则抛出IOError异常。
show
>>> im.show()
在拥有Image对象后,可以通过show方法展示
如果仅仅只是调用
show方法是不能正确展示的,需要缓存Image对象
Image的读写
使用open()加载文件的时候,并不需要知道文件的格式,Image模块已经自动处理了!
使用save()保存Image对象;
转换jpg
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:
            with Image.open(infile) as im:
                im.save(outfile)
        except OSError:
            print("cannot convert", infile)
save()函数提供了第二个参数,,该参数指定了输出文件的格式。
构建jpg缩略图
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:
            with Image.open(infile) as im:
                im.thumbnail(size)
                im.save(outfile, "JPEG")
        except OSError:
            print("cannot create thumbnail for", infile)
该方法通过不完全加载的形式生成预览图,能有效高速地展示文件内容
鉴别图片类型
import sys
from PIL import Image
for infile in sys.argv[1:]:
    try:
        with Image.open(infile) as im:
            print(infile, im.format, f"{im.size}x{im.mode}")
    except OSError:
        pass
裁剪,粘贴,合并
crop是Image提供的api,用于控制Image的区域的。
从图片中复制区域
box = (100, 100, 400, 400)
region = im.crop(box)
区域是一个4-tuple值,左上角是 \((0, 0)\) 。
子区域的处理及粘贴
region = region.transpose(Image.ROTATE_180)
im.paste(region, box)
更多的处理请移步这里
Rolling an image
def roll(image, delta):
    """Roll an image sideways."""
    xsize, ysize = image.size
    delta = delta % xsize
    if delta == 0: return image
    part1 = image.crop((0, 0, delta, ysize))
    part2 = image.crop((delta, 0, xsize, ysize))
    image.paste(part1, (xsize-delta, 0, xsize, ysize))
    image.paste(part2, (0, 0, xsize-delta, ysize))
    return image
PREVIOUSUIelements的基本使用
NEXT面试试题