- 论坛徽章:
- 0
|
在项目中用到验证码,懒得去找,自己随便写了一个:
views.py:
def get_check_code_image(request,image='media/images/checkcode.gif'):
import Image, ImageDraw, ImageFont, random
im = Image.open(image)
draw = ImageDraw.Draw(im)
mp = md5.new()
mp_src = mp.update(str(datetime.now()))
mp_src = mp.hexdigest()
rand_str = mp_src[0:4]
draw.text((10,10), rand_str[0], font=ImageFont.truetype("ARIAL.TTF", random.randrange(25,50)))
draw.text((48,10), rand_str[1], font=ImageFont.truetype("ARIAL.TTF", random.randrange(25,50)))
draw.text((85,10), rand_str[2], font=ImageFont.truetype("ARIAL.TTF", random.randrange(25,50)))
draw.text((120,10), rand_str[3], font=ImageFont.truetype("ARIAL.TTF", random.randrange(25,50)))
del draw
request.session['checkcode'] = rand_str
buf = cStringIO.StringIO()
im.save(buf, 'gif')
return HttpResponse(buf.getvalue(),'image/gif')
urls.py:
from django.conf.urls.defaults import *
urlpatterns = patterns('tracer_server.apps.user.views',
# Uncomment this for admin:
# (r'^admin/', include('django.contrib.admin.urls')),
(r'^get_check_code_image/$', 'get_check_code_image'),
)
template:
[color="#0000ff"]
原文地址:
[url]http://openexperience.javaeye.com/blog/157549[/url]
转者注:
这个例子还需要下载Python Imaging Library(PIL),这里下载最新版本
[url]http://www.pythonware.com/products/pil/index.htm#pil116[/url]
还需要导入的模块:from datetime import datetime, import md5, cStringIO
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/84280/showart_2027476.html |
|