图片验证码 python版本

import random
import string
import base64
from io import BytesIO

from PIL import Image, ImageDraw, ImageFont


chars_lower_digits = string.ascii_lowercase + string.digits
def rndColor():
    """
    生成随机颜色
    :return:
    """
    return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255))

def generate_captcha(_list: list = []):
    captcha_text = "".join(random.choices(_list or chars_lower_digits, k=4))

    width, height = 120, 40
    image = Image.new("RGB", (width, height), color=(255, 255, 255))

    draw = ImageDraw.Draw(image)

    # font = ImageFont.truetype('DejaVuSerif.ttf', 36)
    try:
        font = ImageFont.truetype(
            "DejaVuSerif.ttf", 36
        )  # fix 可能出现问题的地方:需要服务器上面拥有这个字体才可以
    except IOError:
        font = ImageFont.load_default()  # type: ignore

    # text_width, text_height = draw.textsize(captcha_text, font)
    _, _, text_width, text_height = draw.textbbox((0, 0), captcha_text, font=font)
    draw.text(
        ((width - text_width) / 2, (height - text_height) / 2),
        captcha_text,
        font=font,
        fill=(0, 0, 0),
    )

    for i in range(80):
        # 写干扰点
        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())

    byte_arr = BytesIO()
    image.save(byte_arr, format="PNG")

    base64_img = base64.b64encode(byte_arr.getvalue()).decode("utf-8")

    return base64_img, captcha_text

 pip install pillow==10.2.0

posted @ 2024-04-12 11:13  小天狼鑫  阅读(6)  评论(0编辑  收藏  举报