【Python】生成图片验证码

1. 首先安装第三方库PIL(图像处理库)

python 复制代码
pip install pillow

2. 编写生成验证码代码

这里字体 'SimHei.ttf' 文件要放在该文件目录下。

python 复制代码
import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter


def check_code(width=128, height=30, char_length=5, font_file='SimHei.ttf', font_size=28):
    code = []
    img = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255))
    draw = ImageDraw.Draw(img, mode='RGB')

    def rndChar():
        """生成随机字母"""
        return chr(random.randint(65, 90))

    def rndColor():
        """生成随机颜色"""
        return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255))

    # 写文字
    font = ImageFont.truetype(font_file, font_size)
    for i in range(char_length):
        char = rndChar()
        code.append(char)
        h = random.randint(0, 4)
        draw.text([i * width / char_length, h], char, font=font, fill=rndColor())

    # 写干扰点
    for i in range(40):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())

    # 写干扰圆圈
    for i in range(40):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor())

    # 画干扰线
    for i in range(5):
        x1 = random.randint(0, width)
        y1 = random.randint(0, height)
        x2 = random.randint(0, width)
        y2 = random.randint(0, height)

        draw.line((x1, y1, x2, y2), fill=rndColor())

    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
    return img, ''.join(code)


if __name__ == '__main__':
    img, code_str = check_code()
    print(code_str)

    # 保存在当前目录下
    with open('code.png', 'wb') as f:
        img.save(f, format='png')

3. 运行效果

可以看到验证码已生成,图片文件已保存在该目录下:

相关推荐
python-行者11 分钟前
akamai鼠标轨迹
爬虫·python·计算机外设·akamai
R-G-B41 分钟前
【P14 3-6 】OpenCV Python——视频加载、摄像头调用、视频基本信息获取(宽、高、帧率、总帧数)
python·opencv·视频加载·摄像头调用·获取视频基本信息·获取视频帧率·获取视频帧数
赵英英俊44 分钟前
Python day46
python·深度学习·机器学习
weixin_307779133 小时前
AWS Lambda解压缩S3 ZIP文件流程
python·算法·云计算·aws
独行soc10 小时前
2025年渗透测试面试题总结-18(题目+回答)
android·python·科技·面试·职场和发展·渗透测试
S01d13r11 小时前
gunicorn + flask 处理高并发请求
python·flask·gunicorn
杜子不疼.11 小时前
《Python列表和元组:从入门到花式操作指南》
开发语言·python
pan0c2311 小时前
数据处理与统计分析 —— numpy入门
python·numpy
max50060011 小时前
基于桥梁三维模型的无人机检测路径规划系统设计与实现
前端·javascript·python·算法·无人机·easyui
秋氘渔12 小时前
综合案例:Python 函数知识整合 — 学生成绩管理系统
开发语言·python