【发布时间】: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