Python生成验证码实例,python验证码实例


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

前台页面代码如下:

<div>
 <img id="authcode_img" alt="验证码" src="/registration/makeimage/{{time}}"/>  
 <!-- time 任意随机数(时间戳),防止页面缓存 导致验证码不能更新-->
 <a href="javascript:refreshCode();" rel="external nofollow" style="color:blue;">看不清换一张</a>
</div>

<script>
 function refreshCode() {
   $('authcode_img').src = "/registration/makeimage/" + Math.random();
 }
</script>

后台程序如下:

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

程序效果如下:


python人人网自动登录怎处理验证码,否则不可以实现自动登录呀高人指点

碰到验证码咋办?这里分两种情况处理:
-
1.google那种验证码,凉拌
-
2.简单的验证码:字符个数有限,只使用了简单的平移或旋转加噪音而没有扭曲的,这种还是有可能可以处理的,一般思路是旋转的转回来,噪音去掉,
然后划分单个字符,划分好了以后再通过特征提取的方法(例如PCA)降维并生成特征库,然后把验证码和特征库进行比较。这个比较复杂,一篇博文是说不完
的,这里就不展开了,具体做法请弄本相关教科书好好研究一下。
-
3.事实上有些验证码还是很弱的,这里就不点名了,反正我通过2的方法提取过准确度非常高的验证码,所以2事实上是可行的。
 

怎通过python获取验证码图片?

因为验证码图片是禁止缓存的 ,当然无法用缓存函数获取了。 解决方法有很多。可以用同样的会话再次请求得到图片。关于此类图片保存在哪里,请阅读相关资料
 

评论关闭