美文网首页
js 根据视频URL获取视频封面

js 根据视频URL获取视频封面

作者: 伊路顺峰 | 来源:发表于2022-07-13 14:06 被阅读0次

在项目开发中有个需求:根据视频URL获取视频封面URL,目前已知视频URL,网上多数方法都是通过canvas获取base64 图片,不能完全满足我的需求,于是根据我将base64 转成Blob,再将Blob文件上传服务器获取到图片URL,封装成两个方法,在此记录一下,路过的同学拿走不谢。

将方法封装在Utils.ts 文件中作为静态方法:

static getVideoPoster(src: string): Promise<string> {
    return new Promise((resolve, reject) => {
      if (Utils.isEmpty(src)) return Promise.resolve("");
      let video = document.createElement("video");
      video.setAttribute("src", src);
      video.setAttribute("autoplay", "autoplay");
      video.setAttribute("crossOrigin", "anonymous"); //设置跨域 否则toDataURL导出图片失败
      video.setAttribute("width", "300"); //设置大小,如果不设置,下面的canvas就要按需设置
      video.setAttribute("height", "200");
      video.currentTime = 7; //视频时长,一定要设置,不然大概率白屏
      video.addEventListener("loadeddata", function () {
        let canvas = document.createElement("canvas"),
          width = video.width, //canvas的尺寸和图片一样
          height = video.height;
        canvas.width = width; //画布大小,默认为视频宽高
        canvas.height = height;
        canvas.getContext("2d").drawImage(video, 0, 0, width, height); //绘制canvas
        let dataURL = canvas.toDataURL("image/png"); //转换为base64
        const blob = Utils.transformBase64ToBlob(dataURL);

        let fm = new FormData();
        fm.append("files", blob, new Date().getTime() + ".png");
        //apiUploadFile是上传文件的方法,可使用自己项目中axios 上传文件的方法
        apiUploadFile(fm)
          .then((imgUrl) => {
          //imgUrl 是后台返回的图片URL
            resolve(imgUrl);
          })
          .catch((e) => {
            reject("");
          });
      });
    });
  }

  //将base64 转为Blod
  static transformBase64ToBlob(base64: string): Blob {
    let byteString: string = "";

    if (base64.split(",")[0].indexOf("base64") >= 0) {
      byteString = window.atob(base64.split(",")[1]);
    } else {
      byteString = window.unescape(base64.split(",")[1]);
    }

    const mimeString = base64.split(",")[0].split(":")[1].split(";")[0];
    const ia = new Uint8Array(byteString.length);
    for (let i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    const blob = new Blob([ia], {
      type: mimeString,
    });
    return blob;
  }

相关文章

网友评论

      本文标题:js 根据视频URL获取视频封面

      本文链接:https://www.haomeiwen.com/subject/cfxtirtx.html