cloudairambo / utils /imagemagic_utils.py
rihancloud's picture
Deploy clean FastAPI backend without node_modules
99fdb5f
Raw History Blame Contribute Delete
2.62 kB
import os
import subprocess
import uuid
from shutil import which
from PIL import Image
from core.config import settings
# -------------------------------------------------
# Helper: check command availability
# -------------------------------------------------
def _has_cmd(cmd: str) -> bool:
return which(cmd) is not None
# -------------------------------------------------
# MAIN IMAGE CONVERTER
# -------------------------------------------------
def convert_image(input_path: str, output_ext: str):
output_ext = output_ext.lower().lstrip(".")
output_path = os.path.join(
settings.OUTPUT_DIR,
f"{uuid.uuid4().hex}.{output_ext}"
)
# -------------------------------------------------
# SPECIAL CASE: ICO (USE PILLOW — VERY RELIABLE)
# -------------------------------------------------
if output_ext == "ico":
return _convert_to_ico_pillow(input_path, output_path)
# -------------------------------------------------
# Prefer ImageMagick v7
# -------------------------------------------------
if _has_cmd("magick"):
cmd = [
"magick",
input_path,
"-background", "white",
"-flatten",
output_path
]
subprocess.run(cmd, check=True)
return output_path
# -------------------------------------------------
# Fallback to ImageMagick v6
# -------------------------------------------------
if _has_cmd("convert"):
cmd = [
"convert",
input_path,
"-background", "white",
"-flatten",
output_path
]
subprocess.run(cmd, check=True)
return output_path
# -------------------------------------------------
# No converter available
# -------------------------------------------------
raise RuntimeError(
"Image conversion failed: ImageMagick not installed"
)
# -------------------------------------------------
# PILLOW ICO CONVERTER (MULTI-SIZE ICON)
# -------------------------------------------------
def _convert_to_ico_pillow(input_path: str, output_path: str):
with Image.open(input_path) as img:
img = img.convert("RGBA")
sizes = [
(16, 16),
(32, 32),
(48, 48),
(64, 64),
(128, 128),
(256, 256),
]
img.save(
output_path,
format="ICO",
sizes=sizes
)
if not os.path.exists(output_path):
raise RuntimeError("ICO conversion failed")
return output_path