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.
Approach:
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] == 0 and item[1] == 0 and item[2] == 0:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
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).
rgba.putdata(newData)
rgba.save(“transparent_image.png”, “PNG”)
Implementation:
Python3
from PIL import Image img = Image. open ( 'image.png' ) rgba = img.convert( "RGBA" ) datas = rgba.getdata() newData = [] for item in datas: if item[ 0 ] = = 0 and item[ 1 ] = = 0 and item[ 2 ] = = 0 : # finding black colour by its RGB value # storing a transparent value when we find a black colour newData.append(( 255 , 255 , 255 , 0 )) else : newData.append(item) # other colours remain unchanged rgba.putdata(newData) rgba.save( "transparent_image.png" , "PNG" ) |
Output:
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 –
Python3
from PIL import Image img = Image. open ( 'image.png' ) rgba = img.convert( "RGBA" ) datas = rgba.getdata() newData = [] for item in datas: if item[ 0 ] = = 255 and item[ 1 ] = = 255 and item[ 2 ] = = 0 : # finding yellow colour # replacing it with a transparent value newData.append(( 255 , 255 , 255 , 0 )) else : newData.append(item) rgba.putdata(newData) rgba.save( "transparent_image.png" , "PNG" ) |
Output:
Here we make the yellow color transparent.