乐趣区

关于javascript:js截取video视屏画面帧

留神视频必须播放能力截取到视频帧作为封面,能够监听播放进度来截取封面。不播放截取进去是黑屏,你能够监听 vedio 的 timeupdate 事件在事件处理中去实现截图。另外留神讲 vedio 标签的 crossOrigin 属性设置为 ”anonymous”,避免跨域无奈截取

/**
 *@desc: base64 转 blob
 *@param {WindowBase64} dataURI base64
 *@return {Blob}
 */
export const dataURItoBlob = (dataURI: string) => {const byteString = atob(dataURI.split(',')[1]);
  const ab = new ArrayBuffer(byteString.length);
  const ia = new Uint8Array(ab);
  for (var i = 0; i < byteString.length; i++) {ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ia], {type: 'image/png'});
};

/**
 *@desc: blob 转文 件对象
 *@param {Blob} newBlob blob 格式文件
 *@param {String} fileName 文件名
 *@param {String} fileType 文件类型
 *@return {File}
 */
export const blobToFile = (
  newBlob: Blob,
  fileName: string,
  fileType: string = 'image/png',
) => {return new File([newBlob], fileName, {
    type: fileType,
    lastModified: Date.now(),});
};

/**
 *@desc: base64 转 file
 *@param {String} src 图片 base64
 *@param {String} fileName 文件名
 *@return {void}
 */
export const dataURIToFile = (src: string, fileName: string) => {const blob = dataURItoBlob(src);
  const file = blobToFile(blob, fileName);
  return file;
};

/**
 *@desc: 截取 video 画面帧 返回截取的图片(File 文件对象格局以及 base64 格局)(试验后果必须在视频播放之后截取胜利才有保障)
 *@param {HTMLVideoElement} video video 标签节点
 *@param {String} fileName 文件名
 *@param {string} imageType 图片格式
 *@return {Object<{ file: File, src: WindowBase64}>} res={file, src} 后果对象 file 是图片文件对象格局 src base64 图片格式
 */
export const captureVideoPoster = (
  video: HTMLVideoElement,
  fileName: string,
  imageType = 'image/png',
) => {if (!video) return;
  const width = video.videoWidth;
  const height = video.videoHeight;
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
  canvas.width = width;
  canvas.height = height;
  ctx.drawImage(video, 0, 0, width, height);
  const src = canvas.toDataURL(imageType);
  const file = dataURIToFile(src, fileName);
  return {
    src,
    file,
  };
};
退出移动版