Home  >  Article  >  Backend Development  >  How to Combine Multiple Images Horizontally in Python Without Overlapping Issues?

How to Combine Multiple Images Horizontally in Python Without Overlapping Issues?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 08:23:02352browse

How to Combine Multiple Images Horizontally in Python Without Overlapping Issues?

Combining Images Horizontally in Python

This article addresses the issue of combining multiple JPEG images horizontally in Python.

Problem:

The user has three images of equal dimensions (148 x 95), and attempts to combine them horizontally using the provided code. However, the output has extra partial images overlapping previous sub-images.

Solution:

To resolve this issue, we can utilize the following 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('combined_horizontally.jpg')</code>

This code accomplishes the following:

  • Opens the input images and determines their widths and heights.
  • Calculates the total width and maximum height of the combined image.
  • Creates a new image with the calculated dimensions.
  • Pastes each input image horizontally into the new image with an appropriate offset.
  • Saves the combined image as combined_horizontally.jpg.

Additional Considerations:

  • The code dynamically determines the image dimensions, allowing it to handle images of varying sizes.
  • It specifies the dimensions on a single line, making it easy to adjust if needed.
  • By using the max function to determine the max height, the combined image will accommodate all input images, even if they have different heights.

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