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

你可能感兴趣的:(python 验证码总结)