useVideoThumbnail.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import {ref} from 'vue'
  2. function getFileFromBase64(base64URL, filename) {
  3. var arr = base64URL.split(","),
  4. bstr = atob(arr[1]),
  5. n = bstr.length,
  6. u8arr = new Uint8Array(n);
  7. while (n--) {
  8. u8arr[n] = bstr.charCodeAt(n);
  9. }
  10. return new File([u8arr], filename.split(".")[0]+".png", { type: "image/png" });
  11. }
  12. /**
  13. * 获取视频的第一帧图片
  14. */
  15. export function useVideoThumbnail(){
  16. console.log('执行到了')
  17. const screenshot = ref()
  18. const videoDom = document.createElement('video')
  19. videoDom.setAttribute('crossOrigin', 'anonymous') //处理跨域 必须添加 否则 toDataURL toBlob 不生效
  20. videoDom.setAttribute('src', 'https://jtzx001.oss-accelerate.aliyuncs.com/huijiaoyan_test/20260114_50007/14091714_b39124aa-2380-4547-af97-06159fcf6e40.mp4')
  21. videoDom.currentTime = 1
  22. // document.body.appendChild(videoDom)
  23. console.log('视频元素',videoDom)
  24. videoDom.addEventListener('loadeddata',function(){
  25. console.log('加载了')
  26. let canvas = document.createElement('canvas')
  27. //使用视频的宽高作为canvas、预览图的宽高
  28. let width = videoDom.videoWidth
  29. let height = videoDom.videoHeight
  30. canvas.width = width
  31. canvas.height = height
  32. console.log('画布宽度',width)
  33. console.log('画布高度',height)
  34. canvas?.getContext('2d')?.drawImage(videoDom, 0, 0, width, height) //绘制canvas
  35. let base64URL = canvas.toDataURL('image/jpeg') //转换为base64,图片格式默认为png,这里修改为jpeg
  36. // blob链接
  37. canvas.toBlob((blob)=>{
  38. let url = URL.createObjectURL(blob)
  39. screenshot.value = url
  40. })
  41. // base64链接
  42. // screenshot.value = base64URL
  43. // const imgfile = getFileFromBase64(base64URL,'截图.jpg')
  44. // console.log('获取到的文件----',imgfile)
  45. })
  46. return screenshot
  47. }