如何使用 PIL 使所有白色像素透明? [英] How to use PIL to make all white pixels transparent?
本文介绍了如何使用 PIL 使所有白色像素透明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 Python 图像库使所有白色像素透明.(我是一个试图学习 python 的 C 黑客,所以要温柔)我已经进行了转换(至少像素值看起来是正确的),但我不知道如何将列表转换为缓冲区以重新创建图像.这是代码
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
img = Image.open('img.png')
imga = img.convert("RGBA")
datas = imga.getdata()
newData = list()
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)
imgb = Image.frombuffer("RGBA", imga.size, newData, "raw", "RGBA", 0, 1)
imgb.save("img2.png", "PNG")
推荐答案
您需要进行以下更改:
- 追加元组
(255, 255, 255, 0)
而不是列表[255, 255, 255, 0]
- 使用
img.putdata(newData)
- append a tuple
(255, 255, 255, 0)
and not a list[255, 255, 255, 0]
- use
img.putdata(newData)
这是工作代码:
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")
这篇关于如何使用 PIL 使所有白色像素透明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文