Extracting image frame from a video in c#

dapper

Install the following NuGet packages:

  1. FFMediaToolkit
  2. SixLabors.ImageSharp

Download ffmpeg binaries from here: https://github.com/BtbN/FFmpeg-Builds/releases

Here is an example that extracts a PNG image from the middle of the video stream


private byte[] GetImageFromVideo(byte[] buffer)
{

    FFmpegLoader.FFmpegPath = @"c:\path\to\ffmpeg\binaries";

    using MemoryStream memStream = new (buffer);

    using MediaFile file = MediaFile.Open(memStream);

    file.Video.TryGetFrame(file.Video.Info.Duration.Divide(2), out ImageData imageData);

    using SixLabors.ImageSharp.Image<Bgr24> img =
            SixLabors.ImageSharp.Image.LoadPixelData<Bgr24>(imageData.Data, imageData.ImageSize.Width, imageData.ImageSize.Height);

    using MemoryStream outStream = new MemoryStream();

    img.Save(outStream, new PngEncoder());

    return outStream.ToArray();
}

Post a Comment

Previous Post Next Post