ImageFont表示字體對象,ubuntu的字體路徑爲「/usr/share/fonts/truetype/freefont」javascript
代碼以下:css
from django.http import HttpResponse def verifycode(request): #引入繪圖模塊 from PIL import Image, ImageDraw, ImageFont #引入隨機函數模塊 import random #定義變量,用於畫面的背景色、寬、高 bgcolor = (random.randrange(20, 100), random.randrange( 20, 100), 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 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0' #隨機選取4個值做爲驗證碼 rand_str = '' for i in range(0, 4): rand_str += str1[random.randrange(0, len(str1))] #構造字體對象 font = ImageFont.truetype('FreeMono.ttf', 23) #構造字體顏色 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 #內存文件操做 import io buf = io.StringIO() #將圖片保存在內存中,文件類型爲png im.save(buf, 'png') #將內存中的圖片數據返回給客戶端,MIME類型爲圖片png return HttpResponse(buf.getvalue(), 'image/png')
from . import viewsUtil urlpatterns = [ url(r'^verifycode/$', viewsUtil.verifycode), ]
<img id='verifycode' src="/verifycode/" alt="CheckCode"/>
<script type="text/javascript" src="/static/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(function(){ $('#verifycodeChange').css('cursor','pointer').click(function() { $('#verifycode').attr('src',$('#verifycode').attr('src')+1) }); }); </script> <img id='verifycode' src="/verifycode/?1" alt="CheckCode"/> <span id='verifycodeChange'>看不清,換一個</span>
<form method='post' action='/verifycodeValid/'> <input type="text" name="vc"> <img id='verifycode' src="/verifycode/?1" alt="CheckCode"/> <span id='verifycodeChange'>看不清,換一個</span> <br> <input type="submit" value="提交"> </form>
from django.http import HttpResponse def verifycodeValid(request): vc = request.POST['vc'] if vc.upper() == request.session['verifycode']: return HttpResponse('ok') else: return HttpResponse('no')
urlpatterns = [ url(r'^verifycodeValid/$', views.verifycodeValid), ]