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:

  1. <?php
  2.  
  3. // Full path to ffmpeg (make sure this binary has execute permission for PHP)
  4. $ffmpeg = "/full/path/to/ffmpeg";
  5.  
  6. // Full path to the video file
  7. $videoFile = "/full/path/to/video.mp4";
  8.  
  9. // Full path to output image file (make sure the containing folder has write permissions!)
  10. $imgOut = "/full/path/to/frame.jpg";
  11.  
  12. // Number of seconds into the video to extract the frame
  13. $second = 0;
  14.  
  15. // Setup the command to get the frame image
  16. $cmd = $ffmpeg." -i \"".$videoFile."\" -an -ss ".$second.".001 -y -f mjpeg \"".$imgOut."\" 2>&1";
  17.  
  18. // Get any feedback from the command
  19. $feedback = `$cmd`;
  20.  
  21. // Use $imgOut (the extracted frame) however you need to 
  22. // ... 
  23.  
  24. ?>

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.

Attached Files: