zoukankan      html  css  js  c++  java
  • django 验证码图片生成视图函数

    def verify_code(request):
        import random
        # 定义验证码图片背景颜色 宽和高
        bgcolor = (random.randrange(20,180),random.randrange(20,180),255)
        width = 100
        height = 25
    
        # 创建画面对象
        im = Image.new('RGB',(width,height),bgcolor)
    
        # 创建画笔对象
        draw = ImageDraw.Draw(im)
    
        # 调用画笔的point()函数绘制噪点
        for i in range(0,100):
            xy = (random.randrange(0,width),random.randrange(0,height))
            fill = (random.randrange(0,255),255,random.randrange(0,255))
            draw.point(xy,fill=fill)
    
        # 定义验证码的备选值
        str1 = 'AQZSWRFEVCBGTHYNUMJKILOP123456789zxcbansdfqwyehrjtpk'
    
        # 随机选取4个值为验证码  或者6个值,不过图片宽和高,书写文字的间隔需要另外修改设置
        rand_str = ''
        for i in range(0,4):
            rand_str += str1[random.randrange(0,len(str1))]
    
        # 构造字体对象
        font = ImageFont.truetype('static/font/verdana.ttf',23)
        # 字体颜色
        def color():
            fontcolor = (255,random.randrange(0,255),random.randrange(0,255))
            return fontcolor
        # 绘制4个字
        draw.text((5 , 0), rand_str[0], font=font, fill=color())
        draw.text((25, 0), rand_str[1], font=font, fill=color())
        draw.text((50, 0), rand_str[2], font=font, fill=color())
        draw.text((75, 0), rand_str[3], font=font, fill=color())
    
    
        # 释放画笔
        del draw
    
        # 存入session中 用于对比
        request.session['verifycode'] = rand_str
    
        # 内存文件操作
        buf = BytesIO()
    
        # 将图片保存在内存中,文件类型为png
        im.save(buf,'png')
    
        # 将存放的图片返回给客户端 返回类型注意需要为图片
        # print(buf)
        # print(buf.getvalue())
        return HttpResponse(buf.getvalue(),'image/png')

    最终结果为 

  • 相关阅读:
    基于jenkins+gitlab的自动集成环境的搭建
    函数指针与委托
    详解C#break ,continue, return (转)
    REST 与 web service 的比较
    Python
    python
    python
    python
    python 1.0
    python 0.0
  • 原文地址:https://www.cnblogs.com/zengxm/p/11273124.html
Copyright © 2011-2022 走看看