魔杖:如何组装每帧的透明gif / clear背景

时间:2016-04-25 11:35:55

标签: python image imagemagick gif wand

所以我有一系列透明的png并将它们附加到一个新的Image()

with Image() as new_gif:
    for img_path in input_images:
        with Image(filename=img_path) as inimg:
            # create temp image with transparent background to composite
            with Image(width=inimg.width, height=inimg.height, background=None) as new_img:
                new_img.composite(inimg, 0, 0)
                new_gif.sequence.append(new_img)
    new_gif.save(filename=output_path)

遗憾的是,附加新图像时背景未被“清除”。他们也会在那里有最后一张照片:

enter image description here

但我如何清除背景?我虽然通过先前合成一个新的图像来做到这一点.`:| HALP !!

我看到命令行ImageMagick有一个similar但是魔杖没有这样的东西。到目前为止,我必须使用合适的背景颜色进行解决。

1 个答案:

答案 0 :(得分:2)

如果没有看到源图像,我可以假设-set dispose background是需要的。对于,您需要调用wand.api.library.MagickSetOption方法。

from wand.image import Image
from wand.api import library

with Image() as new_gif:
    # Tell new gif how to manage background
    library.MagickSetOption(new_gif.wand, 'dispose', 'background')
    for img_path in input_images:
        library.MagickReadImage(new_gif.wand, img_path)
    new_gif.save(filename=output_path)

Assembled transparent GIF

或者......

您可以扩展魔杖以管理背景处理行为。这种方法可以为您提供以编程方式更改/生成每个帧的好处。但是不利的方面还包括的更多工作。例如。

import ctypes
from wand.image import Image
from wand.api import library

# Tell python about library method
library.MagickSetImageDispose.argtypes = [ctypes.c_void_p, # Wand
                                          ctypes.c_int]    # DisposeType
# Define enum DisposeType
BackgroundDispose = ctypes.c_int(2)
with Image() as new_gif:
    for img_path in input_images:
        with Image(filename=img_path) as inimg:
            # create temp image with transparent background to composite
            with Image(width=inimg.width, height=inimg.height, background=None) as new_img:
                new_img.composite(inimg, 0, 0)
                library.MagickSetImageDispose(new_img.wand, BackgroundDispose)
                new_gif.sequence.append(new_img)
    # Also rebuild loop and delay as ``new_gif`` never had this defined.
    new_gif.save(filename=output_path)

With MagickSetImageDispose< - 仍然需要延迟纠正