Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Have padding white space between each image

In a previous question on the following link Concatenate muliple images with pillow in python, I got the following code that merges each four images together. The code is working very well and I appreciate that to @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')

My question is how to add padding white space between each image?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This seems pretty clear. You just need to pad the height for the 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.
    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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading