需要安装模块pillow
pip3 install pillow
import random
from PIL import Image, ImageDraw, ImageFont
随机生成验证码
def generate_code(length):
characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
code = ''.join(random.choice(characters) for i in range(length))
return code
生成验证码图片
def generate_image(code, width, height, font_size):
img = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255))
draw = ImageDraw.Draw(img)
font = ImageFont.truetype('arial.ttf', font_size)
bbox = draw.textbbox((0, 0, width, height), code, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
x = (width - text_width) // 2
y = (height - text_height) // 2
draw.text((x, y), code, font=font, fill=(0, 0, 0))
for i in range(5):
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)
for i in range(50):
x = random.randint(0, width)
y = random.randint(0, height)
draw.point((x, y), fill=(0, 0, 0))
return img
保存验证码图片
def save_image(img, path):
img.save(path)
测试
if __name__ == '__main__':
code = generate_code(4)
img = generate_image(code, 150, 50, 30)
save_image(img, 'captcha.png')
img.show()