As mentioned yesterday, you can use the GifEncoder from the Bumpkit class library to save animated Gif image files. In fact, the encoder has no dependencies on the rest of the class library, so I just copied it’s code-file into my solution.
Again, the source, for this and a whole bunch of other stuff, is here: RomyView.zip
I added a simple extension method, to allow saving collections of images to animated Gifs, much the same as my extension method that saves images to icon files. The extension method is just this:
Images to animated Gif extension method
- public static void SaveAnimatedGifImage(this IEnumerable<Image> images, string path)
- var imageArray = images.ToArray();
- using (var stream = new MemoryStream())
- using (var encoder = new BumpKit.GifEncoder(stream))
- for (int i = 0; i < imageArray.Length; i++)
- var image = (imageArray[i] as Bitmap).CopyImage();
- encoder.AddFrame(image, 0, 0, TimeSpan.FromSeconds(0));
- stream.Position = 0;
- using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, Constants.BufferSize, false))
Remarks: Perhaps it is worth noting that the CopyImage call above is just an extension method, similar to Bitmap.Clone. The code will fail to add frames without it, or something similar. I would also normally have added an async method the same as the above, but due to a nasty case of the flu, have done only the minimum for a change. (If you have paid attention in previous posts, you should see how easy it would be to add an async overload. All that’s required really is to mark the method async, then use an async method rather than Stream.WriteTo as the last step. i.e. Stream.CopyToAsync, after changing the FileStream constructor to support async operations.)
And here is an image I created with it (after exporting some frames from the trailer for the new man of Steel movie with ffmpeg).
I have scaled this down and set it to repeat only once due to it messing up the page load time.
Note also, the VideoConverter part of my application was used to export the frames. (It just wraps the ffmpeg console application for Windows.) I just chose “Image Sequence” as the output format. It also allows you to crop and scale the output. Cropping was required here because the Man of Steel trailer features black areas above and below the actual image frames. I can’t tell you how to download videos from YouTube though. (I use a program written by someone else for that.)