You can pass to the combine_images
function number of expected columns
, space
between images in pixels and the list of images
:
from PIL import Image
def combine_images(columns, space, images):
rows = len(images) // columns
if len(images) % columns:
rows += 1
width_max = max([Image.open(image).width for image in images])
height_max = max([Image.open(image).height for image in images])
background_width = width_max*columns + (space*columns)-space
background_height = height_max*rows + (space*rows)-space
background = Image.new('RGBA', (background_width, background_height), (255, 255, 255, 255))
x = 0
y = 0
for i, image in enumerate(images):
img = Image.open(image)
x_offset = int((width_max-img.width)/2)
y_offset = int((height_max-img.height)/2)
background.paste(img, (x+x_offset, y+y_offset))
x += width_max + space
if (i+1) % columns == 0:
y += height_max + space
x = 0
background.save('image.png')
combine_images(columns=3, space=20, images=['apple_PNG12507.png', 'banana_PNG838.png', 'blackberry_PNG45.png', 'cherry_PNG635.png', 'pear_PNG3466.png', 'plum_PNG8670.png', 'strawberry_PNG2595.png'])
Result for 7 images and 3 columns:

Result for 6 images and 2 columns:
