使用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
相关推荐
月清晖3 分钟前
centos更换yum源、安装Docker和换源
linux·docker·centos
【 教主 】25 分钟前
<Linux> 多线程
linux·运维·服务器
技术探索者39 分钟前
Shell:如何判断两个字符串相等
linux·shell
athena19992701 小时前
服务器对SEO优化效果的影响
服务器
Slow1 小时前
Linux静态库的制作
linux·c语言
一个梦想过上五休二生活的男人1 小时前
Firewalld防火墙(二)
linux·服务器·数据库
一只猿Hou1 小时前
【logback-spring配置不生效,开发环境和生产环境配置不同输出级别】
linux·spring·logback
gopher95112 小时前
Linux多进程和多线程(五)进程间通信-消息队列
linux·服务器·c语言·开发语言·进程
杨江2 小时前
服务器上VMWare Workstation虚拟机声卡支持
运维·服务器
qq1778036232 小时前
CSOL老是服务器链接中断怎么解决
运维·服务器·网络·ddos