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

2024-09-28 21:54:53 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用PIL将非透明PNG文件转换为透明GIF文件

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


Tags: 文件图形游戏pilpnggif海龟透明化
1条回答
网友
1楼 · 发布于 2024-09-28 21:54:53

至少对我来说,你该怎么做还不清楚!对于一个不存在的问题,这可能是一个不必要的解决方法,因为我不知道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、枕头、GIF、透明度、alpha、保留、透明索引

相关问题 更多 >