产生网站验证码图片的脚本
[总点击:443次]
2009年12月18日
近日想用 web.py 搭建一个网站,在登录部分想到用验证码,参考了网上的一些代码以后自己改写出想要的版本,其特点如下:
1) 图片内容为代数算式
2) 有线条干扰
3) 除去生成验证码图片外还返回一个元组: (filename, result)
使用倒是挺方便的,先放出源码,希望能启发大家。
这里有一张生成的图片:

源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | #!/usr/bin/env python # -*- coding: utf-8 -*- # Name: genpic.py # Author: xiooli <xioooli[at]yahoo.com.cn> # Site: http://joolix.com # Licence: GPLv3 # Version: 091218 '''用于产生网站验证码图片(代数算式)''' import Image,ImageDraw,ImageFont import random import math import hashlib import datetime def genpic(): '''生成验证码图片,返回一个元组(filename,result)''' #图片宽度 width = 130 #图片高度 height = 35 #背景颜色 bgcolor = (151, random.randint(0,225), random.randint(0,225)) #生成背景图片 image = Image.new('RGB',(width,height),bgcolor) #加载字体 font = ImageFont.truetype('/usr/share/fonts/TTF/DejaVuSans-Bold.ttf',27) #字体颜色 fontcolor = (0, 0, 0) #产生draw对象 draw = ImageDraw.Draw(image) # 生成算式 ops = ['+', '-'] op = random.choice(ops) num1 = random.randint(0, 99) num2 = random.randint(0, 99) rand_str = str(num1) + " " + op + " " + str(num2) result = str(eval(rand_str)) # 生成文件名 m = hashlib.md5() m.update(str(datetime.datetime.now())) fnm = m.hexdigest() #画字体,(0,0)是起始位置 draw.text((0,0),rand_str + ' =',font=font,fill=fontcolor) #画线 #线的颜色 linecolor= (random.randint(0,225), random.randint(0,225), random.randint(0,225)) for i in range(0,15): #随机产生线条 x1 = random.randint(0,width) x2 = random.randint(0,width) y1 = random.randint(0,height) y2 = random.randint(0,height) draw.line([(x1, y1), (x2, y2)], linecolor) #释放draw del draw #保存文件到本地 image.save(fnm + '.jpg') return (fnm, result) if __name__ == "__main__": pic = genpic() print pic |
最近评论