python 验证码总结

def verify_code():
codenum = 4
source = ''.join(map(str, range(10)))
code = ''.join(random.sample(source, 4))
print("verify code is :" + code)
# 将验证码存入session
session['verifyCode'] = code
# 设置图片大小
width = 45 * 5
height = 50
image = Image.new('RGB', (width, height), (255, 255, 255))
# 选择字体
font = ImageFont.truetype('/usr/local/arial.ttf', 36)
draw = ImageDraw.Draw(image)
for x in range(width):
for y in range(height):
colorRandom1 = (random.randint(255, 255), random.randint(255, 255), random.randint(255, 255))
draw.point((x, y), fill=colorRandom1)
for t in range(codenum):
colorRandom2 = (random.randint(85, 155), random.randint(85, 155), random.randint(85, 155))
draw.text((45 * t + 25, 10), code[t], font=font, fill=colorRandom2)
image_d = ImageDraw.Draw(image)
for i in range(5):
colorRandom3 = (random.randint(85, 100), random.randint(85, 100), random.randint(85, 100))
begin = (random.randint(0, width), random.randint(0, height))
end = (random.randint(0, width), random.randint(0, height))
image_d.line([begin, end], fill=colorRandom3)
tmps = BytesIO()
image.save(tmps, "jpeg")
res = Response()
res.headers.set("Content-Type", "image/JPEG;charset=UTF-8")
res.set_data(tmps.getvalue())
return res

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容