Python编写生成验证码的脚本的教程


Posted in Python onMay 04, 2015

在web开发中经常用到验证码,为了防止机器人注册或者恶意登陆和查询等,作用不容小觑

但是验证码其实不是一个函数就能搞定的,它需要生成图片和水印,其实每种语言都有相关的函数生成图片和文字水印。包括我熟悉的php,呵呵,今天主要来分享如何用python生成验证码。

python生成验证码主要用到如下模块:Image, ImageDraw, ImageFont, ImageFilter和随机数生成模块Random。

代码如下:

#!/usr/bin/env python
#coding=utf-8
import random
import Image, ImageDraw, ImageFont, ImageFilter
 
_letter_cases = "abcdefghjkmnpqrstuvwxy" # 小写字母,去除可能干扰的i,l,o,z
_upper_cases = _letter_cases.upper() # 大写字母
_numbers = ''.join(map(str, range(3, 10))) # 数字
init_chars = ''.join((_letter_cases, _upper_cases, _numbers))
fontType="/usr/share/fonts/truetype/freefont/FreeSans.ttf"
 
def create_validate_code(size=(120, 30),
               chars=init_chars,
               img_type="GIF",
               mode="RGB",
               bg_color=(255, 255, 255),
               fg_color=(0, 0, 255),
               font_size=18,
               font_type=fontType,
               length=4,
               draw_lines=True,
               n_line=(1, 2),
               draw_points=True,
               point_chance = 2):
 '''
 @todo: 生成验证码图片
 @param size: 图片的大小,格式(宽,高),默认为(120, 30)
 @param chars: 允许的字符集合,格式字符串
 @param img_type: 图片保存的格式,默认为GIF,可选的为GIF,JPEG,TIFF,PNG
 @param mode: 图片模式,默认为RGB
 @param bg_color: 背景颜色,默认为白色
 @param fg_color: 前景色,验证码字符颜色,默认为蓝色#0000FF
 @param font_size: 验证码字体大小
 @param font_type: 验证码字体,默认为 ae_AlArabiya.ttf
 @param length: 验证码字符个数
 @param draw_lines: 是否划干扰线
 @param n_lines: 干扰线的条数范围,格式元组,默认为(1, 2),只有draw_lines为True时有效
 @param draw_points: 是否画干扰点
 @param point_chance: 干扰点出现的概率,大小范围[0, 100]
 @return: [0]: PIL Image实例
 @return: [1]: 验证码图片中的字符串
 '''
 
 width, height = size # 宽, 高
 img = Image.new(mode, size, bg_color) # 创建图形
 draw = ImageDraw.Draw(img) # 创建画笔
 if draw_lines:
  create_lines(draw,n_line,width,height)
 if draw_points:
  create_points(draw,point_chance,width,height)
 strs = create_strs(draw,chars,length,font_type, font_size,width,height,fg_color)
 
 # 图形扭曲参数
 params = [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
      ]
 img = img.transform(size, Image.PERSPECTIVE, params) # 创建扭曲
 
 img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界加强(阈值更大)
 
 return img, strs
 
 
def create_lines(draw,n_line,width,height):
 '''绘制干扰线'''
 line_num = random.randint(n_line[0],n_line[1]) # 干扰线条数
 for i in range(line_num):
  # 起始点
  begin = (random.randint(0, width), random.randint(0, height))
  #结束点
  end = (random.randint(0, width), random.randint(0, height))
  draw.line([begin, end], fill=(0, 0, 0))
 
def create_points(draw,point_chance,width,height):
 '''绘制干扰点'''
 chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100]
  
 for w in xrange(width):
  for h in xrange(height):
   tmp = random.randint(0, 100)
   if tmp > 100 - chance:
    draw.point((w, h), fill=(0, 0, 0))
 
def create_strs(draw,chars,length,font_type, font_size,width,height,fg_color):
 '''绘制验证码字符'''
 '''生成给定长度的字符串,返回列表格式'''
 c_chars = random.sample(chars, length)
 strs = ' %s ' % ' '.join(c_chars) # 每个字符前后以空格隔开
  
 font = ImageFont.truetype(font_type, font_size)
 font_width, font_height = font.getsize(strs)
 
 draw.text(((width - font_width) / 3, (height - font_height) / 3),strs, font=font, fill=fg_color)
  
 return ''.join(c_chars)
 
 
if __name__ == "__main__":
  code_img = create_validate_code()
  code_img[0].save("validate.gif", "GIF")
  print code_img[1]
Python 相关文章推荐
python字典排序实例详解
May 20 Python
实例讲解Python的函数闭包使用中应注意的问题
Jun 20 Python
浅谈Python生成器generator之next和send的运行流程(详解)
May 08 Python
用Python读取几十万行文本数据
Dec 24 Python
Python时间和字符串转换操作实例分析
Mar 16 Python
Python检查 云备份进程是否正常运行代码实例
Aug 22 Python
python读取excel进行遍历/xlrd模块操作
Jul 12 Python
基于python图书馆管理系统设计实例详解
Aug 05 Python
pytorch 移动端部署之helloworld的使用
Oct 30 Python
Python爬虫过程解析之多线程获取小米应用商店数据
Nov 14 Python
Python列表元素删除和remove()方法详解
Jan 04 Python
Django实现简单的分页功能
Feb 22 Python
使用Python制作获取网站目录的图形化程序
May 04 #Python
使用Python脚本来获取Cisco设备信息的示例
May 04 #Python
用Python脚本来删除指定容量以上的文件的教程
May 04 #Python
编写Python脚本来获取Google搜索结果的示例
May 04 #Python
编写Python脚本来实现最简单的FTP下载的教程
May 04 #Python
Python下线程之间的共享和释放示例
May 04 #Python
简单介绍Python中利用生成器实现的并发编程
May 04 #Python
You might like
php将数据库中的电话号码读取出来并生成图片
2008/08/31 PHP
php读取mysql的简单实例
2014/01/15 PHP
win7安装php框架Yii的方法
2016/01/25 PHP
PHP动态生成指定大小随机图片的方法
2016/03/25 PHP
win10 apache配置虚拟主机后localhost无法使用的解决方法
2018/01/27 PHP
Laravel框架实现定时发布任务的方法
2018/08/16 PHP
JavaScript的parseInt 进制问题
2009/05/07 Javascript
搭建pomelo 开发环境
2014/06/24 Javascript
Javascript基础教程之for循环
2015/01/18 Javascript
JS+CSS实现表格高亮的方法
2015/08/05 Javascript
vue实现百度搜索下拉提示功能实例
2017/06/14 Javascript
JavaScript实现的可变动态数字键盘控件方式实例代码
2017/07/15 Javascript
js控制随机数生成概率代码实例
2019/03/21 Javascript
jQuery操作attr、prop、val()/text()/html()、class属性
2019/05/23 jQuery
Vue使用axios出现options请求方法
2019/05/30 Javascript
Jquery动态列功能完整实例
2019/08/30 jQuery
layer弹出层扩展主题的方法
2019/09/11 Javascript
Vue axios 将传递的json数据转为form data的例子
2019/10/29 Javascript
Node配合WebSocket做多文件下载以及进度回传
2019/11/07 Javascript
如何手写一个简易的 Vuex
2020/10/10 Javascript
python抓取京东价格分析京东商品价格走势
2014/01/09 Python
python实现最长公共子序列
2018/05/22 Python
python实现多进程按序号批量修改文件名的方法示例
2019/12/30 Python
PyQt5中QTableWidget如何弹出菜单的示例代码
2020/02/23 Python
Python使用graphviz画流程图过程解析
2020/03/31 Python
记录一下scrapy中settings的一些配置小结
2020/09/28 Python
什么是CSS3 HSLA色彩模式?HSLA模拟渐变色条
2016/04/26 HTML / CSS
CSS3解析抖音LOGO制作的方法步骤
2019/04/11 HTML / CSS
这76道Java面试题及答案,祝你能成功通过面试
2016/04/16 面试题
儿科护理实习自我鉴定
2013/09/19 职场文书
网上卖盒饭创业计划书范文
2014/02/07 职场文书
小学英语教学随笔
2015/08/14 职场文书
php 防护xss,PHP的防御XSS注入的终极解决方案
2021/04/01 PHP
redis连接被拒绝的解决方案
2021/04/12 Redis
Python实现天气查询软件
2021/06/07 Python
动画「进击的巨人」第86话播出感谢绘公开
2022/03/21 日漫