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 Socket编程入门教程
Jul 11 Python
在Python中操作字符串之startswith()方法的使用
May 20 Python
详解Python核心对象类型字符串
Feb 11 Python
Django框架搭建的简易图书信息网站案例
May 25 Python
Appium+python自动化怎么查看程序所占端口号和IP
Jun 14 Python
python3 线性回归验证方法
Jul 09 Python
Flask使用Pyecharts在单个页面展示多个图表的方法
Aug 05 Python
python scipy卷积运算的实现方法
Sep 16 Python
python中安装django模块的方法
Mar 12 Python
Python xmltodict模块安装及代码实例
Oct 05 Python
Python实现文本文件拆分写入到多个文本文件的方法
Apr 18 Python
彻底弄懂Python中的回调函数(callback)
Jun 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
PHP 5.0对象模型深度探索之绑定
2006/09/05 PHP
用PHP生成自己的LOG文件
2006/10/09 PHP
php删除与复制文件夹及其文件夹下所有文件的实现代码
2013/01/23 PHP
php curl 上传文件代码实例
2015/04/27 PHP
php blowfish加密解密算法
2016/07/02 PHP
Docker搭建自己的PHP开发环境
2018/02/24 PHP
JavaScript利用正则表达式去除日期中的-
2014/06/09 Javascript
JavaScript onkeydown事件入门实例(键盘某个按键被按下)
2014/10/17 Javascript
基于jquery编写分页插件
2016/03/07 Javascript
全面解析vue中的数据双向绑定
2017/05/10 Javascript
vue.js基于v-for实现批量渲染 Json数组对象列表数据示例
2019/08/03 Javascript
[05:09]DOTA2-DPC中国联赛2月22日Recap集锦
2021/03/11 DOTA
Python编程之多态用法实例详解
2015/05/19 Python
Python基于numpy灵活定义神经网络结构的方法
2017/08/19 Python
利用Python如何制作好玩的GIF动图详解
2018/07/11 Python
使用python快速实现不同机器间文件夹共享方式
2019/12/22 Python
对Tensorflow中Device实例的生成和管理详解
2020/02/04 Python
浅谈SciPy中的optimize.minimize实现受限优化问题
2020/02/29 Python
浅谈python量化 双均线策略(金叉死叉)
2020/06/03 Python
Python+PyQt5+MySQL实现天气管理系统
2020/06/16 Python
如何解决cmd运行python提示不是内部命令
2020/07/01 Python
python 使用多线程创建一个Buffer缓存器的实现思路
2020/07/02 Python
python生成word合同的实例方法
2021/01/12 Python
matplotlib对象拾取事件处理的实现
2021/01/14 Python
python 基于pygame实现俄罗斯方块
2021/03/02 Python
纯CSS3实现Material Design效果
2017/03/09 HTML / CSS
泰国第一的化妆品网站:Konvy
2018/02/25 全球购物
我能否用void** 指针作为参数, 使函数按引用接受一般指针
2013/02/16 面试题
实现向右循环移位
2014/07/31 面试题
小学生期末自我鉴定
2014/01/19 职场文书
十月份红领巾广播稿
2014/01/22 职场文书
市场部管理制度
2014/02/02 职场文书
儿园租房协议书范本
2014/12/02 职场文书
城管个人总结
2015/02/28 职场文书
JavaScript执行机制详细介绍
2021/12/06 Javascript
golang为什么要统一错误处理
2022/04/03 Golang