簡體   English   中英

如何將PNG圖像轉換為透明的GIF?

[英]How to convert PNG images to a transparent GIF?

我正在嘗試將具有透明背景的 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 文檔,但我似乎不明白transparency參數是如何工作的,或者我認為我用錯了。

首先, GIF 格式不像 PNG 那樣支持 alpha 通道透明度。 您只能在 GIF 中的 256 個可能的 colors 中的一個 select 是透明的 因此,您也不會得到任何平滑的透明度,像素要么是完全透明的,要么是不透明的。

在處理具有RGBA 模式Image對象時,請嘗試在保存之前將所有圖像轉換為PA模式。 也許,這會自動幫助。

假設我們有以下三個圖像:

紅色的

綠色的

藍色的

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

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 實際上並不反映單個 PNG 的透明度,GIF 已完全損壞:

損壞的輸出

將轉換添加到模式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)

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

適當的輸出

我不知道,該路線是否適用於任意 PNG,但值得用您的圖像進行測試,不是嗎? 如果這不起作用,您需要提供一些輸入圖像以進行進一步測試。

最后一種方法可能是用某種顏色替換 PNG 中的所有透明像素,比如說純黃色。 稍后保存 GIF 時,您需要確保所有圖像的調色板都將純黃色存儲在同一索引處,然后最后為該索引設置transparency

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM