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

标签 python image image-processing plone python-imaging-library

我想知道是否可以使用 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/

相关文章:

python - 在Django中,如何将manage.py测试的结果放入文件中?

python - 干净地退出 python3 函数而不离开 repl

python - 如何使用 MongoDB 2.4 对 2d 或 2dsphere 索引字段使用常规查询

Java JFrame pack() 问题

PHP 发出请求检查客户端是否可以通过 ip 访问

javascript - 如何将 .createElement ("image") 也制作成链接

c++ - OpenCV C++ image.reshape 无法正常工作?

ios - 拍照,在相机中选择完整模式或方形模式

c++ - 将 16 位灰度 DICOM 图像转换为 8 位 : the correct procedure

c++ - 将输出帧保存为图像文件 CUDA 解码器