How to create an animated GIF with WinRT

Why using GIF files?

For one of my project (Flipflop: https://apps.microsoft.com/windows/app/flipflop/99c01512-fe4f-4d1a-872e-eb9fd6638ff4), I needed to create an animated GIF based on a group of HTML5 canvas.

intro0


A GIF produced by Flipflop

The main goal of Flipflop is to allow users to create an animated flipbook. And to allow them to share it, I finally found that GIF files were a great deal.

Creating a GIF using WIC components

So I propose you to share the small class that I used to achieve this goal: GifMaker.

To work this class requires you to specify frames size and obviously all frames:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Graphics.Imaging;
using Windows.Storage;

namespace Utilities
{
    public sealed class GifMaker
    {
        readonly List<byte[]> frames = new List<byte[]>();
        private readonly uint frameWidth;
        private readonly uint frameHeight;

        public GifMaker(uint width, uint height)
        {
            frameWidth = width;
            frameHeight = height;
        }

        public void AppendNewFrame([ReadOnlyArray]byte[] frame)
        {
            frames.Add(frame);
        }

 

This class mainly uses WIC or actually Windows.Graphics namespace. This namespace contains a class called BitmapEncoder that will allow us to generate files using specific encoders such as GifEncoder.

The point is that GIF files are composed of a list of frames. You just have to browse through them and send each of them to the encoder using GoToNextFrameAsync to register a new frame:

public IAsyncInfo GenerateAsync(StorageFile file)
{
    return AsyncInfo.Run(async ctx =>
        {
            var outStream = await file.OpenAsync(FileAccessMode.ReadWrite);

            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.GifEncoderId, outStream);

            for (int i = 0; i < frames.Count; i++)
            {
                var pixels = frames[i];
                encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Ignore,
                                     frameWidth, frameHeight,
                                     92.0, 92.0,
                                     pixels);

                if (i < frames.Count - 1)
                    await encoder.GoToNextFrameAsync();
            }

            await encoder.FlushAsync();
            outStream.Dispose();
        });
}

Easy, isn’t it ?

Adding delay between frames

To be complete, you also have to handle the delay between frames and for this point, I must admit it took me a long time to figure out how to do that.

The solution is handled by frame properties (encoder.BitmapProperties) and especially via the property named “/grctlext/Delay” (!!).

To the final code is like the following:

public IAsyncInfo GenerateAsync(StorageFile file, int delay)
{
    return AsyncInfo.Run(async ctx =>
        {
            var outStream = await file.OpenAsync(FileAccessMode.ReadWrite);

            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.GifEncoderId, outStream);

            for (int i = 0; i < frames.Count; i++)
            {
                var pixels = frames[i];
                encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Ignore,
                                     frameWidth, frameHeight,
                                     92.0, 92.0,
                                     pixels);

                if (i == 0)
                {
                    var properties = new BitmapPropertySet
                        {
                            {
                                "/grctlext/Delay",
                                new BitmapTypedValue(delay / 10, PropertyType.UInt16)
                            }
                        };

                    await encoder.BitmapProperties.SetPropertiesAsync(properties);
                }

                if (i < frames.Count - 1)
                    await encoder.GoToNextFrameAsync();
            }

            await encoder.FlushAsync();
            outStream.Dispose();
        });
}

 

Using it from other languages

For instance if you want to use it from JavaScript, you just have to do something like that:

var picker = new Windows.Storage.Pickers.FileSavePicker();
picker.fileTypeChoices.insert("Gif files", [".gif"]);

picker.pickSaveFileAsync().then(function(file) {
    if (!file) {
        return;
    }
    var gifMaker = new Utilities.GifMaker(800, 600);

    for (var commandsIndex = 0; commandsIndex < currentFlipflop.pages.length; commandsIndex++) {
        // This code is used to retrieve canvases bytes
        var bytes = Flipflop.Tools.GetBytesfromFlipflop(currentFlipflop.pages[commandsIndex],
            800, 600);

        gifMaker.appendNewFrame(bytes);
    }

    gifMaker.generateAsync(file, 200).done();
});

Obviously it works the same way from .NET!

intro2