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?
I have found this function that helps me a lot (I put it for others to make use of it)
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
CodePudding user response:
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