from PIL import Image, ImageDraw, ImageFont
from random import choice, randint, randrange
import string
候选字符集, 大小写字母 + 数字
chrs = string.ascii_letters + string.digits
def rand_chars(length):
“””
返回 length 个随机字符串
“””
result = ”.join(choice(chrs) for _ in range(length))
return result
def rand_color():
“””
设置随机色彩
“””
r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)
return (r, g, b)
def draw_rand_line(num, size, draw):
"""绘制随机烦扰线"""
# 绘制随机烦扰线,这里设置为 8 条
for i in range(num):
start = (0, randrange(size[1]))
end = (size[0], randrange(size[1]))
draw.line([start, end], fill=rand_color(), width=1)
# 绘制随机弧线
for i in range(8):
start = (-50, -50) # 起始地位在外边看起来才会像弧线
end = (size[0]+10, randint(0, size[1]+10))
draw.arc(start+end, 0, 360, fill=rand_color())
def draw_rand_point(size, draw):
"""绘制随机烦扰点"""
for i in range(int(size[0]*size[1]*0.07)): # 7% 密度的烦扰像素
draw.point((randrange(size[0]), randrange(size[1])), fill=rand_color()) # randrange 取值范畴是左开右闭
def verify_code(size, chrNumber, bgcolor=(255, 255, 255)):
"""定义图片大小,验证码长度,背景色彩"""
# 创立空白图像
image = Image.new('RGB', size, bgcolor)
# 创立绘图对象
draw = ImageDraw.Draw(image)
# 创立 font 对象
font = ImageFont.truetype('c:\\windows\\fonts\\Arial.ttf', 48) # 选定一款零碎字体
# 生成并计算随机字符的宽度和高度
text = rand_chars(chrNumber)
width, height = draw.textsize(text, font)
# 绘制字符串
x_start = 5
char_w = width // chrNumber - [股指期货](https://www.gendan5.com/ff/sf.html)2 # 计算每个字符宽度
for i in range(chrNumber):
position = (x_start, (size[1]-height)//2+randint(-10, 10)) # 字符坐标, Y 坐标高低浮动
draw.text(xy=position, text=text[i], font=font, fill=rand_color()) # 绘制函数
x_start += char_w + 1
image.show()
# 绘制随机色彩随机地位的烦扰像素
draw_rand_point(size, draw)
image.show()
# 绘制烦扰线
draw_rand_line(8, size, draw)
image.show()
# 保留图片
image.save('Veri_code.jpg')
if name == “__main__”:
# load_image()
verify_code((200, 100), 6, (255, 255, 255))