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 相关文章推荐
Windows系统配置python脚本开机启动的3种方法分享
Mar 10 Python
Python使用logging结合decorator模式实现优化日志输出的方法
Apr 16 Python
Python 专题五 列表基础知识(二维list排序、获取下标和处理txt文本实例)
Mar 20 Python
python XlsxWriter模块创建aexcel表格的实例讲解
May 03 Python
Python快速查找list中相同部分的方法
Jun 27 Python
Python 判断文件或目录是否存在的实例代码
Jul 19 Python
Python selenium根据class定位页面元素的方法
Feb 26 Python
python getpass模块用法及实例详解
Oct 07 Python
PyInstaller将Python文件打包为exe后如何反编译(破解源码)以及防止反编译
Apr 15 Python
Python中的全局变量如何理解
Jun 04 Python
如何用Python 加密文件
Sep 10 Python
用python基于appium模块开发一个自动收取能量的小助手
Sep 25 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 strcmp使用说明
2010/04/22 PHP
解析php中array_merge与array+array的区别
2013/06/21 PHP
php判断ip黑名单程序代码实例
2014/02/24 PHP
php从csv文件读取数据并输出到网页的方法
2015/03/14 PHP
PHP中4种常用的抓取网络数据方法
2015/06/04 PHP
use jscript Create a SQL Server database
2007/06/16 Javascript
Discuz! 6.1_jQuery兼容问题
2008/09/23 Javascript
js 删除数组的几种方法小结
2014/02/21 Javascript
javaScript使用EL表达式的几种方式
2014/05/27 Javascript
JavaScript中eval()函数用法详解
2015/12/14 Javascript
js根据手机客户端浏览器类型,判断跳转官网/手机网站多个实例代码
2016/04/30 Javascript
浅谈js函数中的实例对象、类对象、局部变量(局部函数)
2016/11/20 Javascript
深入理解vue.js双向绑定的实现原理
2016/12/05 Javascript
EditPlus 正则表达式 实战(3)
2016/12/15 Javascript
JavaScript中的call和apply的用途以及区别
2017/01/11 Javascript
Javascript实现找不同色块的游戏
2017/07/17 Javascript
SelectPage v2.4 发布新增纯下拉列表和关闭分页功能
2017/09/07 Javascript
JavaScript日期工具类DateUtils定义与用法示例
2018/09/03 Javascript
基于JavaScript实现每日签到打卡轨迹功能
2018/11/29 Javascript
python实现从ftp服务器下载文件的方法
2015/04/30 Python
python从网络读取图片并直接进行处理的方法
2015/05/22 Python
python实现应用程序在右键菜单中添加打开方式功能
2017/01/09 Python
Python yield与实现方法代码分析
2018/02/06 Python
Python切片操作深入详解
2018/07/27 Python
Dlib+OpenCV深度学习人脸识别的方法示例
2019/05/14 Python
python获取Linux发行版名称
2019/08/30 Python
django创建简单的页面响应实例教程
2019/09/06 Python
tensorflow与numpy的版本兼容性问题的解决
2021/01/08 Python
英国时尚饰品和发饰购物网站:Claire’s
2017/07/04 全球购物
北美主要的汽车零部件零售商:AutoShack.com
2019/02/23 全球购物
关于感恩的演讲稿400字
2014/08/26 职场文书
2015年销售员工作总结范文
2015/04/07 职场文书
单身证明格式样本
2015/06/15 职场文书
用 Python 定义 Schema 并生成 Parquet 文件详情
2021/09/25 Python
项目中Nginx多级代理是如何获取客户端的真实IP地址
2022/05/30 Servers
python数字图像处理:图像简单滤波
2022/06/28 Python