使用canvas获取视频某一秒做封面,解决黑屏问题

实现上传视频后,截图视频的某一秒当封面

主要技术要点,使用canvas的 drawImage 方法,在把获取到的资源使用toDataURL转成base64格式
监听视频的 onerror 方法,解决了有些视频如果截取第一帧时,可能是黑屏问题

<body>
    <h3>上传视频后截取视频图片</h3>
    <input id="videoUpload" type="file" accept="video/*" />
</body>
let videoEle = document.querySelector("#videoUpload");
    videoEle.addEventListener("change", () => {
      getVideoImage(
        URL.createObjectURL(videoEle.files[0]),
        (img, time) => {
          document.body.appendChild(img);
          console.log(img, time);
        },
        3
      );
});

/**
 * 获取封面第一帧及时长
 * path 路径
 * callback 回调
 * secs 在第几秒开始截取
 */
function getVideoImage(path, callback, secs = 1) {
  var me = this,
    video = document.createElement("video");
  video.onloadedmetadata = function() {
    if ("function" === typeof secs) {
      secs = secs(this.duration);
    }
    this.currentTime = Math.min(
      Math.max(0, (secs < 0 ? this.duration : 0) + secs),
      this.duration
    );
  };
  video.onseeked = function(e) {
    var canvas = document.createElement("canvas");
    canvas.height = video.videoHeight;
    canvas.width = video.videoWidth;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    var img = new Image();
    img.src = canvas.toDataURL();
    callback.call(me, img, this.currentTime, e);
  };
  video.onerror = function(e) {
    callback.call(me, undefined, undefined, e);
  };
  video.src = path;
}
/**
 * Base64 转 Blob对象
 * @param dataURI
 * @returns {Blob}
 */
function dataURItoBlob(dataURI) {
  // convert base64/URLEncoded data component to raw binary data held in a string
  let byteString;
  if (dataURI.split(",")[0].indexOf("base64") >= 0) {
    byteString = atob(dataURI.split(",")[1]);
  } else {
    byteString = unescape(dataURI.split(",")[1]);
  }

  // separate out the mime component
  let mimeString = dataURI
    .split(",")[0]
    .split(":")[1]
    .split(";")[0];

  // write the bytes of the string to a typed array
  let ia = new Uint8Array(byteString.length);
  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  return new Blob([ia], {
    type: mimeString,
  });
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值