flask 前后端验证码实现

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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值