Python PIL – Make image transparent

In this post we will be creating a Python script that will apply a transparent mask on an existing image, to do this we will be using the Python Imaging Library also known as PIL enabling us to image processing capabilities.

See the sample of Python code where we utilise the PIL library to make an existing image transparent and save it as a new file. To help us achieve this we utilize the ‘Image.putalpha()’ method which adds or replaces the alpha layer. Here we set the mode to ‘L’ which uses a single channel image i.e. 256 variations of gray with black and white included.

from PIL import Image

img ='image.png')

mask ='L', img.size, 128)

See the following example of our image before a transparent mask.

Image before transparent mask

See the image below with a transparent mask applied.

image with transparent mask

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply