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

2019-01-23 06:42发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:

Probably the best tool for working with videos programatically is FFMpeg. It has support for many formats, even wmv. I suspect there's even a .net wrapper for it.