热门标签:
Q:

在每个图像之间填充空白

在上一个关于以下链接的问题Concatenate muliple images with pillow in python中,我得到了以下代码,将每四个图像合并在一起。 代码工作得很好,我很感激@CrazyChucky

from pathlib import Path

from more_itertools import chunked
from PIL import Image


def concat_images(*images):
    """Generate composite of all supplied images."""
    # Get the widest width.
    width = max(image.width for image in images)
    # Add up all the heights.
    height = sum(image.height for image in images)
    composite = Image.new('RGB', (width, height))
    # Paste each image below the one before it.
    y = 0
    for image in images:
        composite.paste(image, (0, y))
        y += image.height
    return composite


if __name__ == '__main__':
    # Define the folder to operate on (currently set to the current
    # working directory).
    images_dir = Path('.')
    # Define where to save the output (shown here, will be in `output`
    # inside the images dir).
    output_dir = images_dir / 'output'
    # Create the output folder, if it doesn't already exist.
    output_dir.mkdir(exist_ok=True)

    # Iterate through the .png files in groups of four, using an index
    # to name the resulting output.
    png_paths = images_dir.glob('*.png')
    for i, paths in enumerate(chunked(png_paths, 4), start=1):
        images = [Image.open(path) for path in paths]
        composite = concat_images(*images)
        composite.save(output_dir / f'{i}.png')

我的问题是如何在每个图像之间添加填充空白?

我已经找到了这个功能,帮助我很多(我把它给别人利用它)

def add_margin(pil_img, top, right, bottom, left, color):
    width, height = pil_img.size
    new_width = width + right + left
    new_height = height + top + bottom
    result = Image.new(pil_img.mode, (new_width, new_height), color)
    result.paste(pil_img, (left, top))
    return result
原网址
A:

这似乎很清楚。 你只需要为图像填充高度。

def concat_images(*images):
    """Generate composite of all supplied images."""
    # Get the widest width.
    width = max(image.width for image in images)
    # Add up all the heights.
    padding = 10
    height = sum(image.height+padding for image in images) - padding
    composite = Image.new('RGB', (width, height))
    # Paste each image below the one before it.
    y = 0
    for image in images:
        composite.paste(image, (0, y))
        y += image.height + padding
    return composite

相似问题