Paste an Image Into a Predefined Area with Python Pillow

Photo by Agata Create / Unsplash

The Python library Pillow adds image processing capabilities to your Python interpreter. This allows you to create, modify and save images in Python.

Pillow provides a paste() function for pasting an image on top of another image. By default this pastes the image without adjusting it's size. Read on to find out how to paste an image into a predefined area while also correctly resizing it.

We start off by importing the Pillow library and opening our two images:

from PIL import Image

image = Image.open("image.png")
canvas_image = Image.open("canvas.png")
image.png - Random Bitcoin logo I found on my PC
canvas.png - Yeah it's just a plain background. What did you expect?

Next up, we need to first define the area our pasted image should cover and also resize our image to fit that area. The format for the image area requires you to list the x and y pixel coordinates of the upper left and bottom right corner. For example, a rectangle covering all of an 800x600 pixel image is written as (0, 0, 800, 600).

image_position = (269, 233, 467, 431)
image = image.resize(
    (
        crypto_logo_position[2] - crypto_logo_position[0],
        crypto_logo_position[3] - crypto_logo_position[1],
    )
)

Finally we paste the image in the defined area and save the final image. Notice how we also list image at the end of the function call to use it as a mask. This essentially pastes the image without an ugly black or white background.

canvas.paste(image, image_position, image)
canvas.save("output.png")

As we can see on the final image, the Bitcoin logo was pasted at the location we specified earlier and resized accordingly.

Quoorex
Future Entrepreneur. Interested in tech, finance and becoming 1% better every day.
Germany