Extract thumbnails from video using ffmpeg

PHP 2 responses so far

FFmpeg is a free software project that produces libraries and programs for handling multimedia data.It can help us to get frames of video at an interval of time and we can use these frames as thumbnails which when clicked starts the video.Also we can extract multiple frames and create an onmouseover image change effect of this video.So,this software helps us to reduce extra task of uploading thumbnails of videos separately.

First of all ffmpeg needs to be installed to your server.It can easily be installed using command line in ssh.Please follow this [highlight]link[/highlight][highlight][/highlight] to get detailed instructions on ffmpeg installation on centos 6.0.

Once ffmpeg is installed successfully ,its time to write out the code to utilize it and accomplish extracting thumbnails from our videos.

<?
function ExtractThumb($in, $out,$time)
{
 $thumb_stdout;
 $errors;
 $retval = 0;

// Delete the file if it already exists
 if (file_exists($out)) { unlink($out); }

// Use ffmpeg to generate a thumbnail from the movie
 $cmd = "/usr/local/bin/ffmpeg -itsoffset -$time -i $in -vcodec mjpeg -vframes 1 -an -f rawvideo -s 320x240 $out 2>&1";
 exec($cmd, $thumb_stdout, $retval);

// Queue up the error for processing
 if ($retval != 0) { $errors[] = "FFMPEG thumbnail generation failed"; }
 if (!empty($thumb_stdout))
 {
 foreach ($thumb_stdout as $line)
 {
 $line . "
n";
 }
 }

if (!empty($errors))
 {
 foreach ($errors as $error)
 {
 $error . "
n";
 }
 }
}

$file= "path to uploaded video";
ob_start();
passthru("/usr/local/bin/ffmpeg -i ".$file." 2>&1");
$duration = ob_get_contents();
ob_end_clean();

$search='/Duration: (.*?)[.]/';
$duration=preg_match($search, $duration, $matches, PREG_OFFSET_CAPTURE);
$duration = $matches[1][0];
list($hours, $mins, $secs) = split('[:]', $duration);
$totaltime = $secs+($mins*60)+($hours*3600);

$kk=0;
$inkk=$file;
$outkk="output path";
$time=$kk;
ExtractThumb($inkk, $outkk,$time);
//sql query to store this first thumbnail to be written here</pre>
// Loop for fetching images of the videos time diff 10 sec

$i = 10;
while ($i <= $totaltime)
{
$in=$row1['upload_file'];
$out="output path/image name to each of these thumbnails";
$time=$i;
ExtractThumb($in, $out,$time);
//code to insert thumb in db goes here
$i=$i+10;
}
?>

Ffmpeg has wide applications.It is also used to convert and stream audio and video.It includes libavcodec – the leading audio/video codec library.

The following two tabs change content below.
I am a core php developer and web designer working as a freelancer in elance,odesk etc.

Latest posts by Mudit (see all)

  • what women want from men

    I am in fact grateful to the owner of this
    website who has shared this great post at at this time.

  • Paul

    Hey, how can I contact you for a job similar to this?

x
Loading...