Home  >  Article  >  Backend Development  >  How to Combine Images Horizontally in Python Without Partial Segments?

How to Combine Images Horizontally in Python Without Partial Segments?

Barbara Streisand
Barbara StreisandOriginal
2024-10-25 16:32:42943browse

How to Combine Images Horizontally in Python Without Partial Segments?

Combining Images Horizontally in Python

Aiming to horizontally combine multiple JPEG images, you may encounter challenges like additional partial images appearing in the output. Here's a solution that addresses this issue.

Problem:

You have three 148 x 95 pixel images, and you want to combine them horizontally without any unwanted extra segments.

Solution:

  1. Calculate Dimensions:

    • Get the widths and heights of all images as a list of tuples using the zip function.
    • Determine the total width by summing the widths and the maximum height by finding the maximum height.
  2. Create a New Image:

    • Create a new image with the dimensions calculated in step 1 using the Image.new method.
  3. Paste Images:

    • Initialize an x-coordinate offset to 0.
    • Iterate through each image in the original list.
    • Paste the current image onto the new image at the offset and set offset to the current image's width.

Using this modified code:

<code class="python">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')</code>

will produce the desired horizontally combined image without any partial segments.

The above is the detailed content of How to Combine Images Horizontally in Python Without Partial Segments?. 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