Python:Pillow库自动生成图片验证码

hello,大家好,我是wangzirui32,今天我们来学习如何使用Pillow库自动生成图片验证码,开始学习吧!

1. 编写代码

代码如下:

from PIL import Image, ImageDraw, ImageFont
from random import choice, randint

def create_CAPTCHA_content():
    """
    生成验证码内容的函数
    :return:
    """
    # 验证码生成范围 26个字母和10个数字
    text = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

    CAPTCHA_text = ""
    for i in range(1, 5):  # 4位验证码
        CAPTCHA_text += choice(text)

    return CAPTCHA_text

# 创建新图像
image = Image.new("RGB", (100, 50), (124, 231, 122))
draw = ImageDraw.Draw(image)  # 创建画布
# 加载字体 是Windows自带的
font = ImageFont.truetype(r'C:\Windows\Fonts\simhei.ttf', size=30)

x = 15

for i in create_CAPTCHA_content(): # 随机验证码
	# 为每个验证码字符设置不同的RGB颜色
    R = str(randint(0, 255))
    G = str(randint(0, 255))
    B = str(randint(0, 255))

    draw.text((x, 10),
              text=i,
              font=font,
              fill="rgb(" + R + "," + G + "," + B + ")",
              direction=None)

    x += 20 

# 添加干扰线条
for i in range(1, randint(7, 15)): # 线条数量在7-15间
    x, y = randint(0, 100), randint(0, 50) # 线条起点
    x2, y2 = randint(0, 100), randint(0, 50) # 线条终点
	
	# 随机颜色
    R = str(randint(0, 255))
    G = str(randint(0, 255))
    B = str(randint(0, 255))
    # 绘制线条 宽度为2
    draw.line((x, y, x2, y2), fill="rgb(" + R + "," + G + "," + B + ")", width=2)

image.show()
image.save("CAPTCHA.png")

2. 结果展示

运行代码,保存的图片如下:
验证码
从图中可以清楚地看出,验证码内容为A9DM。


好了,今天的课程就到这儿了,我是wangzirui32,我们下次再见!

你可能感兴趣的:(Python,Python模块介绍使用,python)