SoFunction
Updated on 2025-04-14

Detailed tutorial on using PIL library to splice pictures in Python

1. Install the Pillow library

First, you need to make sure that the Pillow library is installed in your Python environment. If you haven't installed it, you can use pip to install it:

pip install pillow

2. Import the necessary modules

In your Python script, you need to import the Image module in the Pillow library. This module provides all the functions required to process images.

from PIL import Image

3. Define the splicing function

Next, define a function to splice two images. This function will accept two images and a parameter (horizontal or vertical) that represents the direction of the stitching.

def concatenate_images(image1, image2, orientation='horizontal'):
    if orientation == 'horizontal':
        # Horizontal splicing        new_image = ('RGB', ( + , ))
        new_image.paste(image1, (0, 0))
        new_image.paste(image2, (, 0))
    elif orientation == 'vertical':
        # Vertical stitching        new_image = ('RGB', (,  + ))
        new_image.paste(image1, (0, 0))
        new_image.paste(image2, (0, ))
    else:
        raise ValueError('Orientation must be "horizontal" or "vertical"')
    return new_image

4. Load the picture

use()Method load the two pictures you want to splice. Make sure that the path you provide is correct and that the image file exists.

image1 = ('path_to_image1.jpg')
image2 = ('path_to_image2.jpg')

Will'path_to_image1.jpg'and'path_to_image2.jpg'Replace with the actual path to your image file.

5. Splice pictures

Call your definedconcatenate_images()Function, pass in two images and the direction you want to splice (‘horizontal’ or ‘vertical’).

concatenated_image = concatenate_images(image1, image2, 'horizontal')  # or 'vertical'

6. Save new pictures

usesave()Method to save the spliced ​​new image to your file system.

concatenated_image.save('concatenated_image.jpg')

Will'concatenated_image.jpg'Replace with the file name and format you want to save.

Complete code example

from PIL import Image

def concatenate_images(image1, image2, orientation='horizontal'):
    if orientation == 'horizontal':
        # Horizontal splicing        new_image = ('RGB', ( + , ))
        new_image.paste(image1, (0, 0))
        new_image.paste(image2, (, 0))
    elif orientation == 'vertical':
        # Vertical stitching        new_image = ('RGB', (,  + ))
        new_image.paste(image1, (0, 0))
        new_image.paste(image2, (0, ))
    else:
        raise ValueError('Orientation must be "horizontal" or "vertical"')
    return new_image

# Loading picturesimage1 = ('path_to_image1.jpg')
image2 = ('path_to_image2.jpg')

#Split picturesconcatenated_image = concatenate_images(image1, image2, 'horizontal')  # or 'vertical'
# Save new picturesconcatenated_image.save('concatenated_image.jpg')

Through the above steps, you can easily use the Pillow library to splice images. Whether it is horizontal or vertical splicing, this tutorial provides you with detailed guidance.

More complex picture stitching

Of course, we can write a more complex picture stitching function that can not only handle horizontal and vertical stitching, but also handle any number of pictures, and allow users to specify the spacing between the stitching pictures and the background color of the output image.

Here is an example of a more complex image stitching function:

from PIL import Image

def concatenate_images(images, orientation='horizontal', spacing=10, bg_color=(255, 255, 255)):
    """
    Functions for stitching pictures。

    parameter:
    images (list of ): List of pictures to be spliced。
    orientation (str): Splicing direction,'horizontal' Indicate level,'vertical' Indicates vertical。
    spacing (int): Spacing between pictures(Pixels)。
    bg_color (tuple): Output image background color,The format is (R, G, B)。

    return:
    : New pictures after splicing。
    """
    if not images:
        raise ValueError("The picture list cannot be empty")

    if orientation == 'horizontal':
        # Calculate the width and height of the picture after stitching        total_width = sum( for img in images) + (len(images) - 1) * spacing
        max_height = max( for img in images)
        new_image = ('RGB', (total_width, max_height), bg_color)

        # Paste the pictures in turn        current_x = 0
        for img in images:
            new_image.paste(img, (current_x, 0))
            current_x +=  + spacing
            # The last image does not require spacing            if current_x == total_width:
                break
            current_x -= spacing
    elif orientation == 'vertical':
        # Calculate the width and height of the picture after stitching        max_width = max( for img in images)
        total_height = sum( for img in images) + (len(images) - 1) * spacing
        new_image = ('RGB', (max_width, total_height), bg_color)

        # Paste the pictures in turn        current_y = 0
        for img in images:
            new_image.paste(img, (0, current_y))
            current_y +=  + spacing
            # The last image does not require spacing            if current_y == total_height:
                break
            current_y -= spacing
    else:
        raise ValueError('Orientation must be "horizontal" or "vertical"')

    return new_image

#User Exampleimages = [('path_to_image1.jpg'), ('path_to_image2.jpg'), ('path_to_image3.jpg')]
concatenated_image = concatenate_images(images, orientation='horizontal', spacing=20, bg_color=(255, 255, 255))
concatenated_image.save('concatenated_image.jpg')

In this function:

  1. Supports any number of pictures: Map any number of pictures by passing in an image list.
  2. Picture spacing:Added onespacingParameters, allowing users to specify the spacing between pictures.
  3. Background color:Added onebg_colorParameters, allowing users to specify the background color of the output image.
  4. Error handling: If the incoming picture list is empty, the function will throw aValueError

Note that when the splicing direction is horizontal, the sum of all image widths is calculated and the spacing between images is added (except the last image). Similarly, when the splicing direction is perpendicular, the sum of all image heights is calculated and the spacing between images is added. Finally, use()Method to create a new blank image and usepaste()Method Paste the original image onto the new image.

This is the article about this detailed tutorial on using the PIL library to splice pictures in Python. For more related contents of PIL library to splice pictures in Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!