一、导入包
import random
from PIL import Image, ImageDraw, ImageFont
二、生成随机的验证码
def random_code(length=4):
'''默认返回4位随机验证码,字符串'''
code = ""
characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
for i in range(length):
rand_char = random.choice(characters)
code += rand_char
return code
三、生成随机的rgb颜色
def random_color():
"""默认返回随机颜色,元组"""
return random.randrange(256), random.randrange(256), random.randrange(256)
四、生成图片验证码
def image_code(width=120, height=30, point=100, line=4):
'''生成图片验证码'''
code = random_code()
color = random_color()
image = Image.new(mode='RGB', size=(width, height), color=(0, 0, 0)) # 背景图片
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("arial.ttf", 28) # 字体
for i, ch in enumerate(code):
draw.text([i * width / 4, 0], ch, fill=color, font=font)
for _ in range(point):
draw.point([random.randint(0, width), random.randint(0, height)], fill=random_color()) # 画点
for _ in range(line):
draw.line(
(random.randint(0, width),
random.randint(0, height),
random.randint(0, width),
random.randint(0, height)
),
fill=random_color()) # 画线
image.show()
# image.save(r'')
总结:
完整资源下载(上链接):https://download.csdn.net/download/SzyPy/89524730?spm=1001.2014.3001.5503