动画 GIF 仅在其第一帧透明 (Python PIL) [英] Animated GIFs are only transparent on their first frame (Python PIL)

查看:30
本文介绍了动画 GIF 仅在其第一帧透明 (Python PIL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码从两个图像创建一个 GIF:

# GIF 始终是调色板图像,因此无论如何它们都会在以后进行转换im1 = PIL.Image.open('grin-emoji-by-twitter-rgba.png').convert('P')im2 = PIL.Image.open('grin-emoji-by-twitter-rgba-2.png').convert('P')im1.save('output.gif', save_all=True, append_images=[im2, im1, im2], loop=0, duration=200, 透明度=255)

然而结果却出人意料地错误.第一帧很好,但后续帧在更新区域周围包含一个黑色矩形而不是透明度:

在我看来,错误如下:在第一张图像上,我们将索引 255 指定为完全透明颜色的索引.然而,save 函数似乎只在第一帧上将索引 255 转换为透明度,但在所有其他帧上跳过此步骤.

有什么办法可以绕过吗?

解决方案

作为我其他答案的替代方案,您也可以

这里声称这得到了修复在新版本的枕头中!(我认为 8.1.2+)

The following code creates a GIF from two images:

# GIFs are always palette images so they would be converted later anyway
im1 = PIL.Image.open('grin-emoji-by-twitter-rgba.png').convert('P')
im2 = PIL.Image.open('grin-emoji-by-twitter-rgba-2.png').convert('P')

im1.save('output.gif', save_all=True, append_images=[im2, im1, im2], loop=0, duration=200, transparency=255)

However the result is unexpectedly wrong. The first frame is fine, but subsequent frames contain a black rectangle around the updating region instead of transparency:

In my opinion the error is as follows: On the first image we specify the index 255 to be the index for completely transparent color. However the save function only seems to convert index 255 to transparency on the first frame, but skips this step on all other frames.

Is there any way to circumvent this?

解决方案

As an alternative to my other answer, you can also just set the disposal value to 2:

im1.save('output.gif', save_all=True, append_images=[im2, im1, im2], 
         loop=0, duration=200, transparency=255, disposal=2)

Note that unlike my other answer this does not work 100% of the time, as the transparency channel can jump around to other indexes. :-/ This only seems to happen in longer GIFs with many colors in them however.

Left: This answer, Right: Other answer with manual alignment

Edit: Here it's claimed this got fixed in newer versions of pillow! (I think 8.1.2+)

这篇关于动画 GIF 仅在其第一帧透明 (Python PIL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆