js截取视频第一帧

使用canvas截取视频第一帧方法.

extractVideoFrame方法,代码核心部分有注释讲解已经封装好了,直接copy到你们项目中使用即可

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            margin: 32px;
        }
    </style>
</head>

<body>
    <input type="file" accept="video/mp4" id="upload_file" onchange="uploadFile(event)">
</body>

<script>
    async function uploadFile(e) {
        const video_file = e.target.files[0];
        const res = await extractVideoFrame(video_file)
        console.log('截取结果', res);
    }
    /**
     * 提取视频第一帧
     * @param {File}  video_file
     */
    function extractVideoFrame(video_file) {
        return new Promise((resolve) => {
            let canvasEl = document.createElement('canvas');
            let videoEl = document.createElement('video');

            videoEl.currentTime = 0.3; // 跳转到指定时间点
            videoEl.muted = true;
            videoEl.src = URL.createObjectURL(video_file);
            videoEl.onloadedmetadata = () => {
                videoEl.play()
            };
            videoEl.ontimeupdate = () => {
                if (videoEl.readyState !== 0 && videoEl.readyState !== 1) {
                    videoEl.pause()
                }
            };
            videoEl.onpause = () => {
                const _w = videoEl.videoWidth;//获取视频宽度
                const _h = videoEl.videoHeight;//获取视频高度
                canvasEl.width = _w;//设置画布宽高
                canvasEl.height = _h;//设置画布宽高
                const ctx = canvasEl.getContext('2d');
                ctx.drawImage(videoEl, 0, 0, _w, _h);// 绘制视频第一帧
                canvasEl.toBlob(// 将canvas转为blob
                    (blob) => {
                        const img_file = new File([blob], (video_file.name.split('.mp4')[0] ?? '未知') + '.jpeg', { type: blob.type })// 将blob转为file
                        const preview_url = URL.createObjectURL(img_file);// 将file转为url
                        document.body.appendChild(canvasEl)
                        resolve({ img_file, preview_url })
                        canvasEl = videoEl = null
                    },
                    'image/jpeg',
                    1
                );
            }
        })
    }
</script>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值