0 votes
in Python Imaging Library by
Can you write a Python script using PIL to merge multiple images into one?

1 Answer

0 votes
by

Yes, using PIL’s Image module, we can merge multiple images into one. Here is a simple script:

from PIL import Image

def merge_images(image_files):

    images = [Image.open(x) for x in image_files]

    widths, heights = zip(*(i.size for i in images))

    total_width = max(widths)

    total_height = sum(heights)

    new_image = Image.new('RGB', (total_width, total_height))

    y_offset = 0

    for img in images:

        new_image.paste(img, (0,y_offset))

        y_offset += img.height

    new_image.save('merged_image.jpg')

merge_images(['image1.jpg', 'image2.jpg', 'image3.jpg'])

This script opens each image file, calculates the combined height and maximum width, creates a new blank image of that size, then pastes each image onto it at the appropriate offset.

...