0%

Python练习册:0010

题目

    使用 Python 生成类似于下图中的字母验证码图片。

img

分析

阅读资料内容是如何生成随机字母,还需要使用pillow库建立画布,填充背景颜色和字母,模糊处理,显示结果,这里主要参考廖雪峰Python 教程中的Pillow部分的示例。

pip install pillow

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""
使用 Python 生成类似于下图中的字母验证码图片。
"""

from PIL import Image, ImageDraw, ImageFont, ImageFilter

import random
import string

# 随机字母:
def rndChar():
return random.choice(string.ascii_letters)

# 随机背景色:
def bkgColor():
return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

# 随机字母色:
def charColor():
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

# 容纳4个字符的宽度 240:
width = 60 * 4
height = 60
image = Image.new('RGB', (width, height), (255, 255, 255))
# 创建Font对象:
font = ImageFont.truetype('consolab.ttf', 42)
# 创建Draw对象:
draw = ImageDraw.Draw(image)
# 填充每个像素:
for x in range(width):
for y in range(height):
draw.point((x, y), fill=bkgColor())

# 输出文字:
letters = []
for t in range(4):
char = rndChar()
letters.append(char)
#随机偏移位置
draw.text((60 * t + random.randint(10,20), random.randint(10,20)),char, font=font, fill=charColor())

# 模糊:
image = image.filter(ImageFilter.BLUR)
image.save('code.png')

#显示
print(letters)
image.show()

参考

欢迎关注我的其它发布渠道