惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
Docker
人人都是产品经理
人人都是产品经理
小众软件
小众软件
博客园 - Franky
WordPress大学
WordPress大学
Jina AI
Jina AI
Google DeepMind News
Google DeepMind News
I
InfoQ
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
F
Fortinet All Blogs
博客园 - 【当耐特】
IT之家
IT之家
G
Google Developers Blog
J
Java Code Geeks
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
云风的 BLOG
云风的 BLOG
Recent Announcements
Recent Announcements
有赞技术团队
有赞技术团队
V
Visual Studio Blog
U
Unit 42
阮一峰的网络日志
阮一峰的网络日志
月光博客
月光博客
GbyAI
GbyAI
雷峰网
雷峰网

博客园 - 干炸小黄鱼

timex 处理时间戳 gorm-gen go 雪花算法 golang每日一库--协程池库ants golang每日一库--json解析库gjson python高级编程-asyncio python高级编程-condition python高级编程-event python装饰器-自动重试 EAP系统 go实现实现 SECS/GEM 协议 设备通信协议 SECS go项目使用Jenkins进行CICD go操作ES mongo db聚合查询 go如何使用mongodb Apache ShardingSphere paxos and raft (分布式一致性算法) go使用zookeeper分布式锁以及和redis差异 go使用 seata 示例 Alibaba 分布式事务 Seata go中使用saga go中使用TCC示例 分布式事务TCC 熔断器 Hystrix OR Sentinel k8s下部署consul and etcd Consul OR Etcd 【力扣hot100】双指针-盛水最多的容器 【力扣hot100】滑动窗口-最小覆盖子串 shell脚本合集
手搓一个验证码
干炸小黄鱼 · 2024-09-11 · via 博客园 - 干炸小黄鱼
import io
import os
import string
from random import choice, randrange, sample
from PIL import Image, ImageDraw, ImageFont



def generate_captcha():
    img_width = 58
    img_height = 30
    font_size = 16
    font_color = ["black", "darkblue", "darkred"]
    background = (randrange(230, 255), randrange(230, 255), randrange(230, 255))
    line_color = (randrange(0, 255), randrange(0, 255), randrange(0, 255))
    current_path = os.path.dirname(os.path.abspath(__file__))
    sample_file = os.path.join(current_path, "../static/fonts/LucidaSansDemiOblique.ttf")
    font = ImageFont.truetype(sample_file, font_size)
    img = Image.new("RGB", (img_width, img_height), background)
    captcha = "".join(sample(string.ascii_letters + string.digits, 4))
    draw = ImageDraw.Draw(img)
    for i in range(randrange(3, 5)):
        xy = (
            randrange(0, img_width),
            randrange(0, img_height),
            randrange(0, img_width),
            randrange(0, img_height),
        )
        draw.line(xy, fill=line_color, width=1)
    x = 2
    for i in captcha:
        y = randrange(0, 10)
        draw.text((x, y), i, font=font, fill=choice(font_color))
        x += 14
    buf = io.BytesIO()
    img.save(buf, "gif")
    buf.seek(0)
    return captcha, buf

captcha, captcha_img = generate_captcha()
# 验证码内容 存储到session, 返回图片展示
session["captcha"] = captcha.lower()
return captcha_img