python - PIL Gif 生成未按预期工作
问题描述
我正在尝试做的事情:由于我对使用 PIL 库生成图像仍然很陌生,因此我决定尝试将图像放在 gif 之上。我可以使用的适当教程或参考资料并不多。
出了什么问题:通常不会生成 gif。这会给出IndexError: bytearray index out of range
我不知道如何解决的错误。但是,有时会生成gif,但会出现一些错误。我在下面包含了其中一些 GIF。
代码:
@client.command()
async def salt(ctx, user:discord.Member=None):
if user == None:
user = ctx.author
animated_gif = Image.open("salty.gif")
response = requests.get(user.avatar_url)
background = Image.open(BytesIO(response.content))
all_frames = []
# background = background.resize((500, 500))
for gif_frame in ImageSequence.Iterator(animated_gif):
# duplicate background image
new_frame = background.copy()
# need to convert from `P` to `RGBA` to use it in `paste()` as mask for transparency
gif_frame = gif_frame.convert('RGBA')
# paste on background using mask to get transparency
new_frame.paste(gif_frame, mask=gif_frame)
all_frames.append(new_frame)
# save all frames as animated gif
all_frames[0].save("image.gif", save_all=True, append_images=all_frames[1:], duration=50, loop=0)
这是我正在使用的 gif:
解决方案
不幸的是,PIL 对动画 GIF 的支持是错误的,而且很难使用。您显示的图像受到与背景图层共享调色板信息的图层的影响,因此它们的某些颜色会失真。
我不知道是否有办法使用 PIL 控制每一帧的调色板信息。
如果您想使用 Python 以编程方式生成 GIF,我现在建议您使用 GIMP 图像编辑器 - 在那里您可以使用程序以交互方式构建图像,或者使用 Python 控制台以编程方式构建图像,然后调用“另存为 gif”功能 ( pdb.file_gif_save2
)。
(我将看看 PIL 的确切功能,并检查我是否可以扩展正确处理透明度的答案 - 否则,GIMP 是要走的路)
推荐阅读
- android - Android 错误:多个库的包名称为“android.support.graphics.drawable”
- sql - 图书馆数据库
- numpy - 如何获取任何图像的文件流的 Numpy 数组
- javascript - 三.js计算STL文件网格体积
- three.js - AR.js 尝试将场景同步到指南针北方
- c++ - 获取浏览器进程 ID,然后在 C++ 程序中使用它
- php - php文件功能不适用于长csv文件
- assembly - 8086 - 在 8086 微处理器中声明数组后的汇编、mov 操作
- c# - 如何使用最速下降法 C# 获得 2 个非线性函数/方程系统的目标来解决它?
- keyboard - Flutter中动态更新keyboardType