How do I convert a collection of canvases into an animated gif in WinRT?

I have a javascript Windows 8 application, and I need to convert a bunch of canvases into an animated gif. Here's what I have so far:

I can convert one canvas to a base64 encoded png like this (in javascript):

var base64png = myCanvas.toDataURL()

I can then convert this encoded image into an array of bytes (in ac# class library):

private byte[] GetBytesFromBase64(string base64)
{
    string data = base64.Split(',')[1]; // get everything after comma
    return Convert.FromBase64String(data);
}

I can then use these bytes to create a gif, and save it on the disk (again, in the c# class library):

public async void ConvertToGif(string image)
    {
        // Note: The following line includes methods not shown in the question, but they work
        IRandomAccessStream stream = await ConvertToRandomAccessStream(
                                           ConvertToMemoryStream(
                                           GetBytesFromBase64(image)));

        var decoder = await BitmapDecoder.CreateAsync(stream);
        var pixels = await decoder.GetPixelDataAsync();

        var file = await KnownFolders.PicturesLibrary.CreateFileAsync("test.gif", CreationCollisionOption.ReplaceExisting);
        var outStream = await file.OpenAsync(FileAccessMode.ReadWrite);

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

        encoder.SetPixelData(
            decoder.BitmapPixelFormat, 
            BitmapAlphaMode.Ignore,
            decoder.PixelWidth, 
            decoder.PixelHeight,
            decoder.DpiX, 
            decoder.DpiY,
            ReplaceTransparentWithWhite(pixels));


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

This, however, only saves one canvas as one gif. How do I add frames to the gif? There is a GifEncoder class in the System.Media.Imaging namespace, but it seems to not be included in the WinRT .Net framework. Any help would be appreciated.


I'd suggest you build it your self as you've already got code to convert a Canvas to a single GIF file. Basically, an animated GIF is just a series of GIF files within a container GIF file. While the specification is a bit wordy, you should find this example from the .NET 1.1 days very useful.

Although the standard file format didn't directly allow animation, through "extensions" animations are allowed. The details are well documented on this Wikipedia page.

The core of what you'll need to do is write out a custom header block for the file, and then the individual streams for each animated GIF frame.

链接地址: http://www.djcxy.com/p/84142.html

上一篇: Win 7上的VS2008无法写入资源文件。 参数无效

下一篇: 如何在WinRT中将一组画布转换为动画GIF?