Search code examples
c#animationimagemagickimagemagick.net

How do I use Magick.NET to convert an animated webp image to an animated gif?


GDI+ and System.Drawing have no support for WebP images. To handle them in my C# Windows desktop app, I'm using Magick.NET to convert them to Gif images, which are supported. This works well, unless the WebP image is animated. The code I'm using to test animated image conversions is as follows:

    public void TestConvertImageType() {
        using (var animatedWebP = new MagickImage("animated.webp")) {
            animatedWebP.Write("animated-generated.gif", MagickFormat.Gif);
        }
        using (var animatedGif = new MagickImage("animated.gif")) {
            animatedGif.Write("animated-generated.webp", MagickFormat.WebP);
        }
    }

Both animated.webp and animated.gif will play if dragged into a chrome browser. Neither generated image will play, however. In chrome, they simply display the first frame of the animated source image.

Using the command line version of ImageMagick, I can convert animated.webp and animated.gif to playable images with the following script:

magick animated.webp animated-generated.gif
magick animated.gif animated-generated.webp

So I know that conversion of animated images is supported by ImageMagick.

My installed version of Magick.NET is Magick.NET-Q8-AnyCPU version 8.5.0
My installed version of ImageMagick is ImageMagick-7.1.0-Q8
My C# app is using .NET Framework 4.8

Can anyone tell me what my C# app needs to do to generate playable animated gif's from animated webp's?


Solution

  • A MagickImage is only a single image. When an animated image is read this will be the first frame. If you want to read all the frames you will need to read the files with a MagickImageCollection instead.

    public void TestConvertImageType() {
        using (var animatedWebP = new MagickImageColection("animated.webp")) {
            animatedWebP.Write("animated-generated.gif", MagickFormat.Gif);
        }
        using (var animatedGif = new MagickImageColection("animated.gif")) {
            animatedGif.Write("animated-generated.webp", MagickFormat.WebP);
        }
    }
    

    And you don't need to also install ImageMagick on your machine. The ImageMagick library comes with the Magick.NET library.