使用python自定义随机验证码
欢迎访问个人博客Potato Blog!!!!
class ImageCode:
"""生成随机的验证码"""
def rand_color(self):
"""获取随机颜色"""
red = random.randint(32, 127)
green = random.randint(32, 127)
blue = random.randint(32, 127)
# print(red, green, blue)
return red, green, blue
def get_text(self):
"""获取随机字符串"""
list = random.sample(string.ascii_letters + string.digits, 5)
# print("".join(list))
return "".join(list)
def draw_lines(self, draw, num, width, height):
for num in range(num):
x1 = random.randint(0, width / 2)
y1 = random.randint(0, height / 2)
x2 = random.randint(0, width)
y2 = random.randint(height / 2, height)
draw.line(((x1, y1), (x2, y2)), fill="black", width=2)
def draw_verify_code(self):
"""设置验证码"""
code = self.get_text()
width, height = 120, 50 # 设定图片大小
im = Image.new('RGB', (width, height), 'white') # 创建图片对象,设定背景颜色为白色
font = ImageFont.truetype(font="arial.ttf", size=40) # 选择字体类型,并设置大小
draw = ImageDraw.Draw(im) # 新建ImageDraw对象
for i in range(4): # 绘制字符串
draw.text((5 + random.randint(-3, 3) + 23 * i, 5 + random.randint(-3, 3)),
text=code[i], fill=self.rand_color(), font=font)
self.draw_lines(draw, 5, width, height) # 绘制干扰线
# im.show() #展示图片
return im, code
def get_code(self):
"""生成图片验证码,并返回给控制器"""
image, code = self.draw_verify_code()
buf = BytesIO()
image.save(buf, 'jpeg') # 保存至缓存区
bstring = buf.getvalue()
return code, bstring
if __name__ == '__main__':
ImageCode().get_text()
ImageCode().draw_verify_code()
如果要在浏览器上显示:
@user.route("/vcode") #蓝图
def vcode():
"""获取随机登录验证码"""
code, bstring = ImageCode().get_code()
response = make_response(bstring)
response.headers['Content-Type'] = 'image/jpeg'
session['vcode'] = code.lower()
return response