def verify(request):
? ? #引入隨機(jī)函數(shù)模塊
? ? import random
? ? from PIL import Image, ImageDraw, ImageFont
? ? #定義變量,用于畫面的背景色纵东、寬爱态、高
? ? #bgcolor = (random.randrange(20, 100), random.randrange(
? ? #? ? 20, 100),100)
? ? bgcolor = (242,164,247)
? ? width = 100
? ? height = 25
? ? #創(chuàng)建畫面對(duì)象
? ? im = Image.new('RGB', (width, height), bgcolor)
? ? #創(chuàng)建畫筆對(duì)象
? ? draw = ImageDraw.Draw(im)
? ? #調(diào)用畫筆的point()函數(shù)繪制噪點(diǎn)
? ? 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)
? ? #定義驗(yàn)證碼的備選值
? ? #str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
? ? str1 = '0123456789'
? ? #隨機(jī)選取4個(gè)值作為驗(yàn)證碼
? ? rand_str = ''
? ? for i in range(0, 4):
? ? ? ? rand_str += str1[random.randrange(0, len(str1))]
? ? #構(gòu)造字體對(duì)象,ubuntu的字體路徑為“/usr/share/fonts/truetype/freefont”
? ? font = ImageFont.truetype('static/arial.ttf', 21)
? ? #font = ImageFont.load_default().font
? ? #構(gòu)造字體顏色
? ? fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
? ? #繪制4個(gè)字
? ? draw.text((5, -3), rand_str[0], font=font, fill=fontcolor)
? ? draw.text((25, -3), rand_str[1], font=font, fill=fontcolor)
? ? draw.text((50, -3), rand_str[2], font=font, fill=fontcolor)
? ? draw.text((75, -3), rand_str[3], font=font, fill=fontcolor)
? ? #釋放畫筆
? ? del draw
? ? #存入session燥翅,用于做進(jìn)一步驗(yàn)證
? ? request.session['verifycode'] = rand_str
? ? """
? ? python2的為
? ? # 內(nèi)存文件操作
? ? import cStringIO
? ? buf = cStringIO.StringIO()
? ? """
? ? # 內(nèi)存文件操作-->此方法為python3的
? ? import io
? ? buf = io.BytesIO()
? ? #將圖片保存在內(nèi)存中象对,文件類型為png
? ? im.save(buf, 'png')
? ? #將內(nèi)存中的圖片數(shù)據(jù)返回給客戶端蚕礼,MIME類型為圖片png
? ? return HttpResponse(buf.getvalue(), 'image/png')