Generate video from collection of images in C# #FFMPEG

You want to create a dynamic video, from a collection of images – Here is where FFMpeg is a great tool to use with C#

So, as a pre-requisite, you’ll need to download FFMpeg and put it in a folder, I’m calling it “C:FFmpeg” – but you can put it anywhere. I’m also assuming you have a collection of images in c:input, and you want the output video in C:out-videoout.mp4 – all these paths can be changed.

If you’ve seem my earlier example of capturing video from a webcam and saving to a video, this approach is more elegant, since it doesn’t involve chopping the header off the bitmap array, and swapping the red and blue channels, however, this solution is for Windows only, it’s not cross platform.

I used the FFMediaToolkit Nuget package, and also System.Drawing.Common

FFmpegLoader.FFmpegPath =
@”C:FFmpeg”;

var settings = new VideoEncoderSettings(width: 960, height: 544, framerate: 30, codec: VideoCodec.H264);
settings.EncoderPreset = EncoderPreset.Fast;
settings.CRF = 17;
var file = MediaBuilder.CreateContainer(@”C:out-videoout.mp4″).WithVideo(settings).Create();
var files = Directory.GetFiles(@”C:Input”);
foreach (var inputFile in files)
{
var binInputFile = File.ReadAllBytes(inputFile);
var memInput = new MemoryStream(binInputFile);
var bitmap = Bitmap.FromStream(memInput) as Bitmap;
var rect = new System.Drawing.Rectangle(System.Drawing.Point.Empty, bitmap.Size);
var bitLock = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
var bitmapData = ImageData.FromPointer(bitLock.Scan0, ImagePixelFormat.Bgr24, bitmap.Size);
file.Video.AddFrame(bitmapData); // Encode the frame
bitmap.UnlockBits(bitLock);

}

file.Dispose();

So, what this does, is create a container video of a given size and framerate, and codec. (H264), then adds the images one by one. The container is hard-coded to 960×544, but you should base this on the maximum size of the images in your image folder instead.

The images need to be decompressed, from jpeg to Bitmap, then from Bitmap to ImageData, which is an array of BGR24 structures.

Hope this helps someone!

Flatlogic Admin Templates banner

Leave a Reply

Your email address will not be published. Required fields are marked *