Spaces:
Sleeping
Sleeping
File size: 2,241 Bytes
f88c368 4003ec5 0d060b5 f88c368 6eba959 f88c368 4003ec5 f88c368 4003ec5 f88c368 4003ec5 6eba959 f88c368 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
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()) |