Loading

Pillow模块——生成随机验证码

urls.py

path('get_code/',views.get_code),

views.py中

from PIL import Image,ImageFont,ImageDraw
"""
Image		产生图片
ImageFont	字体样式
ImageDraw	画笔对象
"""

from io import BytesIO,StringIO
"""
BytesIO     在内存中临时存储 读取的时候以bytes格式为准
StringIO    在内存中临时存储 读取的时候以字符串格式为准
"""

import random
def get_random()
	return random.randint(0,255),random.randint(0,255),random.randint(0,255)
	
def get_code_func(request)
    # 1.推导步骤1:直接读取图片文件返回
    # with open(r'F:\BBS\static\img\123.png','rb') as f:
    #     data = f.read()
    # return HttpResponse(data)
    # 2.推导步骤2:随机产生图片动态返回 第三方pillow模块
    # img_obj = Image.new('RGB',(350,35),'green')
    # with open(r'xxx.png','wb') as f:
    #     img_obj.save(f,'png')
    # with open(r'xxx.png','rb') as f:
    #     data = f.read()
    # return HttpResponse(data)
    # 3.推导步骤3:针对图片的保存与读取做优化 内存管理器
    # img_obj = Image.new('RGB',(350,35),'yellow')
    # io_obj = BytesIO()
    # img_obj.save(io_obj,'png')
    # return HttpResponse(io_obj.getvalue())
    # 4.推导步骤4:图片颜色是可以随机变换的
    # img_obj = Image.new('RGB',(350,35),get_random())
    # io_obj = BytesIO()
    # img_obj.save(io_obj,'png')
    # return HttpResponse(io_obj.getvalue())
    # 5.推导步骤5:编写验证码
    # 先产生图片对象
    img_obj = Image.new('RGB',(350,35),get_random())
    # 将图片对象交给画笔对象
    draw_obj = ImageDraw.Draw(img_obj)
    # 确定字体样式(ttf文件)
    font_obj = ImageFont.truetype('static/font/123.ttf',35)
    # 产生随机验证码
    code = ''
    for i in range(5):
        random_upper = chr(random.randint(65,90))
        random_lower = chr(random.randint(97,122))
        random_int = str(random.randint(0,9))
        # 三选一
        temp_choice = random.choice([random_upper,random_lower,random_int])
        # 写到图片上
        draw_obj.text((i*60 + 45 ,0),temp_choice,font=font_obj)
        code += temp_choice
    # 后端保存验证码 便于后续的比对
    request.session['code'] = code
    io_obj = BytesIO()
    img_obj.save(io_obj,'png')
    return HttpResponse(io_obj.getvalue())

html页面中

<img src="/get_code/" alt="" style="根据实际情况设置" id="code">

// 验证码动态刷新
    $('#code').click(function () {
        let oldSrc = $(this).attr('src');
        $(this).attr('src', oldSrc + '?')
    })
posted @ 2023-05-11 19:19  抱紧小洪  阅读(64)  评论(0编辑  收藏  举报