分类: Python/Ruby
2021-08-02 17:27:40
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 - 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))