python 图片验证码代码


Posted in Python onDecember 07, 2008

下面是一个实战项目的结果。

#coding: utf-8 
import Image,ImageDraw,ImageFont,os,string,random,ImageFilter 
def initChars(): 
""" 
允许的字符集合,初始集合为数字、大小写字母 
usage: initChars() 
param: None 
return: list 
返回允许的字符集和 
for: picChecker类初始字符集合 
todo: Nothing 
""" 
nums = [str(i) for i in range(10)] 
letterCase = [ 
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 
'w', 'x', 'y', 'z' 
] 
upperCase = [ 
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 
'W', 'X', 'Y', 'Z', 
] 
return(nums+letterCase+upperCase) 
class picChecker(): 
""" 
图片验证代码: 
1) 用户注册需填写图片验证码,以阻止机器人注册 
2) 图片验证码字符数为 4 位(大小写字母与数字,不区分大小写)。 
用户如果没有填写验证码或没有填写正确的验证码, 
页面友好性提示用户填写(同时程序方面也做相应限制) 
usage: pc = picChecker().createChecker() 
param: 很多,如下 
chars 允许的字符集合, 
类型 list 
默认值 initChars() 
例子 ['1','2','3'] 
length 字符串长度 
类型 integer 
默认值 4 
size 图片大小 
类型 tutle 
默认值 (120,30) 
例子 (120,30) 
fontsize 字体大小 
类型 integer 
默认值 25 
begin 字符其实位置,即左上角位置 
类型 tutle 
默认值 (5,-2) 
outputType 输出类型 
类型 string 
默认值 GIF 
可选值 GIF JPEG TIFF PNG 
mode 图片模式 
类型 string 
可选值 RGB L (还有其他模式,但只推荐这2种) 
默认值 RGB 
backgroundColor 背景色 
foregroundColor 前景色 
当mode=RGB时,backgroundColor,foregroundColor为tutle类型 
取值为(integer,integer,integer) 
表示RGB颜色值 
当mode=L时,backgroundColor,foregroundColor为数字,表示黑白模式 
取值为0-255 
表示灰度 
fonttype 字体路径 
类型 string 
默认值 "simsum.ttc" 
jamNum 干扰线条数 
类型 (int1,int1) 
int1 干扰线条数下限,包含 
int2 干扰线条数上线,包含 
pointBorder 散点噪音 
构造方法:对每个像素点使用随机函数确定是否在该像素上画散点噪音 
类型 (int1,int2) 
int1越大 散点越多 
int2越大 散点越少 
return: [picCheckerStr,pic] 
picCheckerStr: 表示返回图片中对应的字符串,可用于session验证以及其他用途 
pic : 返回的图片,类型为Image 
for : 
todo : Nothing 
""" 
#默认字体路径 
#DEFAULT_FONT_PATH = os.path.join(os.path.dirname(__file__),'simsun.ttc').replace('\\','/') 
def __init__(self,chars = initChars(),size = (120,30),fontsize = 25, 
begin = (5,-2),outputType = 'GIF',mode = 'RGB' , 
backgroundColor = (255,255,255), foregroundColor = (0,0,255), 
fonttype = "simsun.ttc",length = 4,jamNum = (1,2), 
pointBorder = (40,39)): 
""" 
初始化配置 
""" 
#验证码配置 
#允许的字符串 
self.chars = chars 
#图片大小 
self.size = size 
#字符起始插入点 
self.begin = begin 
#字符串长度 
self.length = length 
#输出类型 
self.outputType = outputType 
#字符大小 
self.fontsize = fontsize 
#图片模式 
self.mode = mode 
#背景色 
self.backgroundColor = backgroundColor 
#前景色 
self.foregroundColor = foregroundColor 
#干扰线条数 
self.jamNum = jamNum 
#散点噪音界限 
self.pointBorder = pointBorder 
#字体库路径 
self.fonttype = fonttype 
#设置字体,大小默认为18 
self.font = ImageFont.truetype(self.fonttype, self.fontsize) 
def getPicString(self): 
""" 
usage: getPicString() 
return: string 
for : 生成给定长度的随机字符串 
todo: Nothing 
""" 
#初始化字符串长度 
length = self.length 
#初始化字符集合 
chars = self.chars 
#获得字符集合 
selectedChars = random.sample(chars,length) 
charsToStr = string.join(selectedChars,'') 
return(charsToStr) 
def createChecker(self): 
""" 
usage: createChecker() 
return: [str,pic] 
str:对应的字符串 
pic:对应的图片 
for: 
todo: 
""" 
#获得验证码字符串 
randStr = self.getPicString() 
#将字符串加入空格 
randStr1 = string.join([i+" " for i in randStr],"") 
#创建图形 
im = Image.new(self.mode,self.size,self.backgroundColor) 
#创建画笔 
draw = ImageDraw.Draw(im) 
#输出随机文本 
draw.text(self.begin, randStr1, font=self.font,fill=self.foregroundColor) 
#im = self.drawText(draw,randStr,im) 
#干扰线 
self.createJam(draw) 
#散点噪音 
self.createPoints(draw) 
#图形扭曲 
para = [1-float(random.randint(1,2))/100, 
0, 
0, 
0, 
1-float(random.randint(1,10))/100, 
float(random.randint(1,2))/500, 
0.001, 
float(random.randint(1,2))/500 
] 
#print randStr,para 
im = im.transform(im.size, Image.PERSPECTIVE,para) 
#图像滤镜 
im=im.filter(ImageFilter.EDGE_ENHANCE_MORE) 
im.save("checker.jpg",self.outputType) 
return([randStr,im]) 
def createJam(self,draw): 
""" 
usage: 创建干扰线 
para: draw 表示画笔 
return: None 
for: 
todo: 
""" 
#干扰线条数 
lineNum = random.randint(self.jamNum[0],self.jamNum[1]) 
for i in range(lineNum): 
begin = (random.randint(0,self.size[0]),random.randint(0,self.size[1])) 
end = (random.randint(0,self.size[0]),random.randint(0,self.size[1])) 
draw.line([begin,end],fill = (0,0,0)) 
def createPoints(self,draw): 
""" 
usage: 创建散点噪音 
para: draw 表示画笔 
return: None 
for: 
todo: 
""" 
#散点噪音 
for x in range(self.size[0]): 
for y in range(self.size[1]): 
flag = random.randint(0,self.pointBorder[0]) 
if flag > self.pointBorder[1]: 
draw.point((x,y),fill = (0,0,0)) 
del flag 
if __name__ == '__main__': 
c=picChecker() 
t=c.createChecker() 
print(t)
Python 相关文章推荐
Python读写Redis数据库操作示例
Mar 18 Python
Python实现全局变量的两个解决方法
Jul 03 Python
python进阶教程之循环对象
Aug 30 Python
尝试用最短的Python代码来实现服务器和代理服务器
Jun 23 Python
Python实现批量读取图片并存入mongodb数据库的方法示例
Apr 02 Python
Python3.x爬虫下载网页图片的实例讲解
May 22 Python
python flask实现分页的示例代码
Aug 02 Python
Django 登陆验证码和中间件的实现
Aug 17 Python
pygame游戏之旅 添加icon和bgm音效的方法
Nov 21 Python
pyqt5利用pyqtDesigner实现登录界面
Mar 28 Python
Django celery异步任务实现代码示例
Nov 26 Python
Python爬虫中Selenium实现文件上传
Dec 04 Python
下载糗事百科的内容_python版
Dec 07 #Python
python 参数列表中的self 显式不等于冗余
Dec 01 #Python
Python GAE、Django导出Excel的方法
Nov 24 #Python
Python类的基础入门知识
Nov 24 #Python
Python 连连看连接算法
Nov 22 #Python
python sqlobject(mysql)中文乱码解决方法
Nov 14 #Python
Python转码问题的解决方法
Oct 07 #Python
You might like
用PHP制作静态网站的模板框架(四)
2006/10/09 PHP
php入门学习知识点二 PHP简单的分页过程与原理
2011/07/14 PHP
PHP中PDO连接数据库中各种DNS设置方法小结
2016/05/13 PHP
php实现登陆模块功能示例
2016/10/20 PHP
PHP中SQL查询语句的id=%d解释(推荐)
2016/12/10 PHP
thinkphp 验证码 的使用小结
2017/05/07 PHP
PHP使用zlib扩展实现GZIP压缩输出的方法详解
2018/04/09 PHP
PHP7 mongoDB扩展使用的方法分享
2019/05/02 PHP
TopList标签和JavaScript结合两例
2007/08/12 Javascript
jquery聚焦文本框与扩展文本框聚焦方法
2012/10/12 Javascript
javascript 获取HTML DOM父、子、临近节点
2014/06/16 Javascript
js动态切换图片的方法
2015/01/20 Javascript
JavaScript设置表单上传时文件个数的方法
2015/08/11 Javascript
jQuery实现的Tab滑动选项卡及图片切换(多种效果)小结
2015/09/14 Javascript
javascript对象的创建和访问
2016/03/08 Javascript
在html中引入外部js文件,并调用带参函数的方法
2016/10/31 Javascript
JS+CSS实现下拉刷新/上拉加载插件
2017/03/31 Javascript
NodeJs通过async/await处理异步的方法
2017/10/09 NodeJs
vue中post请求以a=a&b=b 的格式写遇到的问题
2018/04/27 Javascript
简单的React SSR服务器渲染实现
2018/12/11 Javascript
openlayers实现地图测距测面
2020/09/25 Javascript
python逐行读取文件内容的三种方法
2014/01/20 Python
Dlib+OpenCV深度学习人脸识别的方法示例
2019/05/14 Python
在PYQT5中QscrollArea(滚动条)的使用方法
2019/06/14 Python
python实现雪花飘落效果实例讲解
2019/06/18 Python
Python之pymysql的使用小结
2019/07/01 Python
html5摇一摇代码优化包括DeviceMotionEvent等等
2014/09/01 HTML / CSS
美国美发品牌:Bumble and Bumble
2016/10/08 全球购物
荷兰男士时尚网上商店:Suitable
2017/12/25 全球购物
办公自动化专业大学生职业规划书
2014/03/06 职场文书
金融学专业大学生职业生涯规划
2014/03/07 职场文书
拾金不昧表扬信怎么写
2015/05/04 职场文书
法定代表人免职证明
2015/06/24 职场文书
基于Python的EasyGUI学习实践
2021/05/07 Python
解决Mysql中的innoDB幻读问题
2022/04/29 MySQL
Python实现聚类K-means算法详解
2022/07/15 Python