fix(recipe image): optimize image saving and update PNG metadata handling, fixes #481

This commit is contained in:
Will Miao
2025-09-25 10:43:10 +08:00
parent c85e694c1d
commit 6c3424029c
2 changed files with 14 additions and 6 deletions

View File

@@ -279,10 +279,17 @@ class RecipePersistenceService:
os.makedirs(recipes_dir, exist_ok=True) os.makedirs(recipes_dir, exist_ok=True)
recipe_id = str(uuid.uuid4()) recipe_id = str(uuid.uuid4())
image_filename = f"{recipe_id}.png" optimized_image, extension = self._exif_utils.optimize_image(
image_data=image_bytes,
target_width=self._card_preview_width,
format="webp",
quality=85,
preserve_metadata=True,
)
image_filename = f"{recipe_id}{extension}"
image_path = os.path.join(recipes_dir, image_filename) image_path = os.path.join(recipes_dir, image_filename)
with open(image_path, "wb") as file_obj: with open(image_path, "wb") as file_obj:
file_obj.write(image_bytes) file_obj.write(optimized_image)
lora_stack = metadata.get("loras", "") lora_stack = metadata.get("loras", "")
lora_matches = re.findall(r"<lora:([^:]+):([^>]+)>", lora_stack) lora_matches = re.findall(r"<lora:([^:]+):([^>]+)>", lora_stack)

View File

@@ -4,7 +4,7 @@ import logging
from typing import Optional from typing import Optional
from io import BytesIO from io import BytesIO
import os import os
from PIL import Image from PIL import Image, PngImagePlugin
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -86,9 +86,10 @@ class ExifUtils:
# For PNG, try to update parameters directly # For PNG, try to update parameters directly
if img_format == 'PNG': if img_format == 'PNG':
# We'll save with parameters in the PNG info # Use PngInfo instead of plain dictionary
info_dict = {'parameters': metadata} png_info = PngImagePlugin.PngInfo()
img.save(image_path, format='PNG', pnginfo=info_dict) png_info.add_text("parameters", metadata)
img.save(image_path, format='PNG', pnginfo=png_info)
return image_path return image_path
# For WebP format, use PIL's exif parameter directly # For WebP format, use PIL's exif parameter directly