Create thumbnail from video file via file input

后端 未结 4 1785
悲&欢浪女
悲&欢浪女 2020-12-04 14:19

I am attempting to create a thumbnail preview from a video file (mp4,3gp) from a form input type=\'file\'. Many have said that this can be done server side onl

4条回答
  •  感动是毒
    2020-12-04 14:48

    Recently needed this so I wrote a function, to take in a video file and a desired timestamp, and return an image blob at that time of the video.

    Sample Usage:

    try {
        // get the frame at 1.5 seconds of the video file
        const cover = await getVideoCover(file, 1.5);
        // print out the result image blob
        console.log(cover);
    } catch (ex) {
        console.log("ERROR: ", ex);
    }
    

    Function:

    function getVideoCover(file, seekTo = 0.0) {
        console.log("getting video cover for file: ", file);
        return new Promise((resolve, reject) => {
            // load the file to a video player
            const videoPlayer = document.createElement('video');
            videoPlayer.setAttribute('src', URL.createObjectURL(file));
            videoPlayer.load();
            videoPlayer.addEventListener('error', (ex) => {
                reject("error when loading video file", ex);
            });
            // load metadata of the video to get video duration and dimensions
            videoPlayer.addEventListener('loadedmetadata', () => {
                // seek to user defined timestamp (in seconds) if possible
                if (videoPlayer.duration < seekTo) {
                    reject("video is too short.");
                    return;
                }
                // delay seeking or else 'seeked' event won't fire on Safari
                setTimeout(() => {
                  videoPlayer.currentTime = seekTo;
                }, 200);
                // extract video thumbnail once seeking is complete
                videoPlayer.addEventListener('seeked', () => {
                    console.log('video is now paused at %ss.', seekTo);
                    // define a canvas to have the same dimension as the video
                    const canvas = document.createElement("canvas");
                    canvas.width = videoPlayer.videoWidth;
                    canvas.height = videoPlayer.videoHeight;
                    // draw the video frame to canvas
                    const ctx = canvas.getContext("2d");
                    ctx.drawImage(videoPlayer, 0, 0, canvas.width, canvas.height);
                    // return the canvas image as a blob
                    ctx.canvas.toBlob(
                        blob => {
                            resolve(blob);
                        },
                        "image/jpeg",
                        0.75 /* quality */
                    );
                });
            });
        });
    }
    

提交回复
热议问题