45 lines
1.8 KiB
Python
45 lines
1.8 KiB
Python
from PIL import Image
|
|
import io
|
|
import base64
|
|
import logging # Import logging
|
|
|
|
# Get a logger instance for this module
|
|
logger = logging.getLogger(__name__)
|
|
|
|
def create_thumbnail_from_bytes(image_data_bytes, size=(128, 128), output_format='JPEG'):
|
|
"""
|
|
Creates a thumbnail from image data (bytes).
|
|
Returns the thumbnail as bytes.
|
|
"""
|
|
try:
|
|
img = Image.open(io.BytesIO(image_data_bytes))
|
|
img.thumbnail(size)
|
|
|
|
thumbnail_buffer = io.BytesIO()
|
|
# Ensure the output format is supported by Pillow and the original image
|
|
if img.mode == 'RGBA' and output_format == 'JPEG':
|
|
# Convert RGBA to RGB for JPEG output to avoid errors with alpha channel
|
|
img = img.convert('RGB')
|
|
logger.debug("Converted RGBA image to RGB for JPEG output.")
|
|
img.save(thumbnail_buffer, format=output_format)
|
|
thumbnail_buffer.seek(0)
|
|
logger.info(f"Thumbnail created from bytes. Size: {size}, Format: {output_format}")
|
|
return thumbnail_buffer.getvalue()
|
|
except Exception as e:
|
|
logger.error(f"Error creating thumbnail from bytes: {e}")
|
|
return None
|
|
|
|
def create_thumbnail_from_base64(base64_string, size=(128, 128), output_format='JPEG'):
|
|
"""
|
|
Decodes a base64 image string, creates a thumbnail, and returns the thumbnail as bytes.
|
|
"""
|
|
try:
|
|
decoded_image_data = base64.b64decode(base64_string)
|
|
logger.debug("Base64 string decoded successfully.")
|
|
return create_thumbnail_from_bytes(decoded_image_data, size, output_format)
|
|
except base64.binascii.Error as e:
|
|
logger.error(f"Invalid base64 string provided: {e}")
|
|
return None
|
|
except Exception as e:
|
|
logger.error(f"Error creating thumbnail from base64 string: {e}")
|
|
return None |