前端获取视频缩略图方式

发布时间 2023-03-26 14:37:06作者: 酸菜鱼没有鱼

代码示例:

/**
 * 获取缩略图
 * @param url 视频地址
 * @param currentTime 缩略图取第几秒的图片
 * @param width 截取的图片宽
 * @param height 截取的图片高
 * @returns {Promise<unknown>}
 */
export function getVideoFrameImage (url, currentTime = 3, width = 100, height = 100) {
  return new Promise((resolve, reject) => {
    const video = document.createElement('video')
    video.setAttribute('crossOrigin', 'anonymous')
    video.setAttribute('preload', 'metadata')
    video.setAttribute('src', url)
    // 视频开始可能是黑屏状态
    video.currentTime = currentTime
    video.addEventListener('loadeddata', function () {
      const canvas = document.createElement('canvas')
      const { videoWidth, videoHeight } = video
      const newHeight = height || videoHeight * (width / videoWidth)
      canvas.width = width
      canvas.height = newHeight
      canvas.getContext('2d').drawImage(video, 0, 0, 200, height)
      resolve(canvas.toDataURL('image/jpeg'))
    })
  })
}

//使用方式
getVideoFrameImage(url).then(res => {
    console.log('base64图片路径', res)       
})