python 图片验证码代码


Posted in Python onDecember 07, 2008

下面是一个实战项目的结果。

#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实现读取excel写入mysql的小工具详解
Nov 20 Python
python读取txt文件并取其某一列数据的示例
Feb 19 Python
计算机二级python学习教程(2) python语言基本语法元素
May 16 Python
谈一谈基于python的面向对象编程基础
May 21 Python
python爬虫神器Pyppeteer入门及使用
Jul 13 Python
python matplotlib库绘制散点图例题解析
Aug 10 Python
python使用多线程编写tcp客户端程序
Sep 02 Python
python 协程 gevent原理与用法分析
Nov 22 Python
python设置代理和添加镜像源的方法
Feb 14 Python
Python使用内置函数setattr设置对象的属性值
Oct 16 Python
python实现不同数据库间数据同步功能
Feb 25 Python
Python读写Excel表格的方法
Mar 02 Python
下载糗事百科的内容_python版
Dec 07 #Python
python 参数列表中的self 显式不等于冗余
Dec 01 #Python
Python GAE、Django导出Excel的方法
Nov 24 #Python
Python类的基础入门知识
Nov 24 #Python
Python 连连看连接算法
Nov 22 #Python
python sqlobject(mysql)中文乱码解决方法
Nov 14 #Python
Python转码问题的解决方法
Oct 07 #Python
You might like
PHP中冒号、endif、endwhile、endfor使用介绍
2010/04/28 PHP
php多文件上传下载示例分享
2014/02/20 PHP
php获取URL中带#号等特殊符号参数的解决方法
2014/09/02 PHP
php中关于socket的系列函数总结
2015/05/18 PHP
Symfony2 session用法实例分析
2016/02/04 PHP
PHP共享内存使用与信号控制实例分析
2018/05/09 PHP
分享5个非常有用的Laravel Blade指令
2018/05/30 PHP
from 表单提交返回值用post或者是get方法实现
2013/08/21 Javascript
js制作带有遮罩弹出层实现登录注册表单特效代码分享
2015/09/05 Javascript
Bootstrap Modal遮罩弹出层(完整版)
2016/11/21 Javascript
Sequelize中用group by进行分组聚合查询
2016/12/12 Javascript
Javascript之深入浅出prototype
2017/02/06 Javascript
js实现移动端轮播图效果
2020/12/09 Javascript
vue中render函数的使用详解
2018/10/12 Javascript
jQuery实现当拉动滚动条到底部加载数据的方法分析
2019/01/24 jQuery
vuex 动态注册方法 registerModule的实现
2019/07/03 Javascript
弱类型语言javascript开发中的一些坑实例小结【变量、函数、数组、对象、作用域等】
2019/08/07 Javascript
vue动态加载SVG文件并修改节点数据的操作代码
2020/08/17 Javascript
在Vue中使用CSS3实现内容无缝滚动的示例代码
2020/11/27 Vue.js
Python中的localtime()方法使用详解
2015/05/22 Python
python读取二进制mnist实例详解
2017/05/31 Python
python中类和实例如何绑定属性与方法示例详解
2017/08/18 Python
Python HTML解析器BeautifulSoup用法实例详解【爬虫解析器】
2019/04/05 Python
Python对ElasticSearch获取数据及操作
2019/04/24 Python
解决Python找不到ssl模块问题 No module named _ssl的方法
2019/04/29 Python
django xadmin action兼容自定义model权限教程
2020/03/30 Python
ipython jupyter notebook中显示图像和数学公式实例
2020/04/15 Python
keras多显卡训练方式
2020/06/10 Python
基于django2.2连oracle11g解决版本冲突的问题
2020/07/02 Python
Keras 在fit_generator训练方式中加入图像random_crop操作
2020/07/03 Python
Python环境搭建过程从安装到Hello World
2021/02/05 Python
英国打印机墨盒销售网站:Ink Factory
2019/10/07 全球购物
经理助理岗位职责
2015/02/02 职场文书
董事长岗位职责
2015/02/13 职场文书
五一晚会主持词
2015/07/01 职场文书
详解Python函数print用法
2021/06/18 Python