如何在.NET中创建动画GIF

59

有人知道如何使用C#创建动画GIF吗?理想情况下,我希望对使用的颜色减少具有一定的控制。

使用ImageMagick(作为外部启动的进程)是最好的选择吗?


ImageMagick似乎仍然拥有最佳选项(抖动、颜色减少等)。建议的库和其他创建方法质量相当差。 - The dude
你尝试过最终解决方案了吗?还没有标记答案... - Kiquenet
8个回答

34

这个来自https://github.com/DataDink/Bumpkit的Gif动画创建器代码可以为每帧设置延迟:

使用.NET标准的Gif编码并添加动画头。

编辑:将代码改为类似于典型文件写入器的形式。

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading.Tasks;

/// <summary>
/// Creates a GIF using .Net GIF encoding and additional animation headers.
/// </summary>
public class GifWriter : IDisposable
{
    #region Fields
    const long SourceGlobalColorInfoPosition = 10,
        SourceImageBlockPosition = 789;

    readonly BinaryWriter _writer;
    bool _firstFrame = true;
    readonly object _syncLock = new object();
    #endregion

    /// <summary>
    /// Creates a new instance of GifWriter.
    /// </summary>
    /// <param name="OutStream">The <see cref="Stream"/> to output the Gif to.</param>
    /// <param name="DefaultFrameDelay">Default Delay between consecutive frames... FrameRate = 1000 / DefaultFrameDelay.</param>
    /// <param name="Repeat">No of times the Gif should repeat... -1 not to repeat, 0 to repeat indefinitely.</param>
    public GifWriter(Stream OutStream, int DefaultFrameDelay = 500, int Repeat = -1)
    {
        if (OutStream == null)
            throw new ArgumentNullException(nameof(OutStream));

        if (DefaultFrameDelay <= 0)
            throw new ArgumentOutOfRangeException(nameof(DefaultFrameDelay));

        if (Repeat < -1)
            throw new ArgumentOutOfRangeException(nameof(Repeat));

        _writer = new BinaryWriter(OutStream);
        this.DefaultFrameDelay = DefaultFrameDelay;
        this.Repeat = Repeat;
    }

    /// <summary>
    /// Creates a new instance of GifWriter.
    /// </summary>
    /// <param name="FileName">The path to the file to output the Gif to.</param>
    /// <param name="DefaultFrameDelay">Default Delay between consecutive frames... FrameRate = 1000 / DefaultFrameDelay.</param>
    /// <param name="Repeat">No of times the Gif should repeat... -1 not to repeat, 0 to repeat indefinitely.</param>
    public GifWriter(string FileName, int DefaultFrameDelay = 500, int Repeat = -1)
        : this(new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read), DefaultFrameDelay, Repeat) { }

    #region Properties
    /// <summary>
    /// Gets or Sets the Default Width of a Frame. Used when unspecified.
    /// </summary>
    public int DefaultWidth { get; set; }

    /// <summary>
    /// Gets or Sets the Default Height of a Frame. Used when unspecified.
    /// </summary>
    public int DefaultHeight { get; set; }

    /// <summary>
    /// Gets or Sets the Default Delay in Milliseconds.
    /// </summary>
    public int DefaultFrameDelay { get; set; }

    /// <summary>
    /// The Number of Times the Animation must repeat.
    /// -1 indicates no repeat. 0 indicates repeat indefinitely
    /// </summary>
    public int Repeat { get; }
    #endregion

    /// <summary>
    /// Adds a frame to this animation.
    /// </summary>
    /// <param name="Image">The image to add</param>
    /// <param name="Delay">Delay in Milliseconds between this and last frame... 0 = <see cref="DefaultFrameDelay"/></param>
    public void WriteFrame(Image Image, int Delay = 0)
    {
        lock (_syncLock)
            using (var gifStream = new MemoryStream())
            {
                Image.Save(gifStream, ImageFormat.Gif);

                // Steal the global color table info
                if (_firstFrame)
                    InitHeader(gifStream, _writer, Image.Width, Image.Height);

                WriteGraphicControlBlock(gifStream, _writer, Delay == 0 ? DefaultFrameDelay : Delay);
                WriteImageBlock(gifStream, _writer, !_firstFrame, 0, 0, Image.Width, Image.Height);
            }

        if (_firstFrame)
            _firstFrame = false;
    }

    #region Write
    void InitHeader(Stream SourceGif, BinaryWriter Writer, int Width, int Height)
    {
        // File Header
        Writer.Write("GIF".ToCharArray()); // File type
        Writer.Write("89a".ToCharArray()); // File Version

        Writer.Write((short)(DefaultWidth == 0 ? Width : DefaultWidth)); // Initial Logical Width
        Writer.Write((short)(DefaultHeight == 0 ? Height : DefaultHeight)); // Initial Logical Height

        SourceGif.Position = SourceGlobalColorInfoPosition;
        Writer.Write((byte)SourceGif.ReadByte()); // Global Color Table Info
        Writer.Write((byte)0); // Background Color Index
        Writer.Write((byte)0); // Pixel aspect ratio
        WriteColorTable(SourceGif, Writer);

        // App Extension Header for Repeating
        if (Repeat == -1)
            return;

        Writer.Write(unchecked((short)0xff21)); // Application Extension Block Identifier
        Writer.Write((byte)0x0b); // Application Block Size
        Writer.Write("NETSCAPE2.0".ToCharArray()); // Application Identifier
        Writer.Write((byte)3); // Application block length
        Writer.Write((byte)1);
        Writer.Write((short)Repeat); // Repeat count for images.
        Writer.Write((byte)0); // terminator
    }

    static void WriteColorTable(Stream SourceGif, BinaryWriter Writer)
    {
        SourceGif.Position = 13; // Locating the image color table
        var colorTable = new byte[768];
        SourceGif.Read(colorTable, 0, colorTable.Length);
        Writer.Write(colorTable, 0, colorTable.Length);
    }

    static void WriteGraphicControlBlock(Stream SourceGif, BinaryWriter Writer, int FrameDelay)
    {
        SourceGif.Position = 781; // Locating the source GCE
        var blockhead = new byte[8];
        SourceGif.Read(blockhead, 0, blockhead.Length); // Reading source GCE

        Writer.Write(unchecked((short)0xf921)); // Identifier
        Writer.Write((byte)0x04); // Block Size
        Writer.Write((byte)(blockhead[3] & 0xf7 | 0x08)); // Setting disposal flag
        Writer.Write((short)(FrameDelay / 10)); // Setting frame delay
        Writer.Write(blockhead[6]); // Transparent color index
        Writer.Write((byte)0); // Terminator
    }

    static void WriteImageBlock(Stream SourceGif, BinaryWriter Writer, bool IncludeColorTable, int X, int Y, int Width, int Height)
    {
        SourceGif.Position = SourceImageBlockPosition; // Locating the image block
        var header = new byte[11];
        SourceGif.Read(header, 0, header.Length);
        Writer.Write(header[0]); // Separator
        Writer.Write((short)X); // Position X
        Writer.Write((short)Y); // Position Y
        Writer.Write((short)Width); // Width
        Writer.Write((short)Height); // Height

        if (IncludeColorTable) // If first frame, use global color table - else use local
        {
            SourceGif.Position = SourceGlobalColorInfoPosition;
            Writer.Write((byte)(SourceGif.ReadByte() & 0x3f | 0x80)); // Enabling local color table
            WriteColorTable(SourceGif, Writer);
        }
        else Writer.Write((byte)(header[9] & 0x07 | 0x07)); // Disabling local color table

        Writer.Write(header[10]); // LZW Min Code Size

        // Read/Write image data
        SourceGif.Position = SourceImageBlockPosition + header.Length;

        var dataLength = SourceGif.ReadByte();
        while (dataLength > 0)
        {
            var imgData = new byte[dataLength];
            SourceGif.Read(imgData, 0, dataLength);

            Writer.Write((byte)dataLength);
            Writer.Write(imgData, 0, dataLength);
            dataLength = SourceGif.ReadByte();
        }

        Writer.Write((byte)0); // Terminator
    }
    #endregion

    /// <summary>
    /// Frees all resources used by this object.
    /// </summary>
    public void Dispose()
    {
        // Complete File
        _writer.Write((byte)0x3b); // File Trailer

        _writer.BaseStream.Dispose();
        _writer.Dispose();
    }
}

如何使用这个类? - m.qayyum
完美运行 - Anlo

26

有一个内置的.NET类可对GIF文件进行编码。 GifBitmapEncode MSDN

System.Windows.Media.Imaging.GifBitmapEncoder gEnc = new GifBitmapEncoder();

foreach (System.Drawing.Bitmap bmpImage in images)
{
    var bmp = bmpImage.GetHbitmap();
    var src = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
        bmp,
        IntPtr.Zero,
        Int32Rect.Empty,
        BitmapSizeOptions.FromEmptyOptions());
    gEnc.Frames.Add(BitmapFrame.Create(src));
    DeleteObject(bmp); // recommended, handle memory leak
}
using(FileStream fs = new FileStream(path, FileMode.Create))
{
    gEnc.Save(fs);
}

3
使用这段代码,是否有办法在每一帧之间设置一定的延迟或者设定帧速率? - uSeRnAmEhAhAhAhAhA
9
这段代码存在严重问题。它只是将一堆图片叠加在一起,然后保存为一张图片。 - uSeRnAmEhAhAhAhAhA
2
上面的解决方案中需要注意的一点是,您需要处理由GDI位图对象引起的可能的内存泄漏 - 这是给定代码中的bmpImage.GetHbitmap()。正如MSDN所述,这必须手动清除此处有一个代码示例,说明如何执行此操作以避免GDI位图对象占用过多内存。 - vburca
1
有趣的是,我已经添加了额外的代码来解决内存泄漏问题。 - fireydude
在创建和显示gif后,有人会得到一个黑色矩形吗? - inoabrian

25

你还可以考虑使用ImageMagick库。

该库有两个.NET封装器,列在http://www.imagemagick.org/script/api.php上。

这里是一个使用Magick.net封装器的示例:

using (MagickImageCollection collection = new MagickImageCollection())
{
  // Add first image and set the animation delay to 100ms
  collection.Add("Snakeware.png");
  collection[0].AnimationDelay = 100;

  // Add second image, set the animation delay to 100ms and flip the image
  collection.Add("Snakeware.png");
  collection[1].AnimationDelay = 100;
  collection[1].Flip();

  // Optionally reduce colors
  QuantizeSettings settings = new QuantizeSettings();
  settings.Colors = 256;
  collection.Quantize(settings);

  // Optionally optimize the images (images should have the same size).
  collection.Optimize();

  // Save gif
  collection.Write("Snakeware.Animated.gif");
}

18

如果不知道重要的质量参数,是否调用imagemagick是最好的选择可能很难回答。还有其他一些选项:

它们的优点是你不需要依赖第三方库,在执行代码的所有系统中可用或不可用。

MS Support上的这篇文章解释了如何保存带有自定义颜色表的gif(这需要完全信任)。动画gif只是每个图像的一组gif,并在头部添加了一些附加信息。因此,结合这两篇文章应该可以满足您的需求。


1

要在 Windows Forms 应用程序中使用示例,请添加对以下程序集的引用:

C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\PresentationCore.dll C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Xaml.dll C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\WindowsBase.dll

然后:

  • Int32Rect 在 System.Windows 命名空间中。

  • BitmapSizeOptions 在 System.Windows.Media.Imaging 命名空间中。

  • BitmapFrame 在 System.Windows.Media.Imaging 命名空间中。

另外,不要忘记关闭文件流(类似于以下内容):

using(FileStream targetFile = new FileStream(path, FileMode.Create))
{
   gEnc.Save(targetFile);
}

1

AnimatedGif 包可以制作动态gif图片。

using (var gif = AnimatedGif.AnimatedGif.Create(Path.Combine(outputPath, "output.gif"), 20))
{
    for (var i = 0; i < 10; i++)
    {
        Image img = Image.FromFile(Path.Combine(outputPath, $"{i.ToString().PadLeft(3, '0')}.png"));
        gif.AddFrame(img, delay: -1, quality: GifQuality.Bit8);
    }
}

0

我注意到还有一个很好的替代ImageMagic和NGif的选择没有列在答案中。

FFMpeg可以用于从以下内容创建动画GIF:

  • 图像序列(文件)
  • 现有视频剪辑(例如,mp4或avi)
  • 通过将输入数据作为“ravvideo”通过stdin提供来自C#位图对象(而不使用任何临时文件)

您可以直接从C#代码启动ffmpeg.exe(使用System.Diagnostics.Process),也可以使用现有的.NET ffmpeg包装器之一:

var ffmpeg = new NReco.VideoConverter.FFMpegConverter();
ffmpeg.ConvertMedia("your_clip.mp4", null, "result.gif", null, new ConvertSettings() );

(本代码示例使用免费的NReco VideoConverter - 我是此组件的作者,如有任何关于其使用的问题,请随时咨询。)

GIF 尺寸可以通过降低帧率和/或帧大小来轻松减小。 此外,采用双通道方法生成最优GIF调色板,也可以获得外观精美的动态GIF。


嗨,我正在寻找一个使用NReco将多个图像转换为MP4(h.264)格式的代码。我在网上找不到任何有效的示例。你能帮我解决这个问题吗?谢谢! - Moji
你好,你知道我怎么能将图像与视频合并吗?合并视频是正常的。但是当我尝试在两个视频之间合并图像时,使用nreco就无法工作。 - Kanishka
@Kanishka,如果您知道如何使用ffmpeg.exe从命令行执行此操作,则使用VideoConverter包装器也可以实现相同的操作。 - Vitaliy Fedorchenko
@VitaliyFedorchenko,我发布的这个问题你有什么想法?https://dev59.com/eJnga4cB1Zd3GeqPWk5m - Kanishka
有更多使用FFmpeg的真实世界示例吗? - PreguntonCojoneroCabrón
@PreguntonCojoneroCabrón,请查看有关此主题的ffmpeg文档:https://trac.ffmpeg.org/wiki/Slideshow - Vitaliy Fedorchenko

0

来自fireydude的回答: https://dev59.com/9XM_5IYBdhLWcg3w2XLw#16598294

这个方法不完整,因为.gif不能重复播放。 我在其他问题中找到了一些额外的代码,可以让.gif重复播放。

.NET - 使用GifBitmapEncoder创建循环.gif http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp

完整的代码应该像下面的代码:

System.Windows.Media.Imaging.GifBitmapEncoder gEnc = new GifBitmapEncoder();
foreach (System.Drawing.Bitmap bmpImage in bitMaps)
{
    var bmp = bmpImage.GetHbitmap();
    var src = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
        bmp,
        IntPtr.Zero,
        Int32Rect.Empty,
        BitmapSizeOptions.FromEmptyOptions());
    gEnc.Frames.Add(BitmapFrame.Create(src));
    DeleteObject(bmp); // recommended, handle memory leak
    bmpImage.Dispose(); // recommended, handle memory leak
}

// After adding all frames to gifEncoder (the GifBitmapEncoder)...
using (var ms_ = new MemoryStream())
{
    gEnc.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("abc.gif", newBytes.ToArray());
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接