Skip to content

Instantly share code, notes, and snippets.

@isakvik
Created May 4, 2022 18:53
Show Gist options
  • Save isakvik/6c5d14b1d969db667ed77025238e32bb to your computer and use it in GitHub Desktop.
Save isakvik/6c5d14b1d969db667ed77025238e32bb to your computer and use it in GitHub Desktop.
from math import floor, ceil
from PIL import Image, ImageOps
import os
import random
collage_filename = "__collage.png"
path = "your_imagefolder_path_here"
def best_ratio(width, height):
ratio = width / height
best = 100
bestx = 0
besty = 0
for x in range(1, 20):
for y in range(1, 20):
if x * y > num_pics:
diff = min(best, abs(ratio - (x / y)))
if best > diff:
best = diff
bestx, besty = x, y
return bestx, besty
os.chdir(path)
list = os.listdir(".")
if list.count(collage_filename) > 0:
list.remove(collage_filename)
random.shuffle(list)
width = 1920*2
height = 1080*2 - 20
# init as black
collage = Image.new("RGBA", [width, height], "#000000ff")
num_pics = len(list)
rows, cols = best_ratio(width, height)
imgw = ceil(width / rows)
imgh = ceil(height / cols)
x, y, i = 0, 0, 0
empty_rows = floor((rows * cols - num_pics) / cols)
padding_y = int(empty_rows * (imgh / 2))
for file in list:
x, y = (i % rows), floor(i / rows)
img = Image.open(file)
img = ImageOps.fit(img, [imgw, imgh], Image.BICUBIC)
collage.paste(img, [x * imgw, y * imgh + padding_y, (x+1) * imgw, (y+1) * imgh+ padding_y])
i += 1
collage.save(collage_filename, "PNG")
print(f"saved to file {path}/{collage_filename}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment