一、生成Django验证码
1)验证码代码文件
def raw_code(request):
#随机背景颜色 background
#随机干扰线颜色 line_color
#画布宽度 img_width
#画布高度 img_height
#验证码字体颜色 font_color = ['black','darkblue','darkred']
#验证码字体尺寸 font_size
#验证码字体 font = ImageFont.truetype('ARIAL.TTF',font_size)
import random
from cStringIO import StringIO
from PIL import Image, ImageDraw
string = {'number': '12345679',
'litter': 'ACEFGHKMNPRTUVWXY'}
background = (random.randrange(230, 255), random.randrange(230, 255), random.randrange(230, 255))
line_color = (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255))
img_width = 80
img_height = 30
font_color = ['black', 'darkblue', 'darkred']
# font_size = 60
# 验证码字体
font = Const.CodeFont()
request.session['verify'] = ''
im = Image.new('RGB', (img_width, img_height), background)
code = random.sample(string['litter'], 4)
draw = ImageDraw.Draw(im)
for i in range(random.randrange(3, 5)):
xy = (random.randrange(0, img_width), random.randrange(0, img_height),
random.randrange(0, img_width), random.randrange(0, img_height))
draw.line(xy, fill=line_color, width=1)
x = 2
for i in code:
y = random.randrange(0, 10)
draw.text((x, y), i, font=font, fill=random.choice(font_color))
x += 14
request.session['verify'] += i
del draw
buf = StringIO()
im.save(buf, 'gif')
buf.seek(0)
return HttpResponse(buf.getvalue(), 'image/gif')
2)在上面文件中从下面const.py文件中引入 CodeFont
from tools.const import Const
#coding=utf-8
class Const(object):
def CodeFont():
import ImageFont
if not Const.CODE_FONT:
try:
f = Const.HERE + '/msyh.ttf'
Const.CODE_FONT = ImageFont.truetype(f, 14)
except:
Const.CODE_FONT = ImageFont.load_default()
return Const.CODE_FONT