使用pillow创建动态图形验证码

使用pillow创建动态图形验证码

python 复制代码
#安装pillow模块:pip3 install pillow
from PIL import Image,ImageDraw,ImageFont
import random
import string

def id_code(width,height,bit,font_file,font_size):
    """
    功能:生成随机图片验证码
    :param width: 图片宽度
    :param height: 图片高度
    :param bit:验证码位数
    :param font_file:字体文件路径和文件名
    :param font_size:字体大小
    :return:
        code:验证码(字符串)
        im:Image图片对象
    """
    im=Image.new(mode='RGB',size=(width,height),color=(255,255,255))   #创建Image对象
    draw = ImageDraw.Draw(im)                                          #创建ImageDraw对象
    code_list=[]                                                       #验证码列表
    x=width/20                                                         #x坐标初始值
    font = ImageFont.truetype(font=font_file, size=font_size)          #创建字体对象
    for i in range(bit):                                               #循环绘制验证码字符
        y = random.randrange(0, int(height/3))
        color = (random.randint(0,255),random.randint(0,255),random.randint(0,255))       #生成随机颜色
        var = random.choice(string.ascii_letters + string.digits)
        draw.text((x,y),text=var,fill=color,font=font)
        x+=font_size
        code_list.append(var)
    code=''.join(code_list)

    for i in range(30):                                                #循环绘制干扰点
        x = random.randrange(1, width - 1)
        y = random.randrange(1, height - 1)
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))   #生成随机颜色
        draw.ellipse((x,y,x+2,y+2), fill=color)

    for i in range(2):                                                 #循环绘制干扰线
        y = random.randrange(5, height - 5)
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))   #生成随机颜色
        draw.line((0,y,width,y),width=1,fill=color)

    return code,im                                                     #返回验证码字符串和Image对象

code,im=id_code(120,50,4,'c:/windows/Fonts/simsun.ttc',30)             #调用函数
print(code)                                                            #可以获取验证码字符串
im.show()                                                              #显示图片

每次调用都能生成一个不同的图片验证码,并返回验证码字符串

返回结果:

python 复制代码
code= bW8h
相关推荐
心易行者11 分钟前
Agent应用+API端点商业化进阶实战:从单体智能体到可付费调用的API全流程
运维·服务器·人工智能·python·apache
夜之眷属24 分钟前
Core dump 崩溃排查:JVM 宕机后,那份 core 文件怎么用 gdb 还原现场
java·运维·服务器·jvm
zly350027 分钟前
centos7 mount设备挂载 /dev/sda1/硬盘挂载
linux·运维·服务器
工业一体机老司机33 分钟前
工业一体机选购后的系统部署:Ubuntu下Docker容器化运行与GPIO配置
linux·ubuntu·docker·人机交互
哎呦,帅小伙哦1 小时前
进程监控工具——htop
linux·运维·服务器
深圳恒讯2 小时前
海外服务器延迟高怎么解决?从线路到TCP协议的6层排查清单
运维·服务器·tcp/ip
夏虫不可与之言冰2 小时前
Windows WSL2 (Ubuntu) 搭建 ESP‑IDF 6.1 开发环境全过程演示
linux·windows·ubuntu·esp32·乐鑫科技·乐鑫eim·乐鑫代理商
小羊没烦恼!2 小时前
jQuery1.5的改进细节
java·服务器·开发语言·前端·c#
春涧草茶3 小时前
慢就是快12-12手动抛出异常
java·linux·前端