Home >Backend Development >Python Tutorial >How to Concatenate Multiple Images Horizontally in Python Using Pillow?

How to Concatenate Multiple Images Horizontally in Python Using Pillow?

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 02:06:30804browse

How to Concatenate Multiple Images Horizontally in Python Using Pillow?

Concatenating Images Horizontally with Python

Combining multiple images horizontally is a common task in image processing. Python offers powerful tools to achieve this using the Pillow library.

Problem Description

Consider three square JPEG images of dimensions 148 x 95. The goal is to horizontally concatenate these images while avoiding any partial images in the resulting output.

Suggested Solution

The following code snippet addresses the problem:

<code class="python">import sys
from PIL import Image

# Get the images
images = [Image.open(x) for x in ['Test1.jpg', 'Test2.jpg', 'Test3.jpg']]

# Determine the total width and height
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)

# Create a new, empty image
new_im = Image.new('RGB', (total_width, max_height))

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

# Save the output image
new_im.save('test.jpg')</code>

This code iterates over the input images, determining their dimensions. It creates a new image with the total width and the maximum height of all the images. Each input image is pasted horizontally, and their positions are updated accordingly.

Additional Considerations

  • The code avoids hard-coding image dimensions by dynamically calculating them.
  • By specifying the dimensions in one line, they can be easily adjusted.
  • The provided example concatenates three images, but the code can be used for any number of images.

The above is the detailed content of How to Concatenate Multiple Images Horizontally in Python Using Pillow?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn