gpt4 book ai didi

python - 如何在 PIL 中缩放动画 GIF 图像并保留动画

转载 作者:太空狗 更新时间:2023-10-29 22:16:44 26 4
gpt4 key购买 nike

我想知道是否可以使用 PIL 缩放动画 GIF 图像。特别是 Plone 的原型(prototype) ImageField 目前丢失了使用其缩放方法缩放的图像的动画:

def scale(self, data, w, h, default_format = 'PNG'):
""" scale image (with material from ImageTag_Hotfix)"""
#make sure we have valid int's
size = int(w), int(h)

original_file=StringIO(data)
image = PIL.Image.open(original_file)
# consider image mode when scaling
# source images can be mode '1','L,','P','RGB(A)'
# convert to greyscale or RGBA before scaling
# preserve palletted mode (but not pallette)
# for palletted-only image formats, e.g. GIF
# PNG compression is OK for RGBA thumbnails
original_mode = image.mode
img_format = image.format and image.format or default_format
if original_mode == '1':
image = image.convert('L')
elif original_mode == 'P':
image = image.convert('RGBA')
image.thumbnail(size, self.pil_resize_algo)
# decided to only preserve palletted mode
# for GIF, could also use image.format in ('GIF','PNG')
if original_mode == 'P' and img_format == 'GIF':
image = image.convert('P')
thumbnail_file = StringIO()
# quality parameter doesn't affect lossless formats
image.save(thumbnail_file, img_format, quality=self.pil_quality)
thumbnail_file.seek(0)
return thumbnail_file, img_format.lower()

我知道如何识别动画 GIF:以下计算结果为 True image.format == 'GIF' 和 image.seek(image.tell()+1)。我试过不转换为 RGBA 模式,但那行不通。

背景:在我们的 Plone 实例上,我们修改了默认图像类型以设置其图像字段的 original_size 属性,以强制所有图像以适当的质量设置缩放。这对 jpeg 非常有用,但意味着我们目前无法上传动画 GIF

最佳答案

您可以使用 images2gif.py 读取 gif 文件,然后独立缩放每一帧。 images2gif 将允许您使用一系列图像编写动画 gif。

我在互联网上找到的 images2gif.py 没有处理透明度,所以我修复了它。你可以在这里找到: https://bitbucket.org/bench/images2gif.py

关于python - 如何在 PIL 中缩放动画 GIF 图像并保留动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9128811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com