zoukankan      html  css  js  c++  java
  • django中自定义绘制验证码

    第一步,新建一个路由

    urlpatterns = [
        path('getcode/', views.getcode, name="getcode"),
    ]

    第二步,在views里建立视图函数

    from io import BytesIO
    import random
    from PIL import Image, ImageFont
    from PIL.ImageDraw import Draw, ImageDraw
    from django.conf import settings
    def get_color():
        return random.randrange(256)
    
    
    def generate_code():
        source = 'qazwscedvcrfbtgyhnujmik,olp0987654321QAZWSXEDCRFVTGBYHNUJMIK,OLP'
        code = ""
        for i in range(4):
            code += random.choice(source)
        return code
    
    
    def getcode(request):
        # 初始化画布,初始化画笔
        mode = "RGB"
        size = (200, 100)
        red = get_color()
        green = get_color()
        blue = get_color()
        color_bg = (red, green, blue)
        image = Image.new(mode=mode, size=size, color=color_bg)
        imagedraw = ImageDraw(image, mode=mode)
        imagefont = ImageFont.truetype(settings.FONT_PATH, 80)
    
        verify_code = generate_code()
        request.session['verify_code'] = verify_code
    
        for i in range(4):  # text的绘制
            fill = (get_color(), get_color(), get_color())
            imagedraw.text(xy=(50 * i, 0), text=verify_code[i], font=imagefont, fill=fill)
    
        for i in range(1000):  # 干扰点的绘制
            fill = (get_color(), get_color(), get_color())
            imagedraw.point(xy=(random.randrange(200), random.randrange(100)), fill=fill)
            # imagedraw.text(xy=(0, 0), text='Rock', font=imagefont)
    
        for i in range(10):  # 验证码中的干扰线
            fill = (get_color(), get_color(), get_color())
            imagedraw.line(xy=(random.randrange(200), random.randrange(100), random.randrange(200), random.randrange(100)),
                           fill=fill, width=random.randrange(5))
            # imagedraw.text(xy=(0, 0), text='Rock', font=imagefont)
    
        fp = BytesIO()
    
        image.save(fp, 'png')
    
        return HttpResponse(fp.getvalue(), content_type='image/png')  # 将图片返回到网页中

    第三步,需要去seeting里去配置FONT_PATH,

    FONT_PATH = "C:/Windows/Fonts/arialbd.ttf"

    里面的地址任意写,可以在项目的static下建立一个font在这里引入

    效果是

  • 相关阅读:
    安装oracle 使用vnc无法打开terminal,解决办法
    linux服务器配置本地yum仓库
    less css 框架介绍
    html的概念
    html
    WEB前端第三十八课——js类和对象,继承,设计模式
    WEB前端第三十七课——jsBOM操作-DataParse、jsEngine、性能、history、道岔、closure
    WEB前端第三十六课——jsBOM操作-window、timer
    WEB前端第三十五课——事件绑定应用案例
    WEB前端第三十四课——js事件对象this、event
  • 原文地址:https://www.cnblogs.com/ldlx-mars/p/12489023.html
Copyright © 2011-2022 走看看