在网上进行大量搜索之后,下面的代码可以完成我所要求的:
from PIL import Imageim = Image.open("logo_256.png")# PIL complains if you don't load explicitlyim.load()# Get the alpha bandalpha = im.split()[-1]im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)# Set all pixel values below 128 to 255,# and the rest to 0mask = Image.eval(alpha, lambda a: 255 if a <=128 else 0)# Paste the color of index 255 and use alpha as a maskim.paste(255, mask)# The transparency index is 255im.save("logo_py.png", transparency=255)来源:http :
//nadiana.com/pil-tips-converting-png-gif尽管此处的代码未调用im.load(),因此在我的os / python
/ pil版本上崩溃。(看来这是PIL中的错误)。



