phpjavascriptimageframe

PHP - Extract frame during Video upload


I'm having a problem finding if this is even possible (no info anywhere to be found). Is it possible to EXTRACT a frame (thumbnail) during the video upload? Extract using jscript is also an option if it's possible to extract user side.

Thanks for the help!


Solution

  • Fast forward almost five years since this question was posted, and the answer is now a yes!

    Live demo

    How to extract a frame during video upload using JavaScript

    Before showing code, this is what we'll do:

    1. Set an event handler on the input element that will take the video to be uploaded
    2. When a file is selected from the file system, use the URL object to create a url to the local video file.
    3. Load that URL into a video element.
    4. When the video has loaded into memory, draw a frame on a canvas object.
    5. Now export the frame rendered on the canvas into an image element (or optionally send that image to your server as a data url).

    <input type="file" id="upload"/>
    <img id="thumbnail"/>
    
    <script>
    var input = document.getElementById('upload');
    var img = document.getElementById('thumbnail');
    
    input.addEventListener('change', function(event){
        var file = this.files[0];
        var url = URL.createObjectURL(file);
    
        var video = document.createElement('video');
        video.src = url;
    
        var snapshot = function(){
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
    
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            img.src = canvas.toDataURL('image/png');
    
            video.removeEventListener('canplay', snapshot);
        };
    
        video.addEventListener('canplay', snapshot);
    });
    </script>