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实现问号表达式(?)的方法
Nov 27 Python
使用70行Python代码实现一个递归下降解析器的教程
Apr 17 Python
python3使用scrapy生成csv文件代码示例
Dec 28 Python
Python+OpenCV图片局部区域像素值处理改进版详解
Jan 23 Python
Python爬虫实现的根据分类爬取豆瓣电影信息功能示例
Sep 15 Python
python实现while循环打印星星的四种形状
Nov 23 Python
python如何把字符串类型list转换成list
Feb 18 Python
用python介绍4种常用的单链表翻转的方法小结
Feb 24 Python
python pandas移动窗口函数rolling的用法
Feb 29 Python
python opencv实现图片缺陷检测(讲解直方图以及相关系数对比法)
Apr 07 Python
python:解析requests返回的response(json格式)说明
Apr 30 Python
序列化Python对象的方法
Aug 01 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源代码
2006/10/09 PHP
PHPMYADMIN 简明安装教程 推荐
2010/03/07 PHP
yum命令安装php7和相关扩展
2016/07/04 PHP
PHP的JSON封装、转变及输出操作示例
2019/09/27 PHP
JavaScript 拾漏补遗
2009/12/27 Javascript
jQuery的Ajax时无响应数据的解决方法
2010/05/25 Javascript
游览器中javascript的执行过程(图文)
2012/05/20 Javascript
jQuery写的日历(包括日历的样式及功能)
2013/04/23 Javascript
如何使用Javascript正则表达式来格式化XML内容
2013/07/04 Javascript
JS 获取滚动条高度示例代码
2013/10/24 Javascript
使用jQuery实现的掷色子游戏动画效果
2014/03/14 Javascript
JavaScript中判断整数的多种方法总结
2014/11/08 Javascript
分享五个有用的jquery小技巧
2015/10/08 Javascript
js实现延时加载Flash的方法
2015/11/26 Javascript
浅谈Javascript中的12种DOM节点类型
2016/08/19 Javascript
js实现简单的计算器功能
2017/01/16 Javascript
微信小程序wx:for和wx:for-item的用法详解
2018/04/01 Javascript
JavaScript常见事件处理程序实例总结
2019/01/05 Javascript
vue 移动端注入骨架屏的配置方法
2019/06/25 Javascript
小程序实现上下切换位置
2020/11/16 Javascript
[01:18:43]2014 DOTA2华西杯精英邀请赛5 24 iG VS DK
2014/05/25 DOTA
linux下python抓屏实现方法
2015/05/22 Python
用十张图详解TensorFlow数据读取机制(附代码)
2018/02/06 Python
使用Python对微信好友进行数据分析
2018/06/27 Python
python3.5基于TCP实现文件传输
2020/03/20 Python
python爬虫开发之urllib模块详细使用方法与实例全解
2020/03/09 Python
香港礼品网站:GiftU eshop
2017/09/01 全球购物
美国在线纱线商店:Darn Good Yarn
2019/03/20 全球购物
英文自荐信格式
2013/11/28 职场文书
编辑求职信样本
2013/12/16 职场文书
有限公司股东合作协议书
2014/10/29 职场文书
红色电影观后感
2015/06/18 职场文书
员工规章制度范本
2015/08/07 职场文书
Python离线安装openpyxl模块的步骤
2021/03/30 Python
pytorch中的model=model.to(device)使用说明
2021/05/24 Python
Oracle创建只读账号的详细步骤
2021/06/07 Oracle