文章链接:https://mp.weixin.qq.com/s/LYUBRNallHcjnhJb1R3ZBg

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

主要用到的库--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")

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

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

随机画线,在图片宽高范围内随机生成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")

最终生成的图片



这里介绍的是图片生成的方法,可以将图片直接显示在前端,也可以使用接口返回url。这里我简单的把图片做成链接显示在网页上,https://www.manjiexiang.cn/blog/validate 用Django做的,需要注意的是图片保存的路径。

欢迎关注我的个人博客:https://www.manjiexiang.cn/

更多精彩欢迎关注微信号:春风十里不如认识你

一起学习,一起进步,欢迎上车,有问题随时联系,一起解决!!!

python 生成图形验证码的更多相关文章

  1. 利用python生成图形验证码

    validCode.py import random from io import BytesIO from PIL import Image, ImageDraw, ImageFont def ge ...

  2. C#生成图形验证码

    先看效果: 再上代码 public class CaptchaHelper { private static Random rand = new Random(); private static in ...

  3. PHP5 GD库生成图形验证码(汉字)

    PHP5 GD库生成图形验证码且带有汉字的实例分享. 1,利用GD库函数生成图片,并在图片上写指定字符imagecreatetruecolor 新建一个真彩色图像imagecolorallocate ...

  4. PHP5生成图形验证码(有汉字)

    利用PHP5中GD库生成图形验证码 类似于下面这样 1.利用GD库函数生成图片,并在图片上写指定字符 imagecreatetruecolor   新建一个真彩色图像      imagecolora ...

  5. Python 生成随机验证码

    Python生成随机验证码  Python生成随机验证码,需要使用PIL模块. 安装: 1 pip3 install pillow 基本使用 1. 创建图片 1 2 3 4 5 6 7 8 9 fro ...

  6. Python生成随机验证码

    Python生成随机验证码,需要使用PIL模块. 安装: pip3 install pillow 基本使用 1.创建图片 from PIL import Image img = Image.new(m ...

  7. java生成图形验证码

    效果图 import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.Buf ...

  8. ASP.NET中如何生成图形验证码

    通常生成一个图形验证码主要 有3个步骤: (1)随机产生一个长度为N的随机字符串,N的值可由开发可由开发人员自行设置.该字符串可以包含数字.字母等. (2)将随机生成的字符串创建成图片,并显示. (3 ...

  9. python生成随机图形验证码

    使用python生成随机图片验证码,需要使用pillow模块 1.安装pillow模块 pip install pillow 2.pillow模块的基本使用 1.创建图片 from PIL impor ...

随机推荐

  1. 【二代示波器教程】第14章 uCOS-III操作系统版本二代示波器实现

    第14章      uCOS-III操作系统版本二代示波器实现 本章教程为大家讲解uCOS-III操作系统版本的二代示波器实现.主要讲解RTOS设计框架,即各个任务实现的功能,任务间的通信方案选择,任 ...

  2. HTTP长连接和短连接 + Websocket

    HTTP协议与TCP/IP协议的关系 HTTP的长连接和短连接本质上是TCP长连接和短连接.HTTP属于应用层协议,在传输层使用TCP协议,在网络层使用IP协议.IP协议主要解决网络路由和寻址问题,T ...

  3. [Swift]LeetCode54. 螺旋矩阵 | Spiral Matrix

    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral or ...

  4. [Swift]LeetCode998. 最大二叉树 II | Maximum Binary Tree II

    We are given the root node of a maximum tree: a tree where every node has a value greater than any o ...

  5. Android开发:在Eclipse中配置Android环境

    一.文件需要: https://pan.baidu.com/s/1-XCSSPW5JGyPRlvwRVSfmA 提取码:m5t8 NDK过大没有上传在这个文件里. 二.在Eclipse中配置Tools ...

  6. 【Spark篇】---SparkSQL初始和创建DataFrame的几种方式

    一.前述       1.SparkSQL介绍 Hive是Shark的前身,Shark是SparkSQL的前身,SparkSQL产生的根本原因是其完全脱离了Hive的限制. SparkSQL支持查询原 ...

  7. Python内置函数(47)——open

    英文文档: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, ope ...

  8. 快速搭建WebAPI(Odata+Code-First)附Odata条件查询表~

    Odata是什么? 开放数据协议(Open Data Protocol,缩写OData)是一种描述如何创建和访问Restful服务的OASIS标准.该标准由微软发起,前三个版本1.0.2.0.3.0都 ...

  9. SpringBoot入门教程(二十)Swagger2-自动生成RESTful规范API文档

    Swagger2 方式,一定会让你有不一样的开发体验:功能丰富 :支持多种注解,自动生成接口文档界面,支持在界面测试API接口功能:及时更新 :开发过程中花一点写注释的时间,就可以及时的更新API文档 ...

  10. Linux环境下tomcat的安装与使用

    1.tomcat安装 1.1.前提条件: 需要准备一台Linux机器,我选择的是Ubuntu18. Linux机器上已经安装了JDK,使用java -version命令查看是否安装. stephen@ ...