简体   繁体   English

Python PIL:使用透明背景创建索引的彩色图像

[英]Python PIL: Create indexed color image with transparent background

I wonder how I could create a image with a transparent background and only 2 indexed colours (red and blue) to minimise the file size? 我想知道如何创建一个透明背景的图像,只有2种索引颜色(红色和蓝色)来最小化文件大小?

More specifically I have two black and white images that I want to convert, one to transparent and blue and the other to transparent and red. 更具体地说,我有两个我要转换的黑白图像,一个是透明和蓝色,另一个是透明和红色。 Then I want to merge those 2 images. 然后我想合并这两个图像。 I could do that with a regular RGBA image, but I really want the colour to be indexed to minimise the file size. 我可以使用常规的RGBA图像来做到这一点,但我真的希望将颜色编入索引以最小化文件大小。

Ideally with PIL, but other Python library could also work. 理想情况下使用PIL,但其他Python库也可以工作。

So I managed to do it, using "palette" image type, but the resulting file is not as small as I expected... Here's my code in case its useful for someone else, or if someone can improve on it. 所以我设法使用“调色板”图像类型,但生成的文件并不像我预期的那么小...这是我的代码,以防其他人有用,或者如果有人可以改进它。

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

Once you merge the two images, you won't have two colors any more - the colors will combine based on the transparency of each one at every pixel location. 合并两个图像后,您将不再有两种颜色 - 颜色将根据每个像素位置的每个颜色的透明度进行组合。 Worst case, you will have 256*256=65536 colors, which can't be indexed and wouldn't compress well if you did. 最坏的情况是,你将拥有256 * 256 = 65536种颜色,这些颜色无法编入索引,如果你这样做也不能很好地压缩。

I would suggest saving as a PNG and let the lossless compression do its best. 我建议保存为PNG,让无损压缩尽力而为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM