因为PIL仅支持到Python 2.7,加上年久失修,因而一群志愿者在PIL的基础上建立了兼容的版本,名字叫Pillow,支持最新Python 3.x,又加入了许多新特性,所以,咱们能够直接安装使用Pillow。python
安装Pillow
若是安装了Anaconda,Pillow就已经可用了。不然,须要在命令行下经过pip安装:git
$ pip install pillow
若是遇到Permission denied
安装失败,请加上sudo
重试。github
操做图像
来看看最多见的图像缩放操做,只需三四行代码:dom
from PIL import Image # 打开一个jpg图像文件,注意是当前路径: im = Image.open('test.jpg') # 得到图像尺寸: w, h = im.size print('Original image size: %sx%s' % (w, h)) # 缩放到50%: im.thumbnail((w//2, h//2)) print('Resize image to: %sx%s' % (w//2, h//2)) # 把缩放后的图像用jpeg格式保存: im.save('thumbnail.jpg', 'jpeg')
其余功能如切片、旋转、滤镜、输出文字、调色板等包罗万象。字体
好比,模糊效果也只需几行代码:spa
from PIL import Image, ImageFilter # 打开一个jpg图像文件,注意是当前路径: im = Image.open('test.jpg') # 应用模糊滤镜: im2 = im.filter(ImageFilter.BLUR) im2.save('blur.jpg', 'jpeg')
效果以下:操作系统
PIL的ImageDraw
提供了一系列绘图方法,让咱们能够直接绘图。好比要生成字母验证码图片:命令行
from PIL import Image, ImageDraw, ImageFont, ImageFilter import random # 随机字母: def rndChar(): return chr(random.randint(65, 90)) # 随机颜色1: def rndColor(): return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)) # 随机颜色2: def rndColor2(): return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)) # 240 x 60: width = 60 * 4 height = 60 image = Image.new('RGB', (width, height), (255, 255, 255)) # 建立Font对象: font = ImageFont.truetype('Arial.ttf', 36) # 建立Draw对象: draw = ImageDraw.Draw(image) # 填充每一个像素: for x in range(width): for y in range(height): draw.point((x, y), fill=rndColor()) # 输出文字: for t in range(4): draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2()) # 模糊: image = image.filter(ImageFilter.BLUR) image.save('code.jpg', 'jpeg')
咱们用随机颜色填充背景,再画上文字,最后对图像进行模糊,获得验证码图片以下:3d
若是运行的时候报错:code
IOError: cannot open resource
这是由于PIL没法定位到字体文件的位置,能够根据操做系统提供绝对路径,好比:
'/Library/Fonts/Arial.ttf'
要详细了解PIL的强大功能,请请参考Pillow官方文档:
https://pillow.readthedocs.org/
小结
PIL提供了操做图像的强大功能,能够经过简单的代码完成复杂的图像处理。
参考源码
https://github.com/michaelliao/learn-python3/blob/master/samples/packages/pil/use_pil_resize.py
https://github.com/michaelliao/learn-python3/blob/master/samples/packages/pil/use_pil_blur.py
https://github.com/michaelliao/learn-python3/blob/master/samples/packages/pil/use_pil_draw.py