How to use PIL to make all white pixels transparent?
You can also use pixel access mode to modify the image in-place:
from PIL import Image
img = Image.open('img.png')
img = img.convert("RGBA")
pixdata = img.load()
width, height = img.size
for y in range(height):
for x in range(width):
if pixdata[x, y] == (255, 255, 255, 255):
pixdata[x, y] = (255, 255, 255, 0)
img.save("img2.png", "PNG")
You can probably also wrap the above into a script if you use it often.
You need to make the following changes:
- append a tuple
(255, 255, 255, 0)
and not a list[255, 255, 255, 0]
- use
img.putdata(newData)
This is the working code:
from PIL import Image
img = Image.open('img.png')
img = img.convert("RGBA")
datas = img.getdata()
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
img.putdata(newData)
img.save("img2.png", "PNG")