django|python中图形验证码的实现
作者 : admin 于 2010-03-23 14:01:08
2010
03-23
03-23
python自己并没有带图型库,需要借助第三方的图形库来实现。原来习惯的就是php下的gd库,但网上搜索后普遍说gd的python接口不好用,又考虑php也即将抛弃dg,就选择了很多人推荐的 PIL(python image library) 库。
首先是安装此库,http://www.pythonware.com/products/pil/index.htm
选择自己相应版本和平台进行安装,安装文档写的还算清楚。
然后是代码实现:
- import Image, ImageDraw, ImageFont, md5, random,cStringIO,util
- def show(request):
- im = Image.new('RGBA',(52,18),(50,50,50,50))
- draw = ImageDraw.Draw(im)
- rands = util.rand(4) //自己写的一个取随机字符串的函数
- draw.text((2,0), rands[0], font=ImageFont.truetype("tahomabd.TTF", random.randrange(12,18)), fill='white')
- draw.text((14,0), rands[1], font=ImageFont.truetype("tahomabd.TTF", random.randrange(12,18)), fill='yellow')
- draw.text((27,0), rands[2], font=ImageFont.truetype("tahomabd.TTF", random.randrange(12,18)), fill='yellow')
- draw.text((40,0), rands[3], font=ImageFont.truetype("tahomabd.TTF", random.randrange(12,18)), fill='white')
- del draw
- request.session['checkcode'] = rands
- buf = cStringIO.StringIO()
- im.save(buf, 'gif')
- return HttpResponse(buf.getvalue(),'image/gif')
修改urls.py文件
- #check code
- (r'^checkcode/','view.checkcode.show'),
再访问 http://127.0.0.1/checkcode/ 既可看到效果。
官方的手册写的比较惨,属于找什么没什么。顺便把网上找到的一个写的不错的文档传送来:http://nadiana.com/pil-tutorial-basic-advanced-drawing
三月 25th, 2010 at 14:04:44
参见我做的实例:http://www.2maomao.com/blog/django-newform-captcha/
三月 26th, 2010 at 16:38:59
md5是干什么用的呀???