from PIL import Image, UnidentifiedImageError from fastapi import HTTPException from pathlib import Path import io def asset(path: str) -> Path: return Path("store", path) def image_normalize(img: bytes) -> bytes: try: byte_arr = io.BytesIO() img = Image.open(io.BytesIO(img)) img.save(byte_arr, format='WEBP') return byte_arr.getvalue() except UnidentifiedImageError: raise HTTPException(status_code=500, detail="Image file cannot be readed!") def save_image(img: bytes, dir: str, name: str) -> int: path = asset(dir) path.mkdir(exist_ok=True) img = image_normalize(img) with open(Path(path, name+'.jpg'), "wb") as file: file.write(img) return len(img) def save_file(file_b: bytes, dir: str, name: str) -> int: path = asset(dir) path.mkdir(exist_ok=True) with open(Path(path, name+'.jpg'), "wb") as file: file.write(file_b) return len(file_b)