Home > database >  How to combine several images to one image in a Grid structure in Python?
How to combine several images to one image in a Grid structure in Python?

Time:06-24

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.

CodePudding user response:

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

  • Related