python 生成图形验证码的方法示例


Posted in Python onNovember 11, 2018

日常在网站使用过程中经常遇到图形验证,今天准备自己做个图形验证码,这算是个简单的功能,也适合新手练习的,便于自己学习。

主要用到的库--PIL图像处理库,简单的思路,我们需要随机的颜色,随机的数字或字母,随机的线条、点作为干扰元素 拼凑成一张图片。

生成随机颜色,返回的是rgb三色。

def getRandomColor():
  r = random.randint(0, 255)
  g = random.randint(0, 255)
  b = random.randint(0, 255)
  return (r, g, b)

从数字、大小写字母里生成随机字符。

def getRandomChar():
  random_num = str(random.randint(0, 9))
  random_lower = chr(random.randint(97, 122)) # 小写字母a~z
  random_upper = chr(random.randint(65, 90)) # 大写字母A~Z
  random_char = random.choice([random_num, random_lower, random_upper])
  return random_char

图片操作,生成一张随机背景色的图片,随机生成5种字符+5种颜色,在图片上描绘字,由于默认的字体很小,还需要对字进行处理,不同系统下的字体文件存放位置不一样,这里我是把window下的 arial.ttf 字体复制到了当前文件夹下直接使用的。

# 图片宽高
width = 160
height = 50

def createImg():
  bg_color = getRandomColor()
  # 创建一张随机背景色的图片
  img = Image.new(mode="RGB", size=(width, height), color=bg_color)
  # 获取图片画笔,用于描绘字
  draw = ImageDraw.Draw(img)
  # 修改字体
  font = ImageFont.truetype(font="arial.ttf", size=36)
  for i in range(5):
    # 随机生成5种字符+5种颜色
    random_txt = getRandomChar()
    txt_color = getRandomColor()
    # 避免文字颜色和背景色一致重合
    while txt_color == bg_color:
      txt_color = getRandomColor()
    # 根据坐标填充文字
    draw.text((10 + 30 * i, 3), text=random_txt, fill=txt_color, font=font)
  # 打开图片操作,并保存在当前文件夹下
  with open("test.png", "wb") as f:
    img.save(f, format="png")

这个时候可以看到文件夹下面的图片

python 生成图形验证码的方法示例

这里是张很清晰的图片,为了有干扰元素,这里还需要在图片加入些线条、点作为干扰点。

随机画线,在图片宽高范围内随机生成2个坐标点,并通过随机颜色产生线条。

def drawLine(draw):
  for i in range(5):
    x1 = random.randint(0, width)
    x2 = random.randint(0, width)
    y1 = random.randint(0, height)
    y2 = random.randint(0, height)
    draw.line((x1, y1, x2, y2), fill=getRandomColor())

随机画点,随机生成横纵坐标点。

def drawPoint(draw):
  for i in range(50):
    x = random.randint(0, width)
    y = random.randint(0, height)
    draw.point((x,y), fill=getRandomColor())

生成方法

def createImg():
  bg_color = getRandomColor()
  # 创建一张随机背景色的图片
  img = Image.new(mode="RGB", size=(width, height), color=bg_color)
  # 获取图片画笔,用于描绘字
  draw = ImageDraw.Draw(img)
  # 修改字体
  font = ImageFont.truetype(font="arial.ttf", size=36)
  for i in range(5):
    # 随机生成5种字符+5种颜色
    random_txt = getRandomChar()
    txt_color = getRandomColor()
    # 避免文字颜色和背景色一致重合
    while txt_color == bg_color:
      txt_color = getRandomColor()
    # 根据坐标填充文字
    draw.text((10 + 30 * i, 3), text=random_txt, fill=txt_color, font=font)
  # 画干扰线点
  drawLine(draw)
  drawPoint(draw)
  # 打开图片操作,并保存在当前文件夹下
  with open("test.png", "wb") as f:
    img.save(f, format="png")

最终生成的图片

python 生成图形验证码的方法示例

这里介绍的是图片生成的方法,可以将图片直接显示在前端,也可以使用接口返回url。用Django做的,需要注意的是图片保存的路径。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python序列之list和tuple常用方法以及注意事项
Jan 09 Python
Python获取任意xml节点值的方法
May 05 Python
python实现的简单窗口倒计时界面实例
May 05 Python
Python字符串格式化输出方法分析
Apr 13 Python
Django Highcharts制作图表
Aug 27 Python
Python基于分析Ajax请求实现抓取今日头条街拍图集功能示例
Jul 19 Python
Python编程深度学习计算库之numpy
Dec 28 Python
python中的协程深入理解
Jun 10 Python
python 统计文件中的字符串数目示例
Dec 24 Python
Python拼接字符串的7种方式详解
Mar 19 Python
关于python3 opencv 图像二值化的问题(cv2.adaptiveThreshold函数)
Apr 04 Python
Python编写冷笑话生成器
Apr 20 Python
老生常谈python中的重载
Nov 11 #Python
Django跨域请求CSRF的方法示例
Nov 11 #Python
Python rstrip()方法实例详解
Nov 11 #Python
python requests爬取高德地图数据的实例
Nov 10 #Python
Python爬取商家联系电话以及各种数据的方法
Nov 10 #Python
Python中的取模运算方法
Nov 10 #Python
在Python中获取两数相除的商和余数方法
Nov 10 #Python
You might like
全国FM电台频率大全 - 15 山东省
2020/03/11 无线电
PHP的宝库目录--PEAR
2006/10/09 PHP
php 模拟post_验证页面的返回状态(实例讲解)
2013/10/28 PHP
PHP上传图片进行等比缩放可增加水印功能
2014/01/13 PHP
浅谈php+phpStorm+xdebug配置方法
2015/09/17 PHP
php精确的统计在线人数的方法
2015/10/21 PHP
PHP符合PSR编程规范的实例分享
2016/12/21 PHP
仿校内登陆框,精美,给那些很厉害但是没有设计天才的程序员
2008/11/24 Javascript
JavaScript基础语法让人疑惑的地方小结
2012/05/23 Javascript
location对象的属性和方法应用(解析URL)
2013/04/12 Javascript
JavaScript 实现鼠标拖动元素实例代码
2014/02/24 Javascript
nw.js实现类似微信的聊天软件
2015/03/16 Javascript
深入理解JS正则表达式---分组
2016/07/18 Javascript
JavaScript中定义对象原型的两种使用方法
2016/12/15 Javascript
Bootstrap表格使用方法详解
2017/02/17 Javascript
nodejs集成sqlite使用示例
2017/06/05 NodeJs
详解VUE中v-bind的基本用法
2017/07/13 Javascript
vue双花括号的使用方法 附练习题
2017/11/07 Javascript
React-native桥接Android原生开发详解
2018/01/17 Javascript
使用Vue.js 和Chart.js制作绚丽多彩的图表
2019/06/15 Javascript
微信小程序实现左滑动删除效果
2020/03/30 Javascript
Jquery 动态添加元素并添加点击事件实现过程解析
2019/10/12 jQuery
使用JS实现动态时钟
2020/03/12 Javascript
Flask SQLAlchemy一对一,一对多的使用方法实践
2013/02/10 Python
Selenium 模拟浏览器动态加载页面的实现方法
2018/05/16 Python
python中的tcp示例详解
2018/12/09 Python
Pycharm的Available Packages为空的解决方法
2020/09/18 Python
Python3获取cookie常用三种方案
2020/10/05 Python
html5 canvas里绘制椭圆并保持线条粗细均匀的技巧
2013/03/25 HTML / CSS
Web时代变迁及html5与html4的区别
2016/01/06 HTML / CSS
Ryderwear澳洲官网:澳大利亚高端健身训练装备品牌
2018/09/18 全球购物
信息专业毕业生五年职业规划参考
2014/02/06 职场文书
小学关爱留守儿童活动方案
2014/08/25 职场文书
2015年行政助理工作总结
2015/04/30 职场文书
SpringBoot集成Redis的思路详解
2021/10/16 Redis
教你使用Ubuntu搭建DNS服务器
2022/09/23 Servers