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-video\out.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-video\out.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!
Thanks for this. I am trying to replicate it, but keep getting the error, “Cannot load required FFmpeg libraries from C:\FFmpeg\ directory.” when the code hits the CreateContainer method. Do you know how to fix this?
LikeLike
1) try to set FFMediaToolkit.FFmpegLoader.FFmpegPath to FFmpeg directory
2) It is pissible that you have wrong FFMPeg version. You can try this: https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2021-08-13-12-37/ffmpeg-n4.4-80-gbf87bdd3f6-win64-gpl-shared-4.4.zip
LikeLike
Is there any audio example add this frame? Try searching everything, I didnt find tutorial for this.
LikeLike