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

需求: 上传视频时,有时候需要前端上传封面图,一般是获取视频的第一帧来作为该视频的封面图;
解决方式:

步骤一: 截取视频的第一帧,用 canvas 将图片绘制出来( 默认生成 240*160 的图片 ,图片按自身宽高比缩小,剩余空间填充黑色 ):

let getVideoCover = function(file){
    
    
	const imgWidth=240,imgHeight=160;  // 定义生成图片的宽高,其他宽高需求可以自己改
	var fileUrl = URL.createObjectURL(file);
	var videoElement = document.createElement("VIDEO");
    videoElement.src = fileUrl;
    videoElement.addEventListener("loadeddata",()=>{
    
    
		let {
    
     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;
        } 
        var canvas = document.createElement("canvas");
        canvas.width = imgWidth ;
        canvas.height = imgHeight;
        let ctx = canvas.getContext("2d");
        ctx.fillStyle = "#000";
        ctx.fillRect(0, 0, imgWidth , imgHeight);
        ctx.drawImage(videoElement, x, y, width, height);
        let src = canvas.toDataURL("image/png"); // 完成base64图片的创建
	})
}

这个函数接收一个参数,为file,即需要上传的视频文件,最后的 src 就是图片的base64 ,可以直接放在 img 标签的 src 上面使用,如果后端可以上传base64的话,那么就可以直接上传这个src了,如果后端需要你将这个图片转成文件上传,那么就还需要下一步。

步骤二: 将 base64 图片转换成 file 对象:

dataURLtoFile(dataurl, filename) {
    
    
	var arr = dataurl.split(","),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
    
    
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new File([u8arr], filename, {
    
     type: mime });
},

该函数需要两个参数,第一个参数就是图片的 base64 数据,第二个就是文件的名字,会返回一个 File 对象,将这个file对象发送给后端就可以了。

猜你喜欢

转载自blog.csdn.net/brilliantSt/article/details/123664177
今日推荐