Search code examples
pythonimagemagickwand

Generating gif with Wand independently of filename extension


Is there a way to force Wand to save image in the .gif animated format, no matter what is passed as filename to Image.save()?

with Image() as gif:
    gif.sequence = frames  # 10 images
    gif.format = 'gif'
    gif.save(filename='image.jpg')

This code creates 10 numerated jpg-s but I expected it to create a single file (image.jpg which is acutally a gif). The documentation says that the desired format can be set in the format field.

Why the extension in filename gets a higher priority than Image.format?

The version of Wand in question is 0.5.8.

UPD: Just to clarify, the discrepancy in my question is intentional. I'm interested in the case where .format is set to "gif" but the filename in .save() is passed with the incorrect extension ".jpg", and I'm wondering if there is a way to produce a single gif in this case. If the filename extension is set to ".gif", everything works fine.


Solution

  • This works fine for me with Wand 0.5.7 and Imagemagick 6.9.10.91 Q16 Mac OSX

    from wand.image import Image
    
    with Image(filename='desktop5_anim.gif') as img:
        img.format = 'gif'
        img.save(filename='desktop5_anim2.gif')
    


    This also works to create an animation.

    from wand.image import Image
    
    with Image(filename='lena.jpg') as imgA:
        with Image(filename='zelda1.jpg') as imgB:
            imgA.sequence.append(imgB)
            for frame in imgA.sequence:
                frame.delay = 50
        imgA.loop = 0
        imgA.format = 'gif'
        imgA.save(filename='lena_zelda_anim.gif')
    


    If you intent to keep the '.jpg' suffix in the filename, the output file will actually be a GIF animation regardless of suffix, if you preface the filename with GIF: as gif.save(filename='GIF:image.jpg'). However, I would really not recommend that as some tools only use the suffix to decide what format the file would be. So they will give an error when trying to read the GIF animation as a JPG.

    (Thanks to Eric McConville for the pointers on how to add the delay and on the GIF: preface).