python 生成图形验证码

文章链接: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/

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

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

原文地址:https://www.cnblogs.com/taixiang/p/9942466.html

时间: 2024-08-29 00:25:54

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

Python 生成随机验证码

Python生成随机验证码 Python生成随机验证码,需要使用PIL模块. 安装: 1 pip3 install pillow 基本使用 1. 创建图片 1 2 3 4 5 6 7 8 9 from PIL import Image img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255)) # 在图片查看器中打开 # img.show()  # 保存在本地 with open('code.png','wb') as f

生成图形验证码

介绍生成两种类型的图形验证码: 1.普通的随机字符串;  2.随机运算表达式 图形验证码类: /// <summary> /// 图形验证码类 /// </summary> public class PicCaptcha { #region Constructed Methods /// <summary> /// 默认构造方法 /// </summary> public PicCaptcha() { } /// <summary> ///构造方

python生成随机验证码

Python 生成随机验证码,需安装 PIL模块 安装: pip3 install pillow 基本使用 1,.创建图片 from PIL import Image img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255)) # 在图片查看器中打开 # img.show() # 保存在本地 with open('code.png','wb') as f: img.save(f,format='png') 2.创建画笔,用

python生成中文验证码,带旋转,带干扰噪音线段

# -*- coding: utf-8 -*- """ Created on Sun Oct 4 15:57:46 2015 @author: keithguofan """ import random from PIL import Image,ImageDraw,ImageFont import math,string class RandomChar(): @staticmethod def Unicode(): val = random.

使用Python生成基础验证码教程

pillow是Python平台事实上的图像处理标准库.PIL功能非常强大,但API却非常简单易用. 所以我们使用它在环境里做图像的处理. 第一步 下载pillow #运行命令 pip install pillow 第二部 编写代码 1>创建一个类,初始化并为类添加属性 我们可能需要的属性有:验证码图片宽高,干扰点线数量,我们要出现多少个验证码等 2>随机生成背景颜色和字体颜色,在此建议将背景色生成范围定为浅色(0-120),字体色为深色(120-255)易于人眼识别 3>创建画布并依次画

如何生成随机验证码

Python生成随机验证码 Python生成随机验证码,需要使用PIL模块. 安装: pip3 install pillow 基本使用 1. 创建图片 from PIL import Image img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255)) # 在图片查看器中打开 # img.show() # 保存在本地 with open('code.png','wb') as f: img.save(f,format='

图形验证码

新建一个.cs文件用来写生成图形验证码的方法,返回一个MemoryStream的参数.在Default.aspx中接收输出就可以了. 1.下面是.cs的代码 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; us

PHP 图形验证码

一段生成图形验证码的代码,向原创作者致谢. 1.将以下代码保存为 txm.php ,注:直接运行该页面是没有结果的,要用另一页面引用,请看步骤2 <?php session_start(); $img_width=80;$img_height=24;if($_GET["act"]== "init"){    for($Tmpa=0;$Tmpa<6;$Tmpa++)   {        $nmsg.=dechex(rand(0,15)); // 生成随机

python实现图片验证码

1 验证基础知识1.1 Python生成随机验证码,需要使用PIL模块. # 安装 pip3 install pillow 1.2 创建图片 from PIL import Image img = Image.new(mode="RGB", size=(120, 30), color=(125, 255, 255)) # 保存图片到本地 with open("code.png",'wb') as f: img.save(f,format="png"