生成5位随机数验证码图片

%matplotlib inline
from PIL import Image, ImageDraw, ImageFont
import random
# 获取字体以及大小
font = ImageFont.truetype("../../font/Arial.ttf", size=30)
# 随机数字:
def rndInt():
    return str(random.randint(0, 9))

# 随机颜色1:
def rndColor():
    return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

# 随机颜色2:
def rndColor2():
    return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

# 基础Settings:
width, height = 60 * 5, 60
image = Image.new('RGB', (width, height), (255, 255, 255))
# 创建Draw对象:
draw = ImageDraw.Draw(image)
# 填充每个像素:
for x in range(width):
    for y in range(height):
        draw.point((x, y), fill=rndColor())
# 输出文字:
for t in range(5):
    draw.text((60 * t + 10, 10), rndInt(), font=font, fill=rndColor2())
# # 模糊:
# from PIL import ImageFilter
# image = image.filter(ImageFilter.BLUR)

# 保存到硬盘,名为verify.png格式为png的图片
image.save(open('../../tmp/num_verify.png', 'wb'), 'png')
image

在这里插入图片描述

参考:https://www.liaoxuefeng.com/wiki/897692888725344/966759628285152

你可能感兴趣的:(训练营)