Vue 截取视频第一帧作为封面图 然后转成base64,base64转成图片

场景:业务中上传视频之后展示视频的时候视频上需要有一张封面图

标签vedio中的poster 属性规定视频下载时显示的图像,或者在用户点击播放按钮前显示的图像

目标:

 <video
 controls
 :poster="CoverImg">
<source :src="item.FileUrl" type="video/mp4" />
 您的浏览器不支持 HTML5 video 标签。
</video>

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

    // 截取视频第一帧作为封面图 然后转成base64
    getVideoBase64(url) {
      return new Promise(function (resolve) {
        let dataURL = "";
        const video = document.createElement("video");
        video.setAttribute("crossOrigin", "anonymous"); // 处理跨域
        video.setAttribute("src", url);
        video.setAttribute("preload", "auto");
        video.addEventListener("loadeddata", function () {
          const canvas = document.createElement("canvas");
          console.log("video.clientWidth", video.videoWidth); // 视频宽
          console.log("video.clientHeight", video.videoHeight); // 视频高
          const width = video.videoWidth || 400; // canvas的尺寸和图片一样
          const height = video.videoHeight || 240; // 设置默认宽高为  400  240
          canvas.width = width;
          canvas.height = height;
          canvas.getContext("2d").drawImage(video, 0, 0, width, height); // 绘制canvas
          dataURL = canvas.toDataURL("image/jpeg"); // 转换为base64
          resolve(dataURL);
        });
      });
    },

base64转成图片文件

 // base64转图片
    getFileFromBase64(base64URL, filename) {
      var arr = base64URL.split(","),
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: "image/png" });
    },

上传视频

 <input
                  type="file"
                  v-show="inputShow"
                  ref="inputImg"
                  @change="preview($event)"
                />

具体过程

 preview(event) {
      var file = event.target.files[0];
      let ContentType;
      console.log(file);
      if (file.type.includes("image")) {
        ContentType = "image";
      } else if (file.type.includes("application")) {
        ContentType = "file";
      } else if (file.type.includes("video")) {
        ContentType = "video";
      } else {
        ContentType = "file";
      }
      const fd = new FormData(); // FormData 对象
      fd.append("Files", file); // 文件对象
       //拿到视频文件请求后端接口
      uploads(fd).then(async (res) => {
        if (res.Code == "0") {
            //如果文件类型是video就进行转化
          if (ContentType == "video") {
           //截取视频第一帧
            const vedioUrl = await this.getVideoBase64(res.Urls[0]);
            // 拿到视频第一帧的base64图片转成图片文件
            const imgUrl = await this.getFileFromBase64(vedioUrl, "kefu.jpeg");
            const fd1 = new FormData();
            //拿到图片文件请求后端接口返回链接
            fd1.append("Files", imgUrl);
            // 封面图
            this.CoverImg = await uploads(fd1);
            console.log("this.CoverImg", this.CoverImg);
          }
}

猜你喜欢

转载自blog.csdn.net/weixin_45308405/article/details/127392250