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.open('image.png') mask = Image.new('L', img.size, 128) img.putalpha(mask) img.save('transparent_image.png')
See the following example of our image before a transparent mask.
See the image below with a transparent mask applied.
Take a look at some of our other content around the Python programming language by clicking here.