Create a random thumbnail of a video file

Last modified date

Comments: 16

Create a random thumbnail of a video file

Looking at sites like YouTube, you may think it’s quite hard to create a lot of different thumbnails from video files, and have them from random times within that file. But, no, it’s not! As this article shows, by using the very fabulous FFmpeg library, it’s actually a very short amount of code that’s required to create all those lovely random thumbnails.

First a little information about FFmpeg. If you haven’t come across this yet then you’re missing out on an excellent bit of software to put in your tool kit. It can convert and stream all manner of video and audio files, is open source (under LGPL, but with some optional GPL bits), and is always being worked on and developed.

FFmpeg’s homepage is at http://ffmpeg.mplayerhq.hu/, where you can grab the latest revision from SVN. If you want it for Windows, then one location I found with quite recent builds is http://ffdshow.faireal.net/mirror/ffmpeg/, but if you know any better ones then let me know.

So on with the code…

[php]&1″;
if (preg_match(‘/Duration: ((\d+):(\d+):(\d+))/s’, `$cmd`, $time)) {
$total = ($time[2] * 3600) + ($time[3] * 60) + $time[4];
$second = rand(1, ($total – 1));
}

// get the screenshot
$cmd = “$ffmpeg -i $video -deinterlace -an -ss $second -t 00:00:01 -r 1 -y -vcodec mjpeg -f mjpeg $image 2>&1”;
$return = `$cmd`;

// done! 😉
echo ‘done!’;

?>[/php]

Nice and short, and that’s even with me being generous over white space!

The two key portions in this code are the ones to get the random time location of the video, which we do by parsing the output from a call to ffmpeg, and then running another command to generate the image.

When running the first command it’s important to remember the 2>&1 to redirect the stderr to stdout, as it’s actually an error message we want to capture. To be on the safe side, I simple add it to all my command line calls to FFmpeg (which in this example is only two!)

Now that you have your thumbnail image you may be thinking that you need to use GD, ImageMagick, or some other graphics library to resize the image, right? Well, you could, if you wanted to, but you could also do it in the very same command line to create the thumbnail! Basically, you’d use the -s flag to resize the thumbnail. For example:

[php]$cmd = “$ffmpeg -i $video -deinterlace -an -ss $second -t 00:00:01 -r 1 -y -s 320×240 -vcodec mjpeg -f mjpeg $image 2>&1”;[/php]

You may also notice the -deinterlace flag in there. You may not need this – it depends on whether you video file needs deinterlacing or not. All of the flags are detailed in the FFmpeg documentation.

Oh, and if you’re taking user input for the video file or output image file, then please remember to escape your variables accordingly! Use something like the escapeshellcmd() PHP function.

Have fun grabbing your video frames!!

Share