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多线程http下载实现示例
Dec 30 Python
Python中Collection的使用小技巧
Aug 18 Python
讲解Python中运算符使用时的优先级
May 14 Python
python获取当前运行函数名称的方法实例代码
Apr 06 Python
利用PyInstaller将python程序.py转为.exe的方法详解
May 03 Python
python如何通过实例方法名字调用方法
Mar 21 Python
python matplotlib绘图,修改坐标轴刻度为文字的实例
May 25 Python
python 常用的基础函数
Jul 10 Python
Python3 使用cookiejar管理cookie的方法
Dec 28 Python
python3使用matplotlib绘制条形图
Mar 25 Python
Python3 合并二叉树的实现
Sep 30 Python
python @propert装饰器使用方法原理解析
Dec 25 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
example1.php
2006/10/09 PHP
PHP实现截取中文字符串不出现?号的解决方法
2016/12/29 PHP
jquery 查找select ,并触发事件的实现代码
2011/03/30 Javascript
javascript中xml操作实现代码
2011/11/21 Javascript
Eval and new funciton not the same thing
2012/12/27 Javascript
整理JavaScript创建对象的八种方法
2015/11/03 Javascript
jQuery动态生成Bootstrap表格
2016/11/01 Javascript
js窗口震动小程序分享
2016/11/28 Javascript
JavaScript控制输入框中只能输入中文、数字和英文的方法【基于正则实现】
2017/03/03 Javascript
vue element-ui table表格滚动加载方法
2018/03/02 Javascript
解决Mac下安装nmp的淘宝镜像失败问题
2018/05/16 Javascript
深入解析ES6中的promise
2018/11/08 Javascript
详解微信小程序调用支付接口支付
2019/04/28 Javascript
如何使用JavaScript实现无缝滚动自动播放轮播图效果
2020/08/20 Javascript
python在控制台输出进度条的方法
2015/06/20 Python
深入理解python中的atexit模块
2017/03/07 Python
深入理解python中的select模块
2017/04/23 Python
Pandas的read_csv函数参数分析详解
2019/07/02 Python
Python PO设计模式的具体使用
2019/08/16 Python
Python 网络编程之UDP发送接收数据功能示例【基于socket套接字】
2019/10/11 Python
基于Python实现ComicReaper漫画自动爬取脚本过程解析
2019/11/11 Python
python如何提取英语pdf内容并翻译
2020/03/03 Python
Python实现子类调用父类的初始化实例
2020/03/12 Python
如何用Matplotlib 画三维图的示例代码
2020/07/28 Python
python Timer 类使用介绍
2020/12/28 Python
多视角3D可旋转的HTML5 Logo动画
2016/03/02 HTML / CSS
Merchant 1948澳大利亚:新西兰领先的鞋类和靴子供应商
2018/03/24 全球购物
简述网络文件系统NFS,并说明其作用
2016/10/19 面试题
车辆工程专业求职信
2014/04/28 职场文书
机械专业技术员求职信
2014/06/14 职场文书
关心下一代工作先进事迹
2014/08/15 职场文书
总经理年会致辞
2015/07/29 职场文书
教育教学工作反思
2016/02/24 职场文书
为什么MySQL 删除表数据 磁盘空间还一直被占用
2021/10/16 MySQL
详细聊聊Oracle表碎片对性能有多大的影响
2022/03/19 Oracle
python 判断字符串当中是否包含字符(str.contain)
2022/06/01 Python