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笔记:mysql、redis操作方法
Jun 28 Python
Python爬取附近餐馆信息代码示例
Dec 09 Python
python中set()函数简介及实例解析
Jan 09 Python
python+matplotlib演示电偶极子实例代码
Jan 12 Python
Python写一个基于MD5的文件监听程序
Mar 11 Python
在Python中COM口的调用方法
Jul 03 Python
python网络编程之多线程同时接受和发送
Sep 03 Python
Django 实现xadmin后台菜单改为中文
Nov 15 Python
python实现堆排序的实例讲解
Feb 21 Python
Python datetime 如何处理时区信息
Sep 02 Python
Python 中 sorted 如何自定义比较逻辑
Feb 02 Python
python 对xml解析的示例
Feb 27 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
php获取文件夹路径内的图片以及分页显示示例
2014/03/11 PHP
PHP实现ASCII码与字符串相互转换的方法
2017/04/29 PHP
php中html_entity_decode实现HTML实体转义
2018/06/13 PHP
yii2.0框架多模型操作示例【添加/修改/删除】
2020/04/13 PHP
JavaScript 滚轮事件使用说明
2010/03/07 Javascript
获取鼠标在div中的相对位置的实现代码
2013/12/30 Javascript
jquery查找父元素、子元素(个人经验总结)
2014/04/09 Javascript
ajax请求乱码的解决方法(中文乱码)
2014/04/10 Javascript
jquery中radio checked问题
2015/03/16 Javascript
jQuery()方法的第二个参数详解
2015/04/29 Javascript
jQuery实现类似老虎机滚动抽奖效果
2015/08/06 Javascript
Angularjs在初始化未完毕时出现闪烁问题的解决方法分析
2016/08/05 Javascript
Javascript实现图片懒加载插件的方法
2016/10/20 Javascript
用AngularJS来实现监察表单按钮的禁用效果
2016/11/02 Javascript
基于javascript实现的快速排序
2016/12/02 Javascript
Angular设置别名alias的方法
2018/11/08 Javascript
Vue SPA 初次进入加载动画实现代码
2019/11/14 Javascript
Vue+Node实现商品列表的分页、排序、筛选,添加购物车功能详解
2019/12/07 Javascript
[01:11:28]DOTA2-DPC中国联赛定级赛 RNG vs Phoenix BO3第一场 1月8日
2021/03/11 DOTA
python实现上传样本到virustotal并查询扫描信息的方法
2014/10/05 Python
Python 3.x 新特性及10大变化
2015/06/12 Python
Python3字符串学习教程
2015/08/20 Python
简单讲解Python编程中namedtuple类的用法
2016/06/21 Python
python 中文件输入输出及os模块对文件系统的操作方法
2018/08/27 Python
python调用pyaudio使用麦克风录制wav声音文件的教程
2019/06/26 Python
django中账号密码验证登陆功能的实现方法
2019/07/15 Python
python之PyQt按钮右键菜单功能的实现代码
2019/08/17 Python
python采集百度搜索结果带有特定URL的链接代码实例
2019/08/30 Python
python实现输入三角形边长自动作图求面积案例
2020/04/12 Python
matlab中二维插值函数interp2的使用详解
2020/04/22 Python
html5生成柱状图(条形图)效果的实例代码
2016/03/25 HTML / CSS
39美元购买一副眼镜或太阳镜:39DollarGlasses.com
2018/06/17 全球购物
公司培训欢迎词
2014/01/10 职场文书
学习标兵获奖感言
2014/02/20 职场文书
2014乡镇领导班子四风对照检查材料思想汇报
2014/10/05 职场文书
全国劳模先进事迹材料(2016精选版)
2016/02/25 职场文书