我正在尝试制作一个堡垒之夜图像卡生成器。我想让它在顶层制作皮肤,在底部制作 bg aka gif。这是到目前为止的代码。
import os
from PIL import Image
filename = 'CID_613_Athena_Commando_M_Columbus_7Y4QE.png'
skin = Image.open(filename, 'r')
filename1 = 'bg.gif'
bg = Image.open(filename1, 'r')
text_img = Image.new('RGBA', (512,512), (0, 0, 0, 0))
text_img.paste(bg, (0,0))
text_img.paste(skin, (0,0), mask=skin)
text_img.save("out.gif", format="gif")
CID_613_Athena_Commando_M_Columbus_7Y4QE.png 是:https://imgur.com/Seu1Tx6.png背景:
https://i.imgur.com/fCewt2H.gif
这是输出:
https://i.imgur.com/4yJMp3M.png
我希望它像动画背景一样。与现在不同
最佳答案
您需要迭代 gif 中的所有帧并将前景图像粘贴到所有帧中。
如果图像是动画的( bg.is_animated
),您可以在 bg.n_frames
中获取帧数.
对于动画图像(不仅仅是 gif),Pillow 包含一个 seek(frame_number)
将动画转发到您要使用的帧的方法。
代码将类似于:
if bg.is_animated:
frames = []
for num in range(bg.n_frames):
bg.seek(num)
text_img = Image.new('RGBA', (512,512), (0, 0, 0, 0))
text_img.paste(bg, (0,0))
text_img.paste(skin, (0,0), mask=skin)
frames.append(text_img)
frames[0].save('out.gif',
save_all=True,
append_images=frames[1:],
duration=100,
loop=0)
警告! Pillow 没有优化 gif 输出。也许您需要使用其他工具进一步压缩它们。如果你只需要一个动画,可以考虑保存到 WEBP file format只需更改来自
.gif
的扩展名至 .webp
在 save()
方法。您将获得一个较小的文件,所有浏览器都支持它,并且具有渐变背景的图像质量更好(由于 GIF 8 位调色板,不会有 strip 效应)。
关于python - 带有 Gif 背景的 PIL PNG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65069182/