Saturday, June 26, 2021

How to Get Video Thumbnails with Javascript

Hello,

In this blog we will see how you can generate thumbnail of video using JavaScript.  Let's assume you have file upload in your HTML as following.

<input type="file" id="uploadVideo" accept="video/mp4" />

Now let's add an onChange listener for this.

document.querySelector("#uploadVideo").addEventListener('change', function() {
    var inputFile = document.querySelector("#uploadVideo").files[0];
    getVideoThumbnail(inputFile)
});

Now when you upload video it will call this function and you can access this video by using files property. Now we got the file. First step we will do is get blob URL of video so we can access metadata of video. Check below function. 

Here first what we are doing is creating video element and assigning blob URL to it from input file using URL.createObjectURL method.

Then we have added event listener for meta data. This is necessary as we can't get video data till them time meta data is loaded. 

Then we seek video to 0.0 second. You can add your own time here in case if you need. Then we have added seeked listener. By this time we have video data is available. Now we are using canvas to drawImage from video frame data.

Then using toDataURL method we get the base64Data. Here 0.60 is value of quality. If you don't want to compromise quality of image then you can pass 1 here.  

function getVideoThumbnail(inputFile) {
  try {
    let video = document.createElement('video');
    let blobSrc = URL.createObjectURL(inputFile);
    video.setAttribute('src', blobSrc);
    video.addEventListener('error', () => {
        console.log("Error")
    });
    video.addEventListener('loadedmetadata', () => {
        setTimeout(() => {
          video.currentTime = 0.0;
        }, 200);
        video.addEventListener('seeked', () => {
            let canvas = document.createElement('canvas');
            video.pause();
            canvas.width = 400
            canvas.height = 400;
            let ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            var base64Data = ctx.canvas.toDataURL(
                'image/png',
                0.60
            );
            // SET this data in SRC of image tag or you can add your own logic.
        });
    });
     video.load();
  } catch (err) {
  
  }
}

Hope this helps you.

No comments:

Post a Comment