Files
toolbox/utils/image.py
T

58 lines
1.7 KiB
Python

from utils.loggers import logger
def saveImage(file_bytes: bytes, file_name: str) -> bool:
import os
from PIL import Image
import io
# Убедимся, что путь существует
file_name = f"api/{file_name}"
os.makedirs(os.path.dirname(file_name), exist_ok=True)
# Загружаем изображение
try:
img = Image.open(io.BytesIO(file_bytes))
img.load()
except Exception as e:
logger.error(f"[ImageSave] Unsupported image format: {e}")
return False
# Конвертация в нормальный режим (PNG поддерживает RGBA/RGB)
try:
if img.mode not in ("RGB", "RGBA"):
img = img.convert("RGB")
except Exception as e:
logger.error(f"[ImageSave] Mode conversion error: {e}")
return False
# Сохраняем как PNG
try:
target_path = file_name
if not target_path.lower().endswith(".png"):
target_path += ".png"
logger.info(f"[ImageSave] Saving image to {target_path}")
img.save(target_path, "PNG")
return True
except Exception as e:
logger.error(f"[ImageSave] Error saving image: {e}")
return False
def deleteImage(fileName: str):
if fileName.endswith("default.png"):
return True
try:
import os
file_name = f"api/{file_name}"
logger.info(f"Удаляем изображение {fileName}")
os.remove(f"static/images/{fileName}")
logger.info(f"Изображение {fileName} успешно удалено")
return True
except Exception as e:
logger.error(f"Ошибка удаления изображения: {str(e)}")
return False