kad1r
12/12/2013 - 12:32 AM

Taking screenshot and generating image from video with FFMPEG

Taking screenshot and generating image from video with FFMPEG

/// <summary>
/// file means video file with extension ex: video.mp4
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static string GenerateThumbFromVideo(string file)
{
	string thumbUploadDirectory = "", directory = "", ApplicationPath = "";
	string thumb = "";
	thumbUploadDirectory = @"";
	if (ApplicationPath != "/")
	{
		thumbUploadDirectory += ApplicationPath + "/video";
		file = ApplicationPath + file;
	}
	else
	{
		thumbUploadDirectory += "/video";
	}

	directory = HttpContext.Current.Server.MapPath(thumbUploadDirectory);

	try
	{
		string ffmpegFilePath = "~" + ApplicationPath + "/video/ffmpeg/ffmpeg.exe";
		FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath(file));
		string filename = Path.GetFileNameWithoutExtension(fi.Name);
		string extension = Path.GetExtension(fi.Name);
		Random random = new Random();
		int rand = random.Next(1, 9999999);
		string newfilename = "";
		if (ApplicationPath != "/")
			newfilename = ApplicationPath + "/video/" + filename.replace() + "___(" + rand.ToString() + ").jpg";
		else
			newfilename = "/video/" + filename.replace() + "___(" + rand.ToString() + ").jpg";

		var processInfo = new ProcessStartInfo();
		processInfo.FileName = "\"" + HttpContext.Current.Server.MapPath(ffmpegFilePath) + "\"";
		processInfo.Arguments = string.Format("-ss {0} -i {1} -f image2 -vframes 1 -y {2}", 5, "\"" + HttpContext.Current.Server.MapPath(file) + "\"", "\"" + HttpContext.Current.Server.MapPath(newfilename) + "\"");
		processInfo.CreateNoWindow = true;
		processInfo.UseShellExecute = false;
		using (var process = new Process())
		{
			process.StartInfo = processInfo;
			process.Start();
			process.WaitForExit();
			thumb = newfilename;
		}
	}
	catch (Exception ex)
	{
		string error = ex.Message;
	}

	return thumb;
}