Categories
Python Answers

How to combine several images horizontally with Python?

Spread the love

Sometimes, we want to combine several images horizontally with Python.

In this article, we’ll look at how to combine several images horizontally with Python.

How to combine several images horizontally with Python?

To combine several images horizontally with Python, we can use the PIL module.

For instance, we write:

from PIL import Image

images = [Image.open(x) for x in ['test1.png', 'test2.jpg']]
widths, heights = zip(*(i.size for i in images))

total_width = sum(widths)
max_height = max(heights)

new_im = Image.new('RGB', (total_width, max_height))

x_offset = 0
for im in images:
    new_im.paste(im, (x_offset, 0))
    x_offset += im.size[0]

new_im.save('test.jpg')

We open all the images with:

images = [Image.open(x) for x in ['test1.png', 'test2.jpg']]

Then we get widths and heights of all the images and put them in lists with:

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

Then we get the total width and max height with:

total_width = sum(widths)
max_height = max(heights)

which we set as the dimensions of the combined image.

Next, we combine the pixels from both images into a new image with:

new_im = Image.new('RGB', (total_width, max_height))

x_offset = 0
for im in images:
    new_im.paste(im, (x_offset, 0))
    x_offset += im.size[0]

The pixels are pasted with:

new_im.paste(im, (x_offset, 0))

Finally, we save the image with new_im.save('test.jpg').

Conclusion

To combine several images horizontally with Python, we can use the PIL module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *