简体   繁体   English

如何使用Wand在Python中创建动画gif?

[英]How do I create an animated gif in Python using Wand?

The instructions are simple enough in the Wand docs for reading a sequenced image (eg animated gif, icon file, etc.): Wand文档中的说明很简单,可以读取有序图像(例如GIF动画,图标文件等):

>>> from wand.image import Image
>>> with Image(filename='sequence-animation.gif') as image:
...     len(image.sequence)

...but I'm not sure how to create one. ...但我不确定如何创建一个。

In Ruby this is easy using RMagick , since you have ImageList s. 在Ruby中,使用RMagick很容易,因为你有ImageList (see my gist for an example.) (请参阅我的要点 。)

I tried creating an Image (as the "container") and instantiating each SingleImage with an image path, but I'm pretty sure that's wrong, especially since the constructor documentation for SingleImage doesn't look for use by the end-user. 我尝试创建一个Image (作为“容器”)并使用图像路径实例化每个SingleImage ,但我很确定这是错误的,特别是因为SingleImage的构造函数文档不寻求最终用户使用。

I also tried creating a wand.sequence.Sequence and going from that angle, but hit a dead-end as well. 我也试过创建一个wand.sequence.Sequence并从那个角度出发,但也打了一个死胡同。 I feel very lost. 我感到很失落。

The best examples are located in the unit-tests shipped with the code. 最好的示例位于代码附带的单元测试中。 wand/tests/sequence_test.py for example. wand/tests/sequence_test.py例如。

For creating an animated gif with wand, remember to load the image into the sequence, and then set the additional delay/optimize handling after all frames are loaded. 要使用魔杖创建动画gif,请记住将图像加载到序列中,然后在加载所有帧后设置附加延迟/优化处理。

from wand.image import Image

with Image() as wand:
    # Add new frames into sequance
    with Image(filename='1.png') as one:
        wand.sequence.append(one)
    with Image(filename='2.png') as two:
        wand.sequence.append(two)
    with Image(filename='3.png') as three:
        wand.sequence.append(three)
    # Create progressive delay for each frame
    for cursor in range(3):
        with wand.sequence[cursor] as frame:
            frame.delay = 10 * (cursor + 1)
    # Set layer type
    wand.type = 'optimize'
    wand.save(filename='animated.gif')

输出animated.gif

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM