Create transparent png image with Python – Pillow
To create a transparent png using Python3, the Pillow library is used. The Pillow library comes with python itself. If python is unable to find Pillow library then open the command prompt and run this command:-
pip install Pillow
Note: If you got any problem installing Pillow using pip, then install and setup pip first. For this check this article.
1. import the Image module from the Pillow library
from PIL import Image
2. Open any image and get the RAGBAG values.
img = Image.open(‘image.png’)
rgba = img.convert(“RGBA”)
datas = rgba.getdata()
3. Change the color
Data will be an Imaging Core object containing thousands of tuples of RGBA values. To make transparent the background firstly we have to find the RGBA values of the background or any color we want to make transparent. Here in this image, the background color is black.
The RGB value of black is (0, 0, 0). Now we will loop through the data (RGBA values) and whenever we find a black pixel we will replace it with a transparent RGBA value which is ((255, 255, 255, 0), and the other colors will be unchanged. And we will store the values in a new list called newData.
newData = 
for item in datas:
if item == 0 and item == 0 and item == 0:
newData.append((255, 255, 255, 0))
4. Store the changed image
Store the newData into RGBA value and save the image as a png format(transparent image can’t be stored into jpg or jpeg format).
Now taking the same image if we want to make the yellow color transparent we need to make the yellow pixels transparent. For this, we have to find the yellow color by its RBG values(255, 255, 0) and replace it with (255, 255, 255, 0).
The new code looks like this –
Here we make the yellow color transparent.
Please Login to comment...