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中请使用isinstance()判断变量类型
Aug 25 Python
浅谈Python程序与C++程序的联合使用
Apr 07 Python
python实现在windows下操作word的方法
Apr 28 Python
使用Python多线程爬虫爬取电影天堂资源
Sep 23 Python
详解Python pygame安装过程笔记
Jun 05 Python
python购物车程序简单代码
Apr 18 Python
python实现简易数码时钟
Feb 19 Python
python利用多种方式来统计词频(单词个数)
May 27 Python
python中shell执行知识点
May 06 Python
Django如何使用asyncio协程和ThreadPoolExecutor多线程
Oct 12 Python
python 写一个性能测试工具(一)
Oct 24 Python
python神经网络学习 使用Keras进行回归运算
May 04 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
解析Extjs与php数据交互(增删查改)
2013/06/25 PHP
php取整函数ceil,floo,round的用法及介绍
2013/08/31 PHP
php通过baihui网API实现读取word文档并展示
2015/06/22 PHP
PHP使用array_merge重新排列数组下标的方法
2015/07/22 PHP
JavaScript中for..in循环陷阱介绍
2013/11/12 Javascript
完美解决IE低版本不支持call与apply的问题
2013/12/05 Javascript
JavaScript字符串对象split方法入门实例(用于把字符串分割成数组)
2014/10/16 Javascript
jQuery中extend函数的实现原理详解
2015/02/03 Javascript
详解Bootstrap四种图片样式
2016/01/04 Javascript
Js的Array数组对象详解
2016/02/22 Javascript
JS中对Cookie的操作详解
2016/08/05 Javascript
微信小程序的生命周期的详解
2017/10/19 Javascript
微信小程序实现自定义modal弹窗封装的方法
2018/06/15 Javascript
每天学点Vue源码之vm.$mount挂载函数
2019/03/11 Javascript
详解如何使用微信小程序云函数发送短信验证码
2019/03/13 Javascript
微信小程序仿今日头条导航栏滚动解析
2019/08/20 Javascript
使用Python脚本将Bing的每日图片作为桌面的教程
2015/05/04 Python
python实现linux下使用xcopy的方法
2015/06/28 Python
Python实现屏幕截图的代码及函数详解
2016/10/01 Python
python 划分数据集为训练集和测试集的方法
2018/12/11 Python
Python实现制度转换(货币,温度,长度)
2019/07/14 Python
Python3 批量扫描端口的例子
2019/07/25 Python
python将四元数变换为旋转矩阵的实例
2019/12/04 Python
解决Pytorch自定义层出现多Variable共享内存错误问题
2020/06/28 Python
python tkinter实现连连看游戏
2020/11/16 Python
通过css3动画和opacity透明度实现呼吸灯效果
2019/08/09 HTML / CSS
潘多拉意大利官方网上商城:网上选购PANDORA珠宝
2018/10/07 全球购物
博柏利美国官方网站:Burberry美国
2020/11/19 全球购物
承诺书的格式范文
2014/03/28 职场文书
媒体宣传策划方案
2014/05/25 职场文书
设备管理实施方案
2014/05/31 职场文书
结对共建工作方案
2014/06/02 职场文书
北京爱情故事观后感
2015/06/12 职场文书
七一表彰大会简报
2015/07/20 职场文书
nginx location中多个if里面proxy_pass的方法
2021/03/31 Servers
Java实现二维数组和稀疏数组之间的转换
2021/06/27 Java/Android