zoukankan      html  css  js  c++  java
  • verifycode验证码模版

    复制代码
    -- coding:utf-8 --
    from django.shortcuts import HttpResponse
    def verifycode(request):

    引入绘图模块

    from PIL import Image,ImageDraw,ImageFont

    引入随机函数模块

    import random

    定义变量,用于画面的背景色,宽,高

    bgcolor = (random.randrange(20,100),random.randrange(20,100),random.randrange(20,100))
    width = 100
    height = 50

    创建画面对象

    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)

    定义验证码的备用值

    str = '1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm'

    随机选取4个值作为验证码

    rand_str = ''
    for i in range(0,4):
    rand_str += str[random.randrange(0,len(str))]

    构造字体对象 把C盘的字体文件放到其它盘,因为C盘字体文件路径不好找

    font = ImageFont.truetype("E:simsunb.ttf", 36)
    fontcolor1 = (255, random.randrange(0,255), random.randrange(0,255))
    fontcolor2 = (255, random.randrange(0,255), random.randrange(0,255))
    fontcolor3 = (255, random.randrange(0,255), random.randrange(0,255))
    fontcolor4 = (255, random.randrange(0,255), random.randrange(0,255))

    绘制4个字

    draw.text((5,2), rand_str[0], font=font, fill=fontcolor1)
    draw.text((25,2), rand_str[1], font=font, fill=fontcolor2)
    draw.text((50,2), rand_str[2], font=font, fill=fontcolor3)
    draw.text((75,2), rand_str[3], font=font, fill=fontcolor4)

    释放画笔

    del draw

    request.session['verifycode'] = rand_str

    内存文件操作

    import io
    buf = io.BytesIO()

    将图片保存在内存中,文件类型为png

    im.save(buf,'png')

    将内存中的图片数据返回给客户端,MIME类型为图片png

    return HttpResponse(buf.getvalue(),'image/png')
    备注:
    code1 = request.session['verify'] 【登录获取图片上的验证码】
    code2 = request.POST.get('verifycode') 【获取登录表单上输入的验证码】

  • 相关阅读:
    使用Let`s encrypt 免费的https 证书
    iOS使用Security.framework进行RSA 加密解密签名和验证签名
    java aes_cbc_256 加密解密
    iOS CommonCrypto 对称加密 AES ecb,cbc
    openssl lhash 数据结构哈希表
    openssl stack 数据结构栈基本操作
    openssl pem 生成公钥和私钥及文件
    openssl evp RSA 加密解密
    Mac OS键盘常用快捷键
    PHP JSON 数据编码和解码
  • 原文地址:https://www.cnblogs.com/clearlove007/p/14347084.html
Copyright © 2011-2022 走看看