Mostly works! Image loading and caching seems slow

This commit is contained in:
2025-02-16 20:36:13 -05:00
parent de565fce4f
commit b2ed4cc4e5
14 changed files with 625 additions and 6 deletions

46
src/rendering/image.py Normal file
View File

@ -0,0 +1,46 @@
from PIL import Image
from io import BytesIO
from functools import cache
@cache
def generate_thumbnail(image_path, resize_percent, min_width):
# Generate a unique key based on the image path, resize percentage, and minimum width
key = f"{image_path}_{resize_percent}_{min_width}"
# Open the image file
with Image.open(image_path) as img:
# Calculate the new size based on the resize percentage
width, height = img.size
new_width = int(width * resize_percent / 100)
new_height = int(height * resize_percent / 100)
# Ensure the minimum width is maintained
if new_width < min_width:
scale_factor = min_width / new_width
new_width = min_width
new_height = int(new_height * scale_factor)
# Resize the image while maintaining the aspect ratio
img.thumbnail((new_width, new_height))
# Rotate the image based on the EXIF orientation tag
try:
exif = img._getexif()
orientation = exif.get(0x0112, 1) # 0x0112 is the EXIF orientation tag
if orientation == 3:
img = img.rotate(180, expand=True)
elif orientation == 6:
img = img.rotate(270, expand=True)
elif orientation == 8:
img = img.rotate(90, expand=True)
except (AttributeError, KeyError, IndexError):
# cases: image don't have getexif
pass
# Save the thumbnail to a BytesIO object
thumbnail_io = BytesIO()
img_format = img.format if img.format in ["JPEG", "JPG", "PNG"] else "JPEG"
img.save(thumbnail_io, format=img_format)
thumbnail_io.seek(0)
return (thumbnail_io, img_format)