参考地址内容:https://my.oschina.net/odetteisgorgeous/blog/3186737
参考地址内容:https://zhuanlan.zhihu.com/p/87313900
<template>
<div class="videoDiv">
<video class="video" src="./video1.mp4" autoplay controls='controls'></video>
<button @click="snapshot">截图</button>
<div>
<img v-if="imgUrl" :src="imgUrl" alt="" class="img" id="imgId">
</div>
<button v-if="imgUrl" @click="downloadImage">下载</button>
<canvas style="display:none;width:600px;height:400px;"></canvas>
</div>
</template>
<script>
export default {
data () {
return {
imgUrl: ''
}
},
mounted () {
},
methods: {
// 截图下载
downloadImage() {
var a = document.createElement('a');
a.setAttribute('href', this.imgUrl);
a.setAttribute('target', '_blank');
a.setAttribute('id', 'vid');
a.setAttribute('download', "image"+ (+new Date()) +".jpeg");
let canSupportDownload ='download'in a;
// 防止反复添加
if (document.getElementById('vid')) {
document.body.removeChild(document.getElementById('vid'));
}
if (canSupportDownload) {
document.body.appendChild(a);
a.click();
} else {
alert("不支持下载");
window.open(url);
}
},
// 点击截图
snapshot() {
var video = document.querySelectorAll("video")[0]; //获取前台要截图的video对象,
var canvas = document.querySelectorAll('canvas')[0]; //获取前台的canvas对象,用于作图
var w = parseInt(window.getComputedStyle(video).width);
var h = parseInt(window.getComputedStyle(video).height);
// 为了将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了
canvas.width = w * 4;
canvas.height = h * 4;
canvas.style.width = w + "px";
canvas.style.height = h + "px";
var ctx = canvas.getContext('2d'); //设置canvas绘制2d图,
ctx.drawImage(video, 0, 0, canvas.width, canvas.height); //将video视频绘制到canvas中
// jpeg canvas.toDataURL('image/jpeg', 1)
var images = canvas.toDataURL('image/png'); //canvas的api中的toDataURL()保存图像
// console.log(images)
this.imgUrl = images
let blob = this.dataURLtoFile(this.imgUrl)
// 文件file
console.log(blob)
//再包装一下
let formData = new FormData();
formData.set("file", blob);
},
//base64转化为blob
dataURItoBlob(base64Data) {
var byteString;
if(base64Data.split(',')[0].indexOf('base64') >= 0)
byteString = atob(base64Data.split(',')[1]);
else{
byteString = unescape(base64Data.split(',')[1]);
}
var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
var ia = new Uint8Array(byteString.length);
for(var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob([ia], {
type: mimeString
});
return blob;
},
// 生成为文件类型
dataURLtoFile(dataurl, filename) {
let arr = dataurl.split(',')
let mime = arr[0].match(/:(.*?);/)[1];
if(!filename) {//若无文件名则取当前时间戳
filename = Date.parse(new Date()) + '.png';
}
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
},
}
}
</script>
<style scoped>
.video {
width: 600px;
height: 400px;
}
.img {
width: 600px;
/* height: 400px; */
}
</style>