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') 【獲取登錄表單上輸入的驗證碼】

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM