python 练习0010

问题

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

代码

主要有四部分:

  • 生成随机四位字母数字组合
  • 生成随机颜色
  • 填充噪点
  • 模糊处理
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random, string

def get_random_words():
    letters = string.ascii_letters + string.digits
    # 去除易混字符
    letters = letters.strip('iIoO0l')
    return ''.join([random.choice(letters) for _ in range(4)])

def get_random_color():
    return (random.randint(30, 100), random.randint(30, 100), random.randint(30, 100))

def get_random_code():
    width = 240
    height = 60
    # 灰布
    image = Image.new('RGB', (width, height), (180, 180, 180))
    # 字体
    font = ImageFont.truetype('arial.ttf', 40)
    draw = ImageDraw.Draw(image)
    words = get_random_words()
    for i in range(4):
        draw.text((60 * i + 10, 0), words[i], font=font, fill=get_random_color())
    # 填充噪点
    for _ in range(random.randint(1500, 3000)):
        draw.point((random.randint(0, width), random.randint(0, height)), fill=get_random_color())
    # 模糊处理
    image = image.filter(ImageFilter.BLUR)
    image.save('./pic/' + words + '.jpg')
if __name__ == '__main__':
    get_random_code()

参考链接 : Python Show-Me-the-Code 第 0010 题 生成验证码图片

猜你喜欢

转载自blog.csdn.net/m0_38015368/article/details/89321216