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实现将n个点均匀地分布在球面上的方法
Mar 12 Python
让python在hadoop上跑起来
Jan 27 Python
Python三级目录展示的实现方法
Sep 28 Python
python生成词云的实现方法(推荐)
Jun 13 Python
使用python实现ANN
Dec 20 Python
Python引用计数操作示例
Aug 23 Python
python退出命令是什么?详解python退出方法
Dec 10 Python
在win10和linux上分别安装Python虚拟环境的方法步骤
May 09 Python
tensorflow保持每次训练结果一致的简单实现
Feb 17 Python
python安装cx_Oracle和wxPython的方法
Sep 14 Python
pycharm 实现调试窗口恢复
Feb 05 Python
Python爬取某平台短视频的方法
Feb 08 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数据库的代码
2011/01/06 PHP
destoon在360浏览器下出现用户被强行注销的解决方法
2014/06/26 PHP
yii实现CheckBox复选框在同一行显示的方法
2014/12/03 PHP
Yii基于数组和对象的Model查询技巧实例详解
2015/12/28 PHP
PHP自带方法验证邮箱、URL、IP是否合法的函数
2016/12/08 PHP
PHP魔术方法之__call与__callStatic使用方法
2017/07/23 PHP
Javascript remove 自定义数组删除方法
2009/10/20 Javascript
另一个javascript小测验(代码集合)
2011/07/27 Javascript
用console.table()调试javascript
2014/09/04 Javascript
对javascript继承的理解
2016/10/11 Javascript
js 取消页面可以选中文字的功能方法
2018/01/02 Javascript
vue.js实现只弹一次弹框
2018/01/29 Javascript
对angular2中的ngfor和ngif指令嵌套实例讲解
2018/09/12 Javascript
Vue 实现一个命令式弹窗组件功能
2019/09/25 Javascript
小程序组件传值和引入sass的方法(使用vant Weapp组件库)
2020/11/24 Javascript
[01:19:23]2018DOTA2亚洲邀请赛 4.5 淘汰赛 Mineski vs VG 第二场
2018/04/06 DOTA
python实现各进制转换的总结大全
2017/06/18 Python
Python实现打印螺旋矩阵功能的方法
2017/11/21 Python
Python3网络爬虫中的requests高级用法详解
2019/06/18 Python
对python中的控制条件、循环和跳出详解
2019/06/24 Python
pycharm双击无响应(打不开问题解决办法)
2020/01/10 Python
python GUI模拟实现计算器
2020/06/22 Python
Python爬虫小例子——爬取51job发布的工作职位
2020/07/10 Python
python+excel接口自动化获取token并作为请求参数进行传参操作
2020/11/10 Python
俄罗斯眼镜网: optikaworld
2016/07/31 全球购物
波兰珠宝品牌:YES
2019/08/09 全球购物
卡拉威高尔夫官方网站:Callaway Golf
2020/09/16 全球购物
高校辅导员推荐信范文
2013/12/25 职场文书
个人公开承诺书
2014/03/28 职场文书
课外小组活动总结
2014/08/27 职场文书
房地产财务经理岗位职责
2015/04/08 职场文书
2015年校医个人工作总结
2015/07/24 职场文书
培训后的感想
2015/08/07 职场文书
小学体育教学随笔
2015/08/14 职场文书
Java8中Stream的一些神操作
2021/11/02 Java/Android
python套接字socket通信
2022/04/01 Python