15 Jun 2023
Goal is to have a mosaic of logos from a folder of images. The images are resized to the same size and arranged in a square grid.
logos_folder = '/Users/xxx/logos'
output_image = '/Users/xxx/mosaic.jpg'
import os
from PIL import Image
def create_collage(image_dir, output_filename):
# Get the list of image file names
files = [f for f in os.listdir(image_dir) if os.path.isfile(os.path.join(image_dir, f))]
# Make sure there are at least some files
if not files:
print(f"No images found in directory {image_dir}")
return
# Sort the images by name
files.sort()
# Open images and find maximum width and height
images = []
for f in files:
images.append(Image.open(os.path.join(image_dir, f)))
# Determine the maximum width and height among all images
max_width, max_height = max(img.size for img in images)
# Adjust the width and height of each image to the maximum values, creating a consistent grid
resized_images = [img.resize((max_width, max_height)) for img in images]
# Let's arrange the images in square manner
num_images_side = int(len(resized_images) ** 0.5)
while len(resized_images) % num_images_side != 0:
num_images_side -= 1
num_images_side = max(1, num_images_side) # Make sure it's at least 1
# Calculate total width and height
total_width = max_width * num_images_side
total_height = max_height * (len(resized_images) // num_images_side)
# Create new collage image
collage = Image.new('RGB', (total_width, total_height))
# Position images
x_offset = 0
y_offset = 0
for i, img in enumerate(resized_images):
collage.paste(img, (x_offset, y_offset))
x_offset += img.width
if (i+1) % num_images_side == 0: # Next row
x_offset = 0
y_offset += img.height
# Save collage
collage.save(output_filename)
print(f"Collage created at {output_filename}")
# Example usage:
create_collage(logos_folder, output_image)