js获取视频缩略图

原理:

播放视频,canvas截图,base64转文件

播放视频:input file选择文件,video播放视频

<video id="videoPlayer" controls="controls" style="width:100%;max-height:400px;">
</video>

用户选择了本地视频文件后,设置video的src属性

var video = this.$refs.fileInput.files[0];
var url = URL.createObjectURL(video);
console.log(url);
document.getElementById("videoPlayer").src=url;

截图:

vue的script中

    creatImg:function() {
      const video = document.getElementById('videoPlayer');
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      const imgHeight = video.videoHeight;
      const imgWidth = video.videoWidth;
      ctx.drawImage(video, 0, 0, imgWidth*0.2, imgHeight*0.2);
     
      this.imgSrc = canvas.toDataURL('image/png');
     
      // console.log('imgSrc ' + imgHeight + ' ' + imgWidth)
      // console.log(this.imgSrc);

      var blob = this.dataURLtoBlob(this.imgSrc, "image/png")//base64转blob,全局函数
      var file = new File([blob], "video_image.png", { type: "image/png", lastModified: Date.now() })//blob转file

      return file
    }, 

globalFunc.js中,此js再main.js中引用,不一定非得这么写,只是比较通用的函数没必要每个vue中都写一遍,由此到处

到处全局函数

exports.install = function(Vue, option){

    Vue.prototype.dataURLtoBlob = function (dataURI,type) {
        var binary = atob(dataURI.split(',')[1]);
        var array = [];
        for(var i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i));
        }
        return new Blob([new Uint8Array(array)], {type:type});
    }

}

 

main.js中

import globalFunc from '@/components/globalFunc'

Vue.use(globalFunc)

由此,通过creatImg可以获得视频播放时的一帧,然后生成文件,此文件和input file选择的文件一样,可以通过format-data类型的post传输

缺点:video必须播放,不过设置visibility: hidden属性后用户就看不出来了

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值