flask 前后端验证码实现
程序员文章站
2024-03-20 21:32:10
...
from PIL import Image, ImageFont, ImageDraw, ImageFilter
import random
def validate_picture():
total = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345789'
width = 130
heighth = 50
im = Image.new('RGB',(width, heighth), 'white')
font = ImageFont.truetype(r'D:\ProgramData\Miniconda3\envs\python3.6\Library\lib\fonts\VeraSeBd.ttf',30)
draw = ImageDraw.Draw(im)
str = ''
for item in range(5):
text = random.choice(total)
str += text
draw.text((5+random.randint(4,7)+20*item,5+random.randint(3,7)), text=text, fill='black',font=font )
for num in range(8):
x1 = random.randint(0, width/2)
y1 = random.randint(0, heighth/2)
x2 = random.randint(0, width)
y2 = random.randint(heighth/2, heighth)
draw.line(((x1, y1),(x2,y2)), fill='black', width=1)
im = im.filter(ImageFilter.FIND_EDGES)
return im, str
#返回验证码图片和验证码字符串
@auth.route('/code')
def get_code():
image, str = validate_picture()
# 将验证码图片以二进制形式写入在内存中,防止将图片都放在文件夹中,占用大量磁盘
buf = BytesIO()
image.save(buf, 'jpeg')
buf_str = buf.getvalue()
# 把二进制作为response发回前端,并设置首部字段
response = make_response(buf_str)
response.headers['Content-Type'] = 'image/gif'
# 将验证码字符串储存在session中
session['image'] = str
return response
#将图片返回前端
前端:
<div class="col-md-4" style="text-align:left;">
<!--点击图片重新获取验证码-->
<img src="/code " onclick="this.src='/code?'+ Math.random()" style="cursor:pointer;margin-left: 3%"><span style="color:blue;">(点击图片刷新)</span>
</div>
上一篇: 前后端分离验证码方案
下一篇: JAVA导出数据到CSV文件