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'); // 防止截取圖片黑屏的關(guān)鍵屬性
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'); // 轉(zhuǎn)換為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) {
// 截取的圖片無效(黑屏、白屏、透明),這里可以返回系統(tǒng)默認(rèn)圖片
}
resolve(dataURL);
});
});
};
這里有三個(gè)地方需要注意:
1. 需要加上preload
屬性
video.setAttribute('preload', 'auto');
這是防止截圖結(jié)果為黑屏的關(guān)鍵一步
2. canvas寬高的設(shè)置
const width = video.videoWidth; // canvas的尺寸和視頻一樣
const height = video.videoHeight;
網(wǎng)絡(luò)上其它文章的代碼都直接讀取video.width
和 video.height
,會(huì)導(dǎo)致如果是豎視頻截取出來的封面圖在橫顯示時(shí)會(huì)變形文章來源:http://www.zghlxwxcb.cn/news/detail-686412.html
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) {
// 截取的圖片無效(黑屏、白屏、透明),這里可以返回系統(tǒng)默認(rèn)圖片
}
有時(shí)候截取到的圖片可能是黑屏、白屏、透明等,需要使用二進(jìn)制數(shù)據(jù)進(jìn)行判斷,如果無效,則返回系統(tǒng)默認(rèn)圖片。文章來源地址http://www.zghlxwxcb.cn/news/detail-686412.html
到了這里,關(guān)于js(ts)截取視頻第一幀作為封面圖的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!