• Django 定制验证码


    一、图片验证码

    方式一:

    def get_validCode_img(request):
        path=os.path.join(settings.BASE_DIR,'static','image','1.jpg')
        with open(path,'rb') as f:
            img=f.read()
            return HttpResponse(img)
    

    二、自定义图片验证码磁盘管理

    方式二:

    def get_validCode_img(request):
        from PIL import Image
        img=Image.new(mode='RGB',size=(120,30),color='green')
        f=open('validCode.png','wb')
        img.save(f,'png')
        with open('validCode.png', 'rb') as f:
            data=f.read()
            return HttpResponse(data)
    

    三、自定义图片验证码内存管理

    方式三:

    def get_validCode_img(request):
        from io import BytesIO    # 内存管理
        from PIL import Image
        img = Image.new(mode='RGB', size=(120, 30), color='blue')
        f = BytesIO()    # 文件句柄
        img.save(f, 'png')
    
        data=f.getvalue()
    
        return HttpResponse(data)
    

    四、自定义图片验证码画图

    方式四:

    def get_validCode_img(request):
        from io import BytesIO  # 内存管理
        from PIL import Image,ImageDraw,ImageFont
        from random import randint,choice
        color=(randint(0,255),randint(0,255),randint(0,255))
        img = Image.new(mode='RGB', size=(120, 30), color=color)
    
        draw=ImageDraw.Draw(img,"RGB")
        font=ImageFont.truetype("static/fonts/kumo.ttf",20)
    
        valid_list=[]
        for i in range(5):
            random_num=str(randint(0,9))
            random_lower=chr(randint(65,90))   # 小写字母
            random_upper=chr(randint(97,122))  # 大写字母
    
            random_chr=choice([random_num,random_lower,random_upper])
            draw.text([10+i*22,2],random_chr,color=color,font=font)
            valid_list.append(random_chr)
    
        f = BytesIO()  # 文件句柄
        img.save(f, 'png')
        data = f.getvalue()
        valid_str="".join(valid_list)
        print(valid_str)
        request.session["keepValidCode"]=valid_str
        return HttpResponse(data)  

    字体地址:

    https://files.cnblogs.com/files/supery007/blogCMS.rar  

      

      

  • 相关阅读:
    Java 注解
    java多线程
    webstorm配置Monokai-Sublime.jar主题
    express
    npm与package.json
    Node require方法加载规则
    js伪数组转数组
    node中的Console
    Node.js核心模块-url
    服务端渲染SSR和客户端渲染CSR
  • 原文地址:https://www.cnblogs.com/supery007/p/7866561.html
Copyright © 2020-2023  润新知