How to superimpose two images using PIL in Python

Padding is used to create space inside any defined borders around an element’s content. Here, the element is the image.

PIL (Python Imaging Library) or Pillow is a library widely used for image processing in Python(3.10). PIL supports a wide number of file types, and it has powerful image-processing capabilities.

There are many modules in the PIL library for different purposes. One such module is the Image module. The Image module offers a variety of factory operations, including tools for generating new pictures and loading images from files.

The paste function

Two images can be superimposed on another using the paste() function from the Image module.

Syntax

image_object.paste(image_object, box=None)

Parameters

  • image_object: The image to be merged/superimposed.
  • box: This is an optional parameter and can be used in two different ways. A 4-tuple gives the region to paste into, and if a 2-tuple is used, then it’s treated as the upper left corner. If this parameter is left blank, then it defaults to (0, 0).

Code example

Let’s look at the code below:

from PIL import Image
image_1 = Image.open("/usr/local/src/test1.png")
image_2 = Image.open("/usr/local/src/test2.png")
box = (40, 120)
image_1.paste(image_2, box)
image_1.save("output/superimposed.png")

Code explanation

  • Line 1: The Image module from the PIL library is imported.
  • Line 3: The first image is loaded into memory.
  • Line 5: The second image is loaded into memory.
  • Line 7: The box coordinate is defined.
  • Line 9: The image_2 is pasted onto the image_1. Now, image_1 has a superimposed image.
  • Line 11: The superimposed image is saved to disk.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved