File size: 614 Bytes
a150cf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from __future__ import annotations

import base64
import io
from PIL import Image
from fastapi import HTTPException


def load_image_from_base64(b64: str, *, max_bytes: int) -> Image.Image:
    try:
        raw = base64.b64decode(b64, validate=True)
    except Exception:
        raise HTTPException(status_code=400, detail="Invalid base64 image")

    if len(raw) > max_bytes:
        raise HTTPException(status_code=413, detail="Image too large")

    try:
        return Image.open(io.BytesIO(raw)).convert("RGB")
    except Exception:
        raise HTTPException(status_code=400, detail="Invalid image bytes")