5

I have several images (PNG format) that I want to combine them into one image file in a grid structure (in such a way that I can set the No. of images shown in every row). Also, I want to add small empty space between images.

For example, assume that there are 7 images. And I want to set the No. of images shown in every row as 3. The general structure of the combined image will be:

enter image description here

Please let me know if you know a good way to do that (preferably using PIL/Pillow or matplotlib libraries). Thanks.

Mohammad
  • 775
  • 1
  • 14
  • 37
  • This could be duplicate of https://stackoverflow.com/questions/4567409/python-image-library-how-to-combine-4-images-into-a-2-x-2-grid – Ian Cheung Jun 23 '22 at 07:01

1 Answers1

5

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:

7 images and 3 columns

Result for 6 images and 2 columns:

6 images and 2 columns

Alderven
  • 7,569
  • 5
  • 26
  • 38
  • Thanks a lot. It works fine. However, I wanted to set the No. of columns (No. of images shown in every row). But, I can modify your code. Thanks again. – Mohammad Jun 23 '22 at 14:09
  • One point: when "len(images) % rows"=0, columns will be zero. For example, I have 6 images, and row=3. In this case, columns =0, and I get the error : "ValueError: Width and height must be >= 0" – Mohammad Jun 23 '22 at 14:22
  • 1
    Both of the issues should be fixed. See my updated code. – Alderven Jun 23 '22 at 14:48