backend: convert input images to webp

This commit is contained in:
OleSTEEP 2025-10-02 23:09:00 +03:00
parent d786d7f7af
commit 4921d4bd6f
5 changed files with 32 additions and 7 deletions

25
backend/utils.py Normal file
View file

@ -0,0 +1,25 @@
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)