gpt4 book ai didi

python - 如何将PNG图像转换为透明GIF?

转载 作者:行者123 更新时间:2023-12-02 18:53:36 28 4
gpt4 key购买 nike

我正在尝试将具有透明背景的 PNG 图像列表转换为 GIF,同时保持背景透明度。我找到了这段代码,并对其进行了调整:

import os
from PIL import Image

# Create the frames
frames = []

path = "directory/to/my/png/images"
for frame in os.listdir(path):
new_frame = Image.open(path + "/" + frame)
frames.append(new_frame)

# Save into a GIF file
frames[0].save(path + "/../output/animation.gif", format='GIF',
append_images=frames[1:],
save_all=True,
duration=41, loop=1, transparency=0)

它正在打开文件夹中的所有 PNG 图像,并将它们导出为 GIF,但背景是黑色的。我看过 PIL documentation , 但我似乎不明白 transparency 参数是如何工作的,或者我认为我用错了。

最佳答案

首先,the GIF format does not support alpha-channel transparency like PNG does. You can only select one out of the 256 possible colors in a GIF to be transparent .因此,您也不会获得任何平滑的透明度,像素要么完全透明,要么完全不透明。

处理具有 modeImage 对象时RGBA,尝试在保存之前将所有图像转换为模式PA。也许,这有助于自动

假设我们有以下三张图片:

Red

Green

Blue

您的最小化代码如下所示:

from PIL import Image

frames = [Image.open('red.png'), Image.open('green.png'), Image.open('blue.png')]

frames[0].save('test.gif', format='GIF',
append_images=frames[1:],
save_all=True,
duration=200, loop=0, transparency=0)

生成的 GIF 实际上并没有反射(reflect)单个 PNG 的透明度,GIF 已完全损坏:

Corrupted output

将转换添加到模式 PA,代码可能如下所示:

from PIL import Image

frames = [Image.open('red.png'), Image.open('green.png'), Image.open('blue.png')]

frames = [frame.convert('PA') for frame in frames]

frames[0].save('test.gif', format='GIF',
append_images=frames[1:],
save_all=True,
duration=200, loop=0, transparency=0)

而且,结果很好,保持了透明度:

Proper output

我不知道这条路线是否适用于任意 PNG,但值得用您的图像进行测试,不是吗?如果这不起作用,您需要提供一些输入图像以供进一步测试。

最终的方法可能是用某种颜色替换 PNG 中的所有透明像素,比如纯黄色。稍后保存 GIF 时,您需要确保所有图像的调色板都将纯黄色存储在同一索引处,然后最后将 transparency 设置为该索引。

----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.16299-SP0
Python: 3.9.1
Pillow: 8.1.0
----------------------------------------

关于python - 如何将PNG图像转换为透明GIF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66452964/

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