使用PIL将PNG32转换为PNG8,同时保持透明度 [英] Converting PNG32 to PNG8 with PIL while preserving transparency

查看:322
本文介绍了使用PIL将PNG32转换为PNG8,同时保持透明度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Python图像库将PNG32图像(具有透明性)转换为PNG8. 到目前为止,我已经成功转换为具有扎实背景的PNG8.

I would like to convert a PNG32 image (with transparency) to PNG8 with Python Image Library. So far I have succeeded converting to PNG8 with a solid background.

下面是我在做什么:

from PIL import Image
im = Image.open("logo_256.png")
im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)
im.save("logo_py.png", colors=255)

推荐答案

在网上进行了大量搜索之后,下面的代码即可完成我所要求的操作:

After much searching on the net, here is the code to accomplish what I asked for:

from PIL import Image

im = Image.open("logo_256.png")

# PIL complains if you don't load explicitly
im.load()

# Get the alpha band
alpha = 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 0
mask = Image.eval(alpha, lambda a: 255 if a <=128 else 0)

# Paste the color of index 255 and use alpha as a mask
im.paste(255, mask)

# The transparency index is 255
im.save("logo_py.png", transparency=255)

来源: http://nadiana.com/pil-tips-converting-png- gif 尽管那里的代码没有调用im.load(),因此在我的os/python/pil版本上崩溃了. (看来这是PIL中的错误).

Source: http://nadiana.com/pil-tips-converting-png-gif Although the code there does not call im.load(), and thus crashes on my version of os/python/pil. (It looks like that is the bug in PIL).

这篇关于使用PIL将PNG32转换为PNG8,同时保持透明度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆