如何在Python中使用网格结构将多张图片合并为一张图片?

6
我有几张图片(PNG格式),我想将它们合并成一个网格结构的图像文件(以便我可以设置每行显示的图像数量)。此外,我想在图像之间添加一些小的空白间隔。
例如,假设有7张图片。我想将每行显示的图像数设置为3。合并图像的一般结构如下:

enter image description here

请告诉我,如果你知道一个好的方法来实现这个(最好使用 PIL/Pillowmatplotlib 库)。谢谢。

这可能是 https://dev59.com/WG455IYBdhLWcg3wD_sB 的重复问题。 - Ian Cheung
1个回答

6
你可以将预期的列数columns、像素中的图像间隔space和图像列表images传递给combine_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'])

展示7张图片,3列结果如下:

7 images and 3 columns

展示6张图片,2列结果如下:

6 images and 2 columns


非常感谢。它运行良好。但是,我想设置列数(每行显示的图像数)。不过,我可以修改您的代码。再次感谢。 - Mohammad
一个要点:当“len(images)%rows”= 0时,列将为零。例如,我有6张图片,行= 3。在这种情况下,列= 0,并且我会收到错误消息:“ValueError:宽度和高度必须> = 0” - Mohammad
1
这两个问题都应该得到解决。请查看我的更新代码。 - Alderven

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接