Home >Backend Development >Python Tutorial >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 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!