vue使用canvas截取視頻第一幀作為封面圖,并且上傳阿里云OSS

引入阿里OSS

import { client } from '@/utils/common.js'
//common.js
import OSS from 'ali-oss'
export const client = new OSS({
  bucket: 'tthunter',
  accessKeyId: 'XXXXXXXXX',
  accessKeySecret: 'XXXXXXXXX',
  endpoint: 'XXXXXXXXX.aliyuncs.com',
  region: 'XXXXXXXXX',
  cname: true,
  secure: true,
})

a-upload自定義上傳

customRequest(action) {
      const file = action.file
      let fileName = this.resetName(file)
      client.put(fileName, file).then((res) => {
          //打印視頻上傳到阿里云OSS后的鏈接
          console.log(res.url)
          //使用本地上傳的視頻來獲取第一幀
          this.findVideoPoster(file).then((ret) => {
              //打印封面圖鏈接
              console.log(ret)
            })
        }).catch(() => {})
}

文件上傳時重命名

resetName(file) {
      let ftype = file.type.substring(file.type.lastIndexOf('/') + 1)
      return (String(new Date().getTime()) + parseInt(Math.random() * 100000) + '.' + ftype)
}

獲取視頻第一幀作為封面,file為antdv上傳組件上傳的視頻

findVideoPoster(file) {
      let self = this
      return new Promise(function(resolve) {
        let base64URL = ''
        let video = document.createElement('video')
        video.setAttribute('crossOrigin', 'anonymous') //處理跨域
        video.setAttribute('src', URL.createObjectURL(file))
        video.currentTime = 1
        video.addEventListener('loadeddata', function() {
          let canvas = document.createElement('canvas')
          //使用視頻的寬高作為canvas、預覽圖的寬高
          let width = video.videoWidth 
          let height = video.videoHeight
          canvas.width = width
          canvas.height = height
          canvas.getContext('2d').drawImage(video, 0, 0, width, height) //繪制canvas
          base64URL = canvas.toDataURL('image/jpeg') //轉換為base64,圖片格式默認為png,這里修改為jpeg
          let fileName = String(new Date().getTime()) + parseInt(Math.random() * 100000) + '.jpeg'
          const imgfile = self.data64toFile(base64URL)
          client.put(fileName, imgfile).then((res) => {
              resolve(res.url)
            }).catch((err) => {
              resolve('')
            })
        })
      })
}

base64轉Blob

data64toFile(base64URL) {
      const arr = base64URL.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
}
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容