python 图片验证码代码分享


Posted in Python onJuly 04, 2012
#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处理JSON时的值报错及编码报错的两则解决实录
Jun 26 Python
Python3.X 线程中信号量的使用方法示例
Jul 24 Python
python opencv之分水岭算法示例
Feb 24 Python
Python 获取主机ip与hostname的方法
Dec 17 Python
Python设计模式之策略模式实例详解
Jan 21 Python
pandas中的series数据类型详解
Jul 06 Python
python SVM 线性分类模型的实现
Jul 19 Python
python selenium登录豆瓣网过程解析
Aug 10 Python
Django 再谈一谈json序列化
Mar 16 Python
jupyter notebook tensorflow打印device信息实例
Apr 20 Python
python百行代码自制电脑端网速悬浮窗的实现
May 12 Python
python 爬取天气网卫星图片
Jun 07 Python
Python查询Mysql时返回字典结构的代码
Jun 18 #Python
python 实现堆排序算法代码
Jun 05 #Python
python 实现归并排序算法
Jun 05 #Python
python 实现插入排序算法
Jun 05 #Python
python 算法 排序实现快速排序
Jun 05 #Python
python操作MySQL数据库的方法分享
May 29 #Python
python利用elaphe制作二维条形码实现代码
May 25 #Python
You might like
PHP 中执行排序与 MySQL 中排序
2009/04/21 PHP
PHP连接MySQL查询结果中文显示乱码解决方法
2013/10/25 PHP
php 判断服务器操作系统的类型
2014/02/17 PHP
PHP SOCKET编程详解
2015/05/22 PHP
图片按比例缩放函数
2006/06/26 Javascript
javscript对象原型的一些看法
2010/09/19 Javascript
jQuery获得页面元素的绝对/相对位置即绝对X,Y坐标
2014/03/06 Javascript
jQuery移动web开发之页面跳转和加载外部页面的实现
2015/12/04 Javascript
BootStrap的弹出框(Popover)支持鼠标移到弹出层上弹窗层不隐藏的原因及解决办法
2016/04/03 Javascript
基于jQuery实现瀑布流页面
2017/04/11 jQuery
ES6中Array.copyWithin()函数的用法实例详解
2017/09/16 Javascript
AngularJS实现的select二级联动下拉菜单功能示例
2017/10/25 Javascript
Vue项目webpack打包部署到Tomcat刷新报404错误问题的解决方案
2018/05/15 Javascript
layer.open提交子页面的form和layedit文本编辑内容的方法
2019/09/27 Javascript
vue使用nprogress加载路由进度条的方法
2020/06/04 Javascript
浅谈vue中get请求解决传输数据是数组格式的问题
2020/08/03 Javascript
[03:09]2014DOTA2国际邀请赛 赛场上的美丽风景线 中国Coser也爱DOTA2
2014/07/20 DOTA
Python的面向对象编程方式学习笔记
2016/07/12 Python
详解Python中的相对导入和绝对导入
2017/01/06 Python
python 将对象设置为可迭代的两种实现方法
2019/01/21 Python
python区分不同数据类型的方法
2019/10/14 Python
Python图像处理库PIL的ImageEnhance模块使用介绍
2020/02/26 Python
Python HTMLTestRunner库安装过程解析
2020/05/25 Python
keras训练曲线,混淆矩阵,CNN层输出可视化实例
2020/06/15 Python
django template实现定义临时变量,自定义赋值、自增实例
2020/07/12 Python
浅谈CSS3动画的回调处理
2016/07/21 HTML / CSS
HTML5学习心得总结(推荐)
2016/07/08 HTML / CSS
澳大利亚排名第一的儿童在线玩具商店:Toy Galaxy
2018/10/06 全球购物
北京天润融通.net面试题笔试题
2012/02/20 面试题
介绍一下如何优化MySql
2016/12/20 面试题
学前教育毕业生自荐信范文
2013/12/24 职场文书
倡议书的格式写法
2015/04/28 职场文书
2015年预防青少年违法犯罪工作总结
2015/05/22 职场文书
JS创建或填充任意长度数组的小技巧汇总
2021/10/24 Javascript
MYSQL优化之数据表碎片整理详解
2022/04/03 MySQL
Python调用腾讯API实现人脸身份证比对功能
2022/04/04 Python