feat: Implement image thumbnail generation, storage, and API endpoints for assets, including a regeneration utility.
This commit is contained in:
27
utils/image_utils.py
Normal file
27
utils/image_utils.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from io import BytesIO
|
||||
from typing import Tuple, Optional
|
||||
from PIL import Image
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def create_thumbnail(image_data: bytes, size: Tuple[int, int] = (800, 800)) -> Optional[bytes]:
|
||||
"""
|
||||
Creates a thumbnail from image bytes.
|
||||
Returns the thumbnail as bytes (JPEG format) or None if failed.
|
||||
"""
|
||||
try:
|
||||
with Image.open(BytesIO(image_data)) as img:
|
||||
# Convert to RGB if necessary (e.g. for RGBA/P images saving as JPEG)
|
||||
if img.mode in ('RGBA', 'P'):
|
||||
img = img.convert('RGB')
|
||||
|
||||
img.thumbnail(size)
|
||||
|
||||
thumb_io = BytesIO()
|
||||
img.save(thumb_io, format='JPEG', quality=85)
|
||||
thumb_io.seek(0)
|
||||
return thumb_io.read()
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create thumbnail: {e}")
|
||||
return None
|
||||
Reference in New Issue
Block a user