I’m trying to make all white pixels transparent using the Python Image Library. (I’m a C hacker trying to learn python so be gentle) I’ve got the conversion working (at least the pixel values look correct) but I can’t figure out how to convert the list into a buffer to re-create the image. Here’s the code
JavaScript
x
14
14
1
img = Image.open('img.png')
2
imga = img.convert("RGBA")
3
datas = imga.getdata()
4
5
newData = list()
6
for item in datas:
7
if item[0] == 255 and item[1] == 255 and item[2] == 255:
8
newData.append([255, 255, 255, 0])
9
else:
10
newData.append(item)
11
12
imgb = Image.frombuffer("RGBA", imga.size, newData, "raw", "RGBA", 0, 1)
13
imgb.save("img2.png", "PNG")
14
Advertisement
Answer
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:
JavaScript
1
16
16
1
from PIL import Image
2
3
img = Image.open('img.png')
4
img = img.convert("RGBA")
5
datas = img.getdata()
6
7
newData = []
8
for item in datas:
9
if item[0] == 255 and item[1] == 255 and item[2] == 255:
10
newData.append((255, 255, 255, 0))
11
else:
12
newData.append(item)
13
14
img.putdata(newData)
15
img.save("img2.png", "PNG")
16