.NET - 使用GifBitmapEncoder创建循环.gif

Pau*_*ies 5 c# vb.net wpf animated-gif

我正在尝试编写一些代码来使用GifBitmapEncoder从WPF应用程序导出动画.gif文件.到目前为止我的工作正常,但当我查看结果.gif它只运行一次然后停止 - 我想让它无限循环.

我发现了之前类似的问题:

使用BitmapEncoder生成时,如何在循环中进行GIF重复

但是,他正在使用Windows.Graphics.Imaging中的BitmapEncoder而不是Windows.Media.Imaging版本,这似乎有点不同.尽管如此,这给了我一个方向,经过一番谷歌搜索后我想出了这个:

Dim encoder As New GifBitmapEncoder
Dim metaData As New BitmapMetadata("gif")
metaData.SetQuery("/appext/Application", System.Text.Encoding.ASCII.GetBytes("NETSCAPE2.0"))
metaData.SetQuery("/appext/Data", New Byte() {3, 1, 0, 0, 0})

'The following line throws the exception "The designated BitmapEncoder does not support global metadata.":
'encoder.Metadata = metaData

If DrawingManager.Instance.SelectedFacing IsNot Nothing Then
   For Each Frame As Frame In DrawingManager.Instance.SelectedFacing.Frames
       Dim bmpFrame As BitmapFrame = BitmapFrame.Create(Frame.CombinedImage, Nothing, metaData, Nothing)
       encoder.Frames.Add(bmpFrame)
   Next
End If

Dim fs As New FileStream(newFileName, FileMode.Create)
encoder.Save(fs)
fs.Close()
Run Code Online (Sandbox Code Playgroud)

最初我尝试将元数据直接添加到编码器(如上面代码中的注释掉的行),但是在运行时抛出异常"指定的BitmapEncoder不支持全局元数据".我可以将我的元数据附加到每个帧,但是虽然不会崩溃,但结果.gif也不会循环(我希望循环元数据无论如何都需要是全局的).

有人可以提供任何建议吗?

Jar*_*red 6

在研究了这篇文章并参考了 GIF 文件的原始字节后,我终于让它起作用了。如果你想自己这样做,你可以像这样使用PowerShell以十六进制格式获取字节......

$bytes = [System.IO.File]::ReadAllBytes("C:\Users\Me\Desktop\SomeGif.gif")
[System.BitConverter]::ToString($bytes)
Run Code Online (Sandbox Code Playgroud)

GifBitmapEncoder 似乎编写标题、逻辑屏幕描述符,然后是图形控制扩展。缺少“NETSCAPE2.0”扩展名。在从其他来源的GIF环,缺少的扩展总是图形控制扩展前右侧出现。

所以我只是在第 13 个字节之后插入字节,因为前两个部分总是这么长。

        // After adding all frames to gifEncoder (the GifBitmapEncoder)...
        using (var ms = new MemoryStream())
        {
            gifEncoder.Save(ms);
            var fileBytes = ms.ToArray();
            // This is the NETSCAPE2.0 Application Extension.
            var applicationExtension = new byte[] { 33, 255, 11, 78, 69, 84, 83, 67, 65, 80, 69, 50, 46, 48, 3, 1, 0, 0, 0 };
            var newBytes = new List<byte>();
            newBytes.AddRange(fileBytes.Take(13));
            newBytes.AddRange(applicationExtension);
            newBytes.AddRange(fileBytes.Skip(13));
            File.WriteAllBytes(saveFile, newBytes.ToArray());
        }
Run Code Online (Sandbox Code Playgroud)