js はビデオの最初のフレームをカバーとしてキャプチャします

要件:ビデオをアップロードするとき、フロントエンドでカバー画像をアップロードする必要がある場合があります。通常、ビデオの最初のフレームがビデオのカバー画像として取得されます。解決策
:

ステップ 1:ビデオの最初のフレームをキャプチャし、キャンバスを使用して画像を描画します (デフォルトでは、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 をアップロードできる場合は、このソースを直接アップロードできます。はい、バックエンドでこの画像をファイルに変換してアップロードする必要がある場合は、次のステップが必要です。

ステップ 2: Base64 イメージをファイル オブジェクトに変換します。

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

この関数には 2 つのパラメータが必要です。最初のパラメータは画像の Base64 データで、2 番目のパラメータはファイルの名前です。バックエンドに送信できる File オブジェクトを返します。

おすすめ

転載: blog.csdn.net/brilliantSt/article/details/123664177
おすすめ