Extract an image frame from a video using PHP and ffmpeg

Have you ever needed to grab a still frame from a video clip and display it as a thumbnail image on your website?  This process can be pretty simple with the right tools.  I’ve run into several situations when I’ve needed to extract frames of a video and display it as a thumbnail inside a page.

Requirements:

Webserver running PHP
ffmpeg installed on server (this post will not cover the installation process)

PHP Code:

<?php
 
// Full path to ffmpeg (make sure this binary has execute permission for PHP)
$ffmpeg = "/full/path/to/ffmpeg";
 
// Full path to the video file
$videoFile = "/full/path/to/video.mp4";
 
// Full path to output image file (make sure the containing folder has write permissions!)
$imgOut = "/full/path/to/frame.jpg";
 
// Number of seconds into the video to extract the frame
$second = 0;
 
// Setup the command to get the frame image
$cmd = $ffmpeg." -i \"".$videoFile."\" -an -ss ".$second.".001 -y -f mjpeg \"".$imgOut."\" 2>&1";
 
// Get any feedback from the command
$feedback = `$cmd`;
 
// Use $imgOut (the extracted frame) however you need to 
// ... 
 
?>

That’s all there is to it.  As mentioned in the comments above, be sure that the output folder is writable or this will process will fail.  If you want to fine-tune the selected frame for extraction, you can change the “.001” to the exact frame number for the second you select.

 

Leave a Reply

avatar
  Subscribe  
Notify of