js captures the first frame of the video as the cover

Requirement: When uploading a video, sometimes it is necessary to upload the cover image on the front end, usually the first frame of the video is obtained as the cover image of the video;
solution:

Step 1: Capture the first frame of the video, and use canvas to draw the picture (by default, a 240*160 picture is generated, the picture is reduced according to its own aspect ratio, and the remaining space is filled with black):

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图片的创建
	})
}

This function receives a parameter, which is file, which is the video file to be uploaded. The final src is the base64 of the image, which can be directly used on the src of the img tag. If the backend can upload base64, then you can directly upload this src Yes, if the backend needs you to convert this picture into a file and upload it, then you need the next step.

Step 2: Convert the base64 image into a file object:

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 });
},

This function requires two parameters. The first parameter is the base64 data of the picture, and the second is the name of the file. It will return a File object, which can be sent to the backend.

Guess you like

Origin blog.csdn.net/brilliantSt/article/details/123664177