# Makes a collage image from a directory full of images
#
# Assumes all the images are the same size and square

from os import listdir
from PIL import Image
import random
import math

images = listdir('.')

aspect = 1.77 # Aspect ratio of the output image

# Know cols * rows = len(images)
# Want cols = rows * aspect, multiply by cols
# => cols * cols = rows * cols * aspect, substitute len(images)
# => cols^2 = len(images) * aspect
# => cols = sqrt(len(images) * aspect)

cols = int(math.sqrt(len(images) * aspect))
rows = int(math.ceil(float(len(images))/float(cols)))

random.shuffle(images)
im = Image.open(images[0])
(w, h) = im.size
im.close()

(width, height) = (w*cols, h*rows)

collage = Image.new("RGB", (width, height))
for y in range(rows):
    for x in range(cols):
        i = y*cols + x
        # Fill in extra images by duplicating some images randomly
        if i >= len(images):
            i = random.randrange(len(images))
        p = Image.open(images[i])
        collage.paste(p, (x*w,y*h))
        im.close()

collage.save('collage.png')
collage.close()