>>> from env_helper import info; info()
页面更新时间: 2024-04-06 23:06:41
运行环境:
    Linux发行版本: Debian GNU/Linux 12 (bookworm)
    操作系统内核: Linux-6.1.0-18-amd64-x86_64-with-glibc2.36
    Python版本: 3.11.2

3.13. 实例: 使用Pillow生成验证码

我们在前面只是使用了Pillow 的读取图片功能,Pillow库同样可以用户生成图片,比如我们经常见到的验证码,下面我们就使用Pillow来生成验证码。

3.13.1. 场景描述

我们在应用注册或者登陆时,会输入验证码进行验证,那么验证码是如何生成的呢,我们使用Pillow来测试一下。

3.13.2. 解决思路

先生成随机数,在将随机数保存为图片。

3.13.3. 解决办法

我们主要利用前面讲过的办法,主要有图片的剪裁、缩放、写入文字、旋转、填充、保存等功能。

>>> from PIL import Image,ImageDraw,ImageFont
>>> import random
>>> import string

设置图片的大小,文字的字体、大小、颜色设置为随机选取,这样看起来更加美观。

>>> size=(200,100)
>>> fontSize=30
>>> font = ImageFont.truetype('VeraMoBI.ttf',fontSize)
>>> image1 = Image.new('RGBA',size,(255,)*4)
>>> texts = ''.join(random.sample(string.ascii_letters + string.digits, 5))

开始向图片内添加字符串,并将字体进行旋转,遍历结束后保存。

>>> x = 10
>>> xplus = 15
>>> for text in texts:
>>>     fontColor = (random.randint(0,250),random.randint(0,250),random.randint(0,250))
>>>     draw = ImageDraw.Draw(image1)
>>>     draw.text((x,4),text,fill=fontColor,font=font)
>>>     rot = image1.rotate(random.randint(-10,10),expand=0)
>>>     fff = Image.new('RGBA',rot.size,(255,)*4)
>>>     image1 = Image.composite(rot,fff,rot)
>>>     x += xplus
>>>
>>> image1.save('xx_demo_p.png')

查看一下结果:

_images/xx_demo_p.png

3.13.4. 总结

程序自上向下执行,所以并不难理解,用到的都是我们在前面讲到的内容,知识的灵活运用才是最重要的。