export function getVideoCover(file, response) {
// 定义生成图片的宽高,其他宽高需求可以自己改
// const imgWidth = 240;
// const imgHeight = 160;
const fileUrl = URL.createObjectURL(file);
const videoElement = document.createElement('VIDEO');
videoElement.preload = true;
videoElement.autoplay = true;
videoElement.muted = true;
const callBack = () => {
const { videoWidth, videoHeight } = videoElement; // 获取video的宽高
// let x = 0, y = 0, width = 0, height = 0;
// // 计算缩小后图片的宽高以及canvas绘制的位置信息
// if (videoWidth / videoHeight >= 1.5) {
// width = imgWidth ;
// height = videoHeight * (imgWidth / videoWidth);
// x = 0;
// y = (imgHeight- height) / 2;
// } else {
// height = imgHeight;
// width = videoWidth * (imgHeight / videoHeight);
// y = 0;
// x = (imgWidth - width) / 2;
// }
const canvas = document.createElement('canvas');
canvas.width = videoWidth ;
canvas.height = videoHeight;
const ctx = canvas.getContext('2d');
// ctx.fillStyle = "#000";
// ctx.fillRect(0, 0, imgWidth , imgHeight);
ctx.drawImage(videoElement, 0, 0, videoWidth, videoHeight);
const dataBase64 = canvas.toDataURL('image/png'); // 完成base64图片的创建
if (dataBase64) {
const imgFile = dataURLtoFile(dataBase64, `${new Date().getTime()}.png`);
if (response) {
response(imgFile, dataBase64);
}
}
};
// videoElement.addEventListener('loadeddata', callBack);
// videoElement.onseeked = callBack;
videoElement.onloadeddata = setTimeout(() => {
callBack();
}, 1000);;
videoElement.src = fileUrl;
}
export function dataURLtoFile(dataBase64, filename) {
const arr = dataBase64.split(",");
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
constn = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { type: mime });
}
网友评论