Python生成图片验证码

安装库

1
2
#安装pillow模块
pip3 install pillow

生成验证码的代码

在随机字符串中,我并没用数字1,大写字母I,以及小写字母l。这3个实在是不好区分,所以我就没放。

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
import random
from PIL import Image, ImageDraw, ImageFont

# 随机颜色
def random_color():
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

def random_char(length):
# 随机选择字符
characters = "023456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ"
# 生成指定长度的验证码
code = ''.join(random.choice(characters) for i in range(length))
return code


def generate_captcha():
width, height = 160, 60
image = Image.new("RGB", (width, height), (255, 255, 255))
draw = ImageDraw.Draw(image)
# linux下可能没有这个字体,你可以使用DejaVuSans.ttf
font = ImageFont.truetype("arial.ttf", 36)

# 验证码图片
code = random_char(4)
for idx,t in enumerate(code):
# "rtl", "ltr",
draw.text((40 * idx + 10, 10), t, font=font, fill=random_color())

# 生成干扰点
for x in range(0,width,10):
for y in range(0,height,10):
draw.point((x, y), fill=(0,0,0))

# 添加干扰线
for i in range(3):
x1 = random.randint(0, width)
y1 = random.randint(0, height)
x2 = random.randint(0, width)
y2 = random.randint(0, height)
draw.line((x1, y1, x2, y2), fill=(0, 0, 0), width=2)
# image = image.filter(ImageFilter.GaussianBlur(radius=2))
image.save("captcha.jpg", "jpeg")

generate_captcha()