1赃阀、View
def verification_code(request):
bgcolor = (random.randrange(20, 100), random.randrange(20, 100), 255)
width = 100
height = 25
# 創(chuàng)建畫面對象
# im = Image.new('RGB', (width, height), bgcolor)
im = Image.new('RGB', (width, height), (255, 255, 255))
# 創(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)造字體對象
font = ImageFont.truetype('simsun.ttc', 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
# 創(chuàng)建內(nèi)存讀寫的對象
buf = BytesIO()
# 將圖片保存在內(nèi)存中第练,文件類型為png
im.save(buf, 'png')
# 放入session中
request.session['verificationcode'] = rand_str
request.session.set_expiry(0)
return HttpResponse(buf.getvalue(), 'image/png')
2贮预、Template
<td>驗證碼</td>
<td><input type="text" name="verificationcode"/></td>
<td><img src="/user/verification_code" alt="驗證碼" id="verificationcode"/></td>
<script>
window.onload = function(){
src = "/user/verification_code?n="
code = document.getElementById("verificationcode")
//為驗證碼添加click事件
code.onclick = function(){
code.src = src + new Date().getTime()
}
}
</script>