Transparent Background

Learn PIL basics and pasting in PIL before you attempt this topic.

A typical PNG image with a transparent background has an alpha channel.

You can inspect an image to check if its background is transparent. First, check its mode.

Transparent backgrounds need to be “RGBA” mode. They have an Alpha Channel (“A”) that contains opacity values.

cat = Image.open('cat.png')
print(cat.mode)
# mode needs to be "RGBA"

If your image is RGB (no transparency), you might be able to use a tool such as remove.bg to make the background transparent and download a new copy of it.

The alpha channel of your image becomes a mask. A mask is a list of values that show which pixels are opaque and which ones are transparent. In fact, some pixels can be partially opaque. Alpha values range from 0 (completely transparent) to 255 (completely opaque).

A transparent PNG image contains its own mask. The alpha channel is the mask.

Here’s the code to paste a transparent image named “cat” onto a larger background named “bg”. This shows how to do it with and without the mask.

Notice the third argument in the last line:

# cat background will not be transparent
bg.paste(cat, (0,0))

# cat background is transparent
bg.paste(cat, (0,0), cat)

By adding “, cat” at the end of the paste() function call, you are telling the function to use the “cat” image as a transparency mask. This means only the colors with an opaque alpha value will change the colors of the background image.

Note: this won’t work if the image isn’t actually transparent. Be aware that some online images are labeled as transparent, but they actually aren’t. Try a different image if you suspect this problem. You can also inspect the pixels of the image. Look at a pixel in the background and see if the last value is zero.

Example 1: This RGBA pixel is black color and opaque (A = 255).
An image with this type of background will paste a black rectangle over your background image, which isn’t what you want.
(0, 0, 0, 255)

Example 2: This RGBA pixel is black and is transparent (A = 0).
An image with this type of background will work properly as a transparency mask.
(0, 0, 0, 0)

You can use the getpixel() function to check one of your pixel. Usually the top left corner, (0, 0), will be part of the transparent background, so for an Image object named “img” you could try this:

print(img.getpixel((0,0))