手搓一个验证码

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
posted @ 2024-09-11 19:24  干炸小黄鱼  阅读(3)  评论(0编辑  收藏  举报