gpt4 book ai didi

python PIL : Create indexed color image with transparent background

转载 作者:太空宇宙 更新时间:2023-11-03 11:09:52 24 4
gpt4 key购买 nike

我想知道如何创建具有透明背景且只有 2 种索引颜色(红色和蓝色)的图像以最小化文件大小?

更具体地说,我有两个要转换的黑白图像,一个为透明和蓝色,另一个为透明和红色。然后我想合并这两个图像。我可以使用常规 RGBA 图像来做到这一点,但我真的希望对颜色进行索引以最小化文件大小。

理想情况下使用 PIL,但其他 Python 库也可以工作。

最佳答案

所以我设法做到了,使用“调色板”图像类型,但生成的文件并不像我预期的那么小...这是我的代码,以防它对其他人有用,或者如果有人可以改进它。

from PIL import Image

im = Image.open("image1.png")
imP = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=3)
imP.putpalette([
0, 0, 0, # index 0 is black background
0, 0, 255, # index 1 is blue
255, 0, 0, # index 2 is red ])

im2 = Image.open("image2.png")
imP2L = im2.convert('L') # need a greyscale image to create a mask
mask = Image.eval(imP2L, lambda a: 255 if a == 0 else 0)
imP.paste(2, mask) # Paste the color of index 2 using image2 as a mask
imP.save('out3.png', transparency = 0, optimize = 1) # Save and set index 0 as transparent

关于 python PIL : Create indexed color image with transparent background,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7733364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com