2012-02-03 44 views
6

我想知道是否可以使用PIL缩放动画GIF图像。特别是Plone的原型的ImageField目前失去了图像上的动画使用其规模缩小方法:如何在PIL中缩放动画GIF图像并保留动画

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' and image.seek(image.tell()+1)。我试过不转换到RGBA模式,但不起作用。

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

+0

缩放调色板图像可能会导致图像质量不可接受。 – 2012-02-03 15:09:29

回答

4

PIL对动画GIF有一些有限的支持,但正如前面所说的那样,它有限,而且您必须在非常低的水平上处理它。

我建议尝试一些其他缩放图像比PIL方法,如果你想处理动画gif的。可能最直接的方法是使用带有subprocess.Popen的off-process ImageMagick - (甚至在这个时候,我只是猜测ImageMagick“用动画GIF做了正确的事情”) -

An选项是有一个“图像处理服务器”,另一个Python脚本,除了你的zope安装,它将接收缩放图像的请求 - 可能用xmlrpc调用 - 你可以将它作为GIMP插件构建并使用GIMP for缩放GIF的。

另一种选择是让事情保持原样,并使用动画GIF的“静止画面”来显示原始图像,并在原始图像上显示适合动画的原始图像。 (或者,也许只是要求动画的gif已经以适当的尺寸提交了)

+2

谢谢。我调整了代码,以便它不会尝试缩放动画GIF图像,如果源图像不大于比例尺。参见http://dev.plone.org/ticket/12488 – scarba05 2012-02-03 16:04:00

+1

我对PIL进行了进一步的研究 - 它确实支持阅读多帧gif,但不支持创建或编写它们。 – jsbueno 2012-02-04 02:55:51

7

您可以使用images2gif.py来读取gif并比单独缩放每个帧。 images2gif将允许您用一系列图像编写动画gif。

我在互联网上找到的images2gif.py没有处理透明度,所以我解决了这个问题。你可以发现,这里: https://bitbucket.org/bench/images2gif.py