Python生成验证码实例

Python生成验证码实例,第1张

Python生成验证码实例

本文实例展示了Python生成验证码的方法,具有很好的实用价值。分享给大家供大家参考。具体实现方法如下:

前台页面代码如下:


   
 
 看不清换一张




后台程序如下:

import StringIO
import Image, ImageDraw, ImageFont, random  #相应的模块需要安装
from xxx.settings import authcode_font #请确保改字体存在

def make_image(request):
  mp = hashlib.md5()
  mp.update(str(datetime.datetime.now())+str(random.random()))  
  mp_src = mp.hexdigest()
  rand_str = mp_src[0:6]
  font = ImageFont.truetype(authcode_font, 25)
  width = 75
  height = 30
  im = Image.new('RGB',(width,height),'#%s'%mp_src[-7:-1])
  draw = ImageDraw.Draw(im)
  draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height)))
  draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height)))
  draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height)))
  draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height)))
  draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height)))
  draw.text((5,2), rand_str, font=font)  
  del draw  
  buffer = StringIO.StringIO()
  im.save(buffer,'jpeg')
  httpResponse = HttpResponse(content=buffer.getvalue(),mimetype="image/jpeg")
  request.session['auth_code'] = rand_str
  return httpResponse

程序效果如下:

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/3336130.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-10-06
下一篇 2022-10-06

发表评论

登录后才能评论

评论列表(0条)

保存