Speed up image extraction with ffmpeg

A product requirement for a media management application I am building is to automatically extract a user-defined number of images from an uploaded video file. The user can request for up to 20 images to be extracted from a given video. My initial implementation was taking almost 5 minutes to complete a 20 image extraction from a 7 minute video.

1
2
3
4
5
6
7
8
9
10
11
12
13
private function generateThumbnails( $video, $destination, $duration, $thumbnail_count ){

    $duration = (int)$duration;
    $interval = floor( $duration / $thumbnail_count );

    $c = 1;
    while( $c <= $thumbnail_count ){
        $offset = $interval * $c;
        exec("ffmpeg -i \"{$video}\" -ss " . $offset . " -y -vcodec mjpeg -vframes 1 -an -f rawvideo -s 720x404 " . $destination . "thumb_" . $c . ".jpg");
        $c++;
    }

}

Turns out ffmpeg will encode the video to the -ss parameter if you supply the -i parameter before the -ss parameter. So the simple fix was to call -ss before -i. The 20 image extraction now takes less than a second.

1
2
3
4
5
6
7
8
9
10
11
12
13
private function generateThumbnails( $video, $destination, $duration, $thumbnail_count ){

    $duration = (int)$duration;
    $interval = floor( $duration / $thumbnail_count );

    $c = 1;
    while( $c <= $thumbnail_count ){
        $offset = $interval * $c;
        exec("ffmpeg -ss " . $offset . " -i \"{$video}\" -y -vcodec mjpeg -vframes 1 -an -f rawvideo -s 720x404 " . $destination . "thumb_" . $c . ".jpg");
        $c++;
    }

}

2 Comments

  1. Bastian Thies says:

    Thanks alot!

    I had exactly the same problem! Works like a charm…

    Best regards, Bastian

  2. Chris says:

    Thank you so much, awesome

Leave a Reply