Spaces:
Sleeping
Sleeping
from PIL import Image | |
import os | |
from io import BytesIO | |
import base64 | |
import uuid | |
def resize_to_fit(image, max_size): | |
""" | |
Resize an image to fit within max_size (width, height) while preserving aspect ratio. | |
Returns a new image with transparent background and the resized image centered. | |
""" | |
image.thumbnail(max_size, Image.LANCZOS) # Resize while keeping aspect ratio | |
new_image = Image.new("RGB", max_size, (255, 255, 255)) # white background | |
paste_position = ( | |
(max_size[0] - image.width) // 2, | |
(max_size[1] - image.height) // 2, | |
) | |
new_image.paste(image, paste_position) | |
return new_image | |
async def combine_images_side_by_side(image1: bytes, image2: bytes) -> str: | |
""" | |
Takes two images, scales them to 1280x1280, combines them side by side, | |
saves to tmp storage, and returns the base64 encoded image string. | |
Args: | |
image1: First image as bytes | |
image2: Second image as bytes | |
Returns: | |
Base64 encoded string of the combined image | |
""" | |
print("combine images side by side") | |
# Create temp directory if it doesn't exist | |
os.makedirs('tmp', exist_ok=True) | |
# Open images from bytes | |
img1 = Image.open(BytesIO(image1)) | |
img2 = Image.open(BytesIO(image2)) | |
# Scale both images to 1280x1280 | |
img1 = resize_to_fit(img1, (1280, 1280)) | |
img2 = resize_to_fit(img2, (1280, 1280)) | |
# Create new image with combined width (2560) and height (1280) | |
combined = Image.new('RGB', (2560, 1280)) | |
# Paste images side by side | |
combined.paste(img1, (0, 0)) | |
combined.paste(img2, (1280, 0)) | |
# Generate unique filename | |
filename = f"tmp/combined_{uuid.uuid4()}.png" | |
print("filename: " + filename) | |
# Save image | |
combined.save(filename) | |
# Convert to base64 | |
with open(filename, "rb") as image_file: | |
encoded_string = base64.b64encode(image_file.read()).decode('utf-8') | |
# Clean up | |
#os.remove(filename) | |
print("combined images side by side") | |
return encoded_string | |
# Example usage: | |
# with open('image1.jpg', 'rb') as f1, open('image2.jpg', 'rb') as f2: | |
# combined_image = combine_images_side_by_side(f1.read(), f2.read()) |