python如何生成網(wǎng)頁驗證碼
本文實例為大家分享了python生成網(wǎng)頁驗證碼的具體代碼,供大家參考,具體內(nèi)容如下
驗證碼為pil模塊生成,可直接應(yīng)用于django框架當中。
首先需要安裝Pillow模塊 我們這里使用的版本為3.4.1
終端中直接輸入指令 pip install Pillow==3.4.1
from PIL import Image, ImageDraw, ImageFont
from django.utils.six import BytesIO
def verify_code(request):
#引入隨機函數(shù)模塊
import random
#定義變量,用于畫面的背景色、寬、高
bgcolor = (random.randrange(20, 100), random.randrange(
20, 100), 255)
width = 100
height = 25
#創(chuàng)建畫面對象
im = Image.new('RGB', (width, height), bgcolor)
#創(chuàng)建畫筆對象
draw = ImageDraw.Draw(im)
#調(diào)用畫筆的point()函數(shù)繪制噪點
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 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
#隨機選取4個值作為驗證碼
rand_str = ''
for i in range(0, 4):
rand_str += str1[random.randrange(0, len(str1))]
#構(gòu)造字體對象,ubuntu的字體路徑為“/usr/share/fonts/truetype/freefont”
font = ImageFont.truetype('FreeMono.ttf', 23)
#構(gòu)造字體顏色
fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
#繪制4個字
draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
#釋放畫筆
del draw
#存入session,用于做進一步驗證
request.session['verifycode'] = rand_str
#內(nèi)存文件操作
buf = BytesIO()
#將圖片保存在內(nèi)存中,文件類型為png
im.save(buf, 'png')
#將內(nèi)存中的圖片數(shù)據(jù)返回給客戶端,MIME類型為圖片png
return HttpResponse(buf.getvalue(), 'image/png'
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python調(diào)用短信貓控件實現(xiàn)發(fā)短信功能實例
這篇文章主要介紹了python調(diào)用短信貓控件實現(xiàn)發(fā)短信功能實例,需要的朋友可以參考下2014-07-07
python 非線性規(guī)劃方式(scipy.optimize.minimize)
今天小編就為大家分享一篇python 非線性規(guī)劃方式(scipy.optimize.minimize),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
python嵌套函數(shù)使用外部函數(shù)變量的方法(Python2和Python3)
這篇文章主要介紹了python嵌套函數(shù)使用外部函數(shù)變量的方法,需要的朋友可以參考下2016-01-01
Python import與from import使用和區(qū)別解讀
Python程序可以調(diào)用一組基本的函數(shù)(即內(nèi)建函數(shù)),比如print()、input()和len()等函數(shù)。接下來通過本文給大家介紹Python import與from import使用及區(qū)別介紹,感興趣的朋友一起看看吧2021-09-09

