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脚本实现xls(xlsx)转成csv
Apr 10 Python
tensorflow实现对图片的读取的示例代码
Feb 12 Python
numpy实现合并多维矩阵、list的扩展方法
May 08 Python
python使用response.read()接收json数据的实例
Dec 19 Python
python 反编译exe文件为py文件的实例代码
Jun 27 Python
python的faker库用法
Nov 28 Python
python飞机大战pygame游戏之敌机出场实现方法详解
Dec 17 Python
python使用openCV遍历文件夹里所有视频文件并保存成图片
Jan 14 Python
新版Pycharm中Matplotlib不会弹出独立的显示窗口的问题
Jun 02 Python
python字典的值可以修改吗
Jun 29 Python
Python3如何在服务器打印资产信息
Aug 27 Python
详解Pycharm安装及Django安装配置指南
Sep 15 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 Errcode: 28 终极解决方法
2009/07/01 PHP
ThinkPHP应用模式扩展详解
2014/07/16 PHP
Apache启动报错No space left on device: AH00023该怎么解决
2015/10/16 PHP
Laravel框架实现redis集群的方法分析
2017/09/14 PHP
PHP convert_cyr_string()函数讲解
2019/02/13 PHP
9行javascript代码获取QQ群成员具体实现
2013/10/16 Javascript
JavaScript截取字符串的2个函数介绍
2014/08/27 Javascript
实例详解JSON数据格式及json格式数据域字符串相互转换
2016/01/07 Javascript
JavaScript如何对图片进行黑白化
2018/04/10 Javascript
小程序扫描普通链接二维码跳转小程序指定界面方法
2019/05/07 Javascript
微信小程序的开发范式BeautyWe.js入门详解
2019/07/10 Javascript
IDEA安装vue插件图文详解
2019/09/26 Javascript
VUE-ElementUI 自定义Loading图操作
2020/11/11 Javascript
[01:00:54]TI4正赛第二日开场
2014/07/20 DOTA
[03:55]2016国际邀请赛中国区预选赛首日TOP10精彩集锦
2016/06/27 DOTA
python实现删除文件与目录的方法
2014/11/10 Python
Python中集合类型(set)学习小结
2015/01/28 Python
python 中字典嵌套列表的方法
2018/07/03 Python
python3 enum模块的应用实例详解
2019/08/12 Python
python数据持久存储 pickle模块的基本使用方法解析
2019/08/30 Python
Django中密码的加密、验密、解密操作
2019/12/19 Python
将python依赖包打包成window下可执行文件bat方式
2019/12/26 Python
Python3 ID3决策树判断申请贷款是否成功的实现代码
2020/05/21 Python
Python 使用生成器代替线程的方法
2020/08/04 Python
python之语音识别speech模块
2020/09/09 Python
python基于爬虫+django,打造个性化API接口
2021/01/21 Python
python推导式的使用方法实例
2021/02/28 Python
使用Python快速打开一个百万行级别的超大Excel文件的方法
2021/03/02 Python
Max&Co官网:意大利年轻女性时尚品牌
2017/05/16 全球购物
会计职业生涯规划书
2014/01/13 职场文书
市级文明单位申报材料
2014/05/07 职场文书
房屋所有权证明
2014/10/20 职场文书
党员廉洁自律个人总结
2015/02/13 职场文书
保管员岗位职责
2015/02/14 职场文书
2015年高二班主任工作总结
2015/05/25 职场文书
python中的class_static的@classmethod的巧妙用法
2021/06/22 Python