将非透明图像转换为透明gif图像PIL

时间:2020-05-21 01:24:59

标签: python image python-imaging-library transparency

是否可以使用PIL将非透明的png文件转换为透明的gif文件?

我的乌龟图形游戏需要它。我似乎只能透明化png文件,而不是gif文件。

谢谢!

1 个答案:

答案 0 :(得分:3)

至少对我来说,这不应该怎么做!对于不存在的问题,这可能是不必要的解决方法,因为我对PIL在内部的工作方式一无所知。

无论如何,我使用以下输入图像将其弄乱了足够长的时间:

enter image description here

#!/usr/bin/env python3

from PIL import Image, ImageDraw, ImageOps

# Open PNG image and ensure no alpha channel
im = Image.open('start.png').convert('RGB')

# Draw alpha layer - black square with white circle
alpha = Image.new('L', (100,100), 0)
ImageDraw.Draw(alpha).ellipse((10,10,90,90), fill=255)

# Add our lovely new alpha layer to image
im.putalpha(alpha)

# Save result as PNG and GIF
im.save('result.png')
im.save('unhappy.gif')

当我到达这里时,PNG可用,GIF为“不快乐” 。

下面的PNG:

enter image description here

“不开心” 以下GIF:

enter image description here

这是我固定GIF的方法:

# Extract the alpha channel
alpha = im.split()[3]

# Palettize original image leaving last colour free for transparency index
im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)

# Put 255 everywhere in image where we want transparency
im.paste(255, ImageOps.invert(alpha))
im.save('result.gif', transparency=255)

enter image description here

关键字:Python,图像处理,PIL,Pillow,GIF,透明度,Alpha,保留,透明索引。