JS如何上传视频后从视频截图到一张封面Cover?

文章目录

    • 概要
    • 获取上传视频文件截图
    • 小结

概要

从上传视频文件中获取一张图片

获取上传视频文件截图

html片段,两个都是隐藏的


 <input type="file" style="display: none" id="file" ref="uploadVideo" accept="video/*"
                       @change="uploadVideoClick($event)"/>
 
 <canvas ref="canvas" style="display: none;">canvas>

js片段


  //截图第一帧转成/png图片
        const video = document.createElement('video');
        const canvas = this.$refs.canvas;
        const context = canvas.getContext('2d');

        video.src = URL.createObjectURL(file);
        video.addEventListener('loadedmetadata', () => {
          video.currentTime = 0; // 设置视频当前时间为第0秒
          video.addEventListener('seeked', () => {
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            context.drawImage(video, 0, 0, canvas.width, canvas.height);
            //base64转Blob
            const imgFile = dataURLtoFile(canvas.toDataURL('image/jpeg'))
            //上传封面
            const formData = new FormData()
            formData.append('file', imgFile) // 传入bpmn文件
            //后端上传封面的接口
            uploadCover(formData).then(res => {
              if (res.code === 200) {
                this.userInfo.coverImg = res.dataMap.url
              } else {
                meassageError(res.msg)
              }
            })
          });
        })

base64转Blob

export function 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});
}

小结

努力探索新技术

你可能感兴趣的:(javascript,音视频,前端)