FastAPI.6

发布时间 2023-09-05 10:41:10作者: zhangbinn

FastAPI.6

FastApi用pillow生成随机四位数字验证码图片

  1. 导入模块
    import random
    from fastapi import FastAPI,Response
    from PIL import Image, ImageDraw, ImageFont
    from io import BytesIO
    
  2. 代码
    def code():
    # 生成四位随机数字
        code = ""
        for _ in range(4):
            digit = str(random.randint(0, 9))
            code += digit
        return code
    
    
    @app.get('/code')
    def generate_image():
        number = code()
        width, height = 200, 100
        bg_color = (random.randint(10, 200), random.randint(20, 200), random.randint(50, 250))
        image = Image.new("RGB", (width, height), bg_color)
        draw = ImageDraw.Draw(image, 'RGB')
        # 如果没有Ceria Lebaran.otf字体文件,请替换为已有字体文件的路径
        font = ImageFont.truetype("Ceria Lebaran.otf", 80)
        num_particles = 200
        particle_size = 3  # 调整粒子大小
    
        # 随机绘制指定数量的粒子
        for _ in range(num_particles):
            x = random.randint(0, width-1)
            y = random.randint(0, height-1)
            # 随机选取颜色
            color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
            # 在指定位置绘制像素点
            draw.ellipse([(x-particle_size, y-particle_size), (x+particle_size, y+particle_size)], fill=color)
    
        text_width, text_height = draw.textsize(number, font=font)
        x = (width - text_width) // 2
        y = (height - text_height) // 2
    
        draw.text((x, y), number, font=font, fill=(0, 0, 0))
        # 将生成的图片保存到内存中
        image_io = BytesIO()
        image.save(image_io, 'PNG')
        image_io.seek(0)
    
        image.save("verification_code.png")  # 可以在本地看见生成的图片
        return Response(content=image_io.getvalue(), media_type='image/png')
    
    image