Does anyone know how to create an animated gif using c#? Ideally I would have some control over the color reduction used.
Is using imagemagick (as an external started process) the best choice?
Does anyone know how to create an animated gif using c#? Ideally I would have some control over the color reduction used.
Is using imagemagick (as an external started process) the best choice?
Whether or not calling imagemagick is the best choice is kind of hard to awnser without knowing the quality parameters that are important. Some other options would be:
these have the advantage that you don't have a dependency on a third partly library which might or might not be available on all systems executing your code.
This article at MS Support explains how to save a gif with a custom color table (this does require full trust). A animated gif is just a set of gifs for each image with some additional information in the header. So combining these two articles should get you what you need.
The AnimatedGif package can make animated gifs.
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);
}
}
Quote from fireydude answer: https://stackoverflow.com/a/16598294/8917485
This method is not complete, cause the .gif can't repeat. I found some additional code on other question, make .gif repeat.
.NET - Creating a looping .gif using GifBitmapEncoder http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp
The complete code should looks like the code below:
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());
}