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 PIL.
For instance, we write
import sys
from PIL import Image
images = [Image.open(x) for x in ['Test1.jpg', 'Test2.jpg', 'Test3.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')
to open the images with Image.open
.
Then we zip
the image sizes together and get their width
and height
.
Next, we get the total_width
and max_height
by adding up the widths
and heights
.
Then we create a new image with Image.new
with total_width
and max_height
.
Next, we add a for loop to put the pixels of the images into the new image.
Finally, we call save
to save the new image.
Conclusion
To combine several images horizontally with Python, we can use PIL.