【问题标题】:Place GIF in front of a PNG with Python PIL library使用 Python PIL 库将 GIF 放在 PNG 前面
【发布时间】:2022-01-01 20:42:56
【问题描述】:

我正在尝试使用 Python 3 和 PIL 库将 PNG 文件与 GIF 文件合并。

我想将 PNG 文件放在后台,将 GIF 文件放在前台。我可以做相反的事情,将 GIF 文件放在后台,将 PNG 文件放在前台。感谢在这里回答的人:How to merge a image and a Gif in Python Pillow 但是,当我尝试做我需要的事情时,我只得到透明的 GIF,而图像背景上没有 PNG。

我使用这个透明的 GIF:https://i.imgur.com/wOolptS.gif

我使用这个 PNG:https://i.imgur.com/kfnQGYP.png

我得到这个输出:https://i.imgur.com/rtWYKVn.gif

我的代码:

from PIL import Image

foreground = Image.open('image.gif')
background = Image.open('image.png').convert("RGBA")
img_w, img_h = background.size
foreground_w, foreground_w = foreground.size
if foreground.is_animated:
    frames = []
    for num in range(foreground.n_frames):
        foreground.seek(num)
        layer = Image.new('RGBA', (foreground_w, foreground_w), (0, 0, 0, 0)).resize((img_w, img_h))
        layer.paste(background, (0,0), mask=background)
        layer.paste(foreground.resize((img_w, img_h)), (0,0))
        frames.append(layer)
        frames[0].save('1.gif',
                    save_all=True,
                    append_images=frames[1:],
                    duration=100,loop=0)

【问题讨论】:

    标签: python-3.x python-imaging-library png gif


    【解决方案1】:

    即使您称其为“透明 GIF”,其中也没有一个透明像素。调色板包含 16 种颜色,但每帧的 99.99% 由前 2 个调色板条目组成。前 3 帧使用 4 种颜色,第 4 帧使用 6。

    如果 GIF 包含适当的透明度,简单的over = foreground.convert('RGBA') 将为您提供具有 alpha 透明度的图像。

    【讨论】:

      猜你喜欢
      • 2021-03-12
      • 2011-10-05
      • 2012-01-12
      • 2016-02-10
      • 2021-08-09
      • 2014-03-17
      • 2011-09-15
      • 2021-09-01
      • 2012-06-12
      相关资源
      最近更新 更多