Create thumbnail from video without ffmpeg in PHP

If the video can be played back in the browser you could try using the Canvas feature of html5 to playback the video in a canvas and then post a still from that video to your server using javascript… Maybe you could even automate it, or if you only have a few dozen videos do it by hand…

The following is some jquery flavored javascript to upload a base64-encoded jpg in order to get you started. (Mashed up from several different projects, so untested and probably a security nightmare.)

<script>
    var vidDOM = $('article').children('video');
    var vid = vidDOM.get(2);
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');

    vidDOM.bind({
        'paused':function () {
            vid.width = canvas.width = vid.offsetWidth;
            vid.height = canvas.height = vid.offsetHeight;
            var $this = this; 
            ctx.drawImage($this, 0, 0, vid.width, vid.height);
            uploadbase64();
        }
    })

    function uploadbase64(){
        canvasData = canvas.toDataURL("image/jpeg"); 
        var ajax = new XMLHttpRequest();
        ajax.open("POST",'ImageUpload.php?filename="+vidDOM.id,false);
        ajax.setRequestHeader("Content-Type', 'application/upload');
        ajax.send(canvasData);
    }
</script>

And here is a bit of php to accept the upload.

<?php
    $filename =$_GET['filename'];

    if (file_get_contents('php://input')){
        // Remove the headers (data:,) part.
        $filteredData=substr(file_get_contents('php://input'), strpos(file_get_contents('php://input'), ",")+1);

        // Need to decode before saving since the data we received is already base64 encoded
        $decodedData=base64_decode($filteredData);

        //create the file
        if($fp = fopen( $filename, 'wb' )){
            fwrite( $fp, $decodedData);
            fclose( $fp );
        } else {
            echo "Could not create file.";
        }
}

echo "Created image ".$filename;

?>

Leave a Comment