js(ts)截取视频第一帧作为封面图

js截取视频第一帧作为封面图

直接上代码:

/*
* 截取视频的第一帧
*/
export const getVideoBase64 = (url: string) => {
    return new Promise(resolve => {
        let dataURL = '';
        const video = document.createElement('video') as HTMLVideoElement;
        video.setAttribute('crossOrigin', 'anonymous');// 处理跨域
        video.setAttribute('src', url);
        video.setAttribute('width', '400');
        video.setAttribute('height', '240');
        video.setAttribute('preload', 'auto'); // 防止截取图片黑屏的关键属性
        video.setAttribute('autoplay', 'autoplay');
        video.addEventListener('loadeddata', () => {
            const canvas = document.createElement('canvas');
            const width = video.videoWidth; // canvas的尺寸和视频一样
            const height = video.videoHeight;
            canvas.width = width;
            canvas.height = height;
            canvas.getContext('2d').drawImage(video, 0, 0, width, height); // 绘制canvas
            const imageData: any = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height); // 绘制canvas
            const arr = imageData.data;
            dataURL = canvas.toDataURL('image/png'); // 转换为base64
            const brr = [];
            for (let a = 0; a < arr.length; a++) {
                const arrItem = arr[a];
                if (arrItem > 0 && arrItem < 200) {
                    brr.push(arrItem);
                }
            }
			if (!brr.length) {
				// 截取的图片无效(黑屏、白屏、透明),这里可以返回系统默认图片
			}
            resolve(dataURL);
        });
    });
};

这里有三个地方需要注意:

1. 需要加上preload 属性

video.setAttribute('preload', 'auto');

这是防止截图结果为黑屏的关键一步

2. canvas宽高的设置

            const width = video.videoWidth; // canvas的尺寸和视频一样
            const height = video.videoHeight;

网络上其它文章的代码都直接读取video.widthvideo.height,会导致如果是竖视频截取出来的封面图在横显示时会变形

3. 判断图片有效性

const imageData: any = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height); // 绘制canvas
            const arr = imageData.data;
            const brr = [];
            for (let a = 0; a < arr.length; a++) {
                const arrItem = arr[a];
                if (arrItem > 0 && arrItem < 200) {
                    brr.push(arrItem);
                }
            }
			if (!brr.length) {
				// 截取的图片无效(黑屏、白屏、透明),这里可以返回系统默认图片
			}

有时候截取到的图片可能是黑屏、白屏、透明等,需要使用二进制数据进行判断,如果无效,则返回系统默认图片。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值