vnshed/backend/utils.py

25 lines
No EOL
657 B
Python

from PIL import Image, UnidentifiedImageError
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:
return 0
def save_image(img: bytes, dir: str, name: str) -> int:
path = asset(dir)
path.mkdir(exist_ok=True)
img = image_normalize(img)
if img:
with open(Path(path, name+'.webp'), "wb") as file:
file.write(img)
return len(img)