Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2546544
  • 博文数量: 271
  • 博客积分: 6659
  • 博客等级: 准将
  • 技术积分: 3141
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-17 10:24
文章分类

全部博文(271)

文章存档

2016年(2)

2015年(12)

2014年(7)

2013年(19)

2012年(22)

2011年(81)

2010年(128)

分类: 系统运维

2012-05-04 20:43:24

首先需要在setting当中启用 session的功能

点击(此处)折叠或打开

  1. import ImageFont,Image,ImageDraw,random
  2. cStringIO import StringIO

  3. def display(request):

  4.     background #随机靠山色彩
  5.     line_color #随机干扰线色彩
  6.     img_width = #画布宽度
  7.     img_height = #画布高度
  8.     font_color = #验证码字体色彩
  9.     font_size = #验证码字体尺寸
  10.     font = I#验证码字体

  11.     string = {'number':'12345679',
  12.               'litter':'ACEFGHKMNPRTUVWXY'}
  13.     background = (random.randrange(230,255),random.randrange(230,255),random.randrange(230,255))
  14.     line_color = (random.randrange(0,255),random.randrange(0,255),random.randrange(0,255))
  15.     img_width = 58
  16.     img_height = 30
  17.     font_color = ['black','darkblue','darkred']
  18.     font_size = 14
  19.     font = ImageFont.truetype('msyh.ttf',font_size)
  20.     request.session['verify'] = ''
  21.  
  22.     #新建画布
  23.     im = Image.new('RGB',(img_width,img_height),background)
  24.     draw = ImageDraw.Draw(im)
  25.     code = random.sample(string['litter'],4)
  26.     #code = u'调和社会'
  27.     #新建画笔
  28.     draw = ImageDraw.Draw(im)
  29.  
  30.     #画干扰线
  31.     for i in range(random.randrange(3,5)):
  32.         xy = (random.randrange(0,img_width),random.randrange(0,img_height),
  33.               random.randrange(0,img_width),random.randrange(0,img_height))
  34.         draw.line(xy,fill=line_color,width=1)
  35.      
  36.     #写入验证码文字
  37.     x = 2
  38.     for i in code:
  39.         y = random.randrange(0,10)
  40.         draw.text((x,y), i, font=font, fill=random.choice(font_color))
  41.         x += 14
  42.         request.session['verify'] += i
  43.     del x
  44.      
  45.     del draw
  46.     buf = StringIO()
  47.     im.save(buf,'gif'
  48.     buf.seek(0)
  49.     return HttpResponse(buf.getvalue(),'image/gif'

阅读(3064) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~