Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save first frame of a video as image?

I want to extract first frame of uploaded video and save it as image file.
Possible video formats are mpeg, avi and wmv.

One more thing to consider is that we are creating an ASP.NET website.

like image 688
CoderHawk Avatar asked Aug 26 '10 13:08

CoderHawk


2 Answers

You could use FFMPEG as a separate process (simplest way) and let it decode first IDR for you. Here you have a class FFMPEG that has GetThumbnail() method, to it you pass address of video file, address of the JPEG image to be made, and resolution that you want the image to be:

using System.Diagnostics;
using System.Threading; 

public class FFMPEG
{
    Process ffmpeg;

    public void exec(string input, string output, string parametri)
    {
        ffmpeg = new Process();

        ffmpeg.StartInfo.Arguments = " -i " + input+ (parametri != null? " "+parametri:"")+" "+output; 
        ffmpeg.StartInfo.FileName = "utils/ffmpeg.exe";
        ffmpeg.StartInfo.UseShellExecute = false;
        ffmpeg.StartInfo.RedirectStandardOutput = true;
        ffmpeg.StartInfo.RedirectStandardError = true;
        ffmpeg.StartInfo.CreateNoWindow = true;

        ffmpeg.Start();
        ffmpeg.WaitForExit();
        ffmpeg.Close();     
    }


    public void GetThumbnail(string video, string jpg, string velicina)
    {
        if (velicina == null) velicina = "640x480";
        exec(video, jpg, "-s "+velicina);
    }
}

Use like this:

FFMPEG f = new FFMPEG();
f.GetThumbnail("videos/myvid.wmv", "images/thumb.jpg", "1200x223");

For this to work, you must have ffmpeg.exe in folder /utils, or change the code to locate ffmpeg.exe.

There are other ways to use FFMPEG in .NET, like .NET wrappers, you could google for them. They basically do the same thing here, only better. So if FFMPEG gets your job done, I'd recomend to use .NET wrapper.

like image 168
Cipi Avatar answered Oct 18 '22 08:10

Cipi


Try to make argument string format like:

ffmpeg.StartInfo.Arguments =" -i c:\MyPath\MyVideo -vframes 1 c:\MyOutputPath\MyImage%d.jpg"

Instead of

ffmpeg.StartInfo.Arguments = " -i " + input+ (parametri != null? " "+parametri:"")+" "+output;

in the answer code provided above.

I don't know what was the reason, but second mentioned argument line is not working on my machine whereas when I changed argument like the first command it works fine.

like image 35
Anil Avatar answered Oct 18 '22 08:10

Anil