A set of .NET Framework managed libraries for developing graphical user interfaces.
Hi @mc ,
Thanks for reaching out.
The code snippets below are just for reference, so you may need to adjust them to fit your project structure and requirements.
GifBitmapEncoder belongs to WPF, so it is not available in a plain WinForms project by default. That is why it seems like you cannot use it directly. If you want to use that encoder in a WinForms app, you need to enable WPF support in the project and then convert your System.Drawing.Bitmap objects into WPF image frames before saving.
If your project is SDK-style, add this to the project file:
<PropertyGroup>
<UseWindowsForms>true</UseWindowsForms>
<UseWPF>true</UseWPF>
</PropertyGroup>
After that, you can create the GIF like this:
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Media.Imaging;
public static void SaveGif(IEnumerable<Bitmap> bitmaps, string outputPath)
{
var encoder = new GifBitmapEncoder();
foreach (Bitmap bitmap in bitmaps)
{
using var ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Png);
ms.Position = 0;
var frame = BitmapFrame.Create(
ms,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.OnLoad);
encoder.Frames.Add(frame);
}
using var fs = new FileStream(outputPath, FileMode.Create, FileAccess.Write);
encoder.Save(fs);
}
You can call it like this:
var frames = new List<Bitmap>
{
new Bitmap("frame1.png"),
new Bitmap("frame2.png"),
new Bitmap("frame3.png")
};
SaveGif(frames, "output.gif");
foreach (var bmp in frames)
{
bmp.Dispose();
}
If you only need to save a single bitmap as a normal GIF image, the simpler WinForms-friendly option is just:
bitmap.Save("output.gif", ImageFormat.Gif);
One thing to keep in mind is that if you need a real animated GIF with control over frame delays and looping, GifBitmapEncoder can be a bit limited. In that case, a library like Magick.NET or ImageSharp is usually a smoother option for a WinForms app.
Hope this helps! If my answer was helpful, I would greatly appreciate it if you could follow the instructions here so others with the same problem can benefit as well.