canvas得到base64图片:
getVideo () {
// 获取上传文件标签
let filesId = document.getElementById('videoupload')
// 获取音频标签
let video = document.getElementById('video')
this.fileDetail = filesId.files
let url = this.getFileURL(filesId.files[0])
if (url) {
// 给video标签设置src
video.src = url
}
var canvas = document.getElementById('myCanvas') // 获取 canvas 对象
const ctx = canvas.getContext('2d') // 绘制2d
video.crossOrigin = 'anonymous' // 解决跨域问题,也就是提示污染资源无法转换视频
video.currentTime = 1 // 第一帧
video.oncanplay = () => {
canvas.width = video.clientWidth // 获取视频宽度
canvas.height = video.clientHeight // 获取视频高度
// 利用canvas对象方法绘图
ctx.drawImage(video, 0, 0, video.clientWidth, video.clientHeight)
console.log(canvas, 'canvas')
// 转换成base64形式
var oGrayImg = canvas.toDataURL('image/png') // 截取后的视频封面
this.videoImg = [oGrayImg]
//base64转成png格式图片文件
let name = this.fileDetail.name // 定义文件名字(例如:cober.png)
function dataURLtoFile (dataurl, filename = 'file') {
let arr = dataurl.split(',')
let mime = arr[0].match(/:(.*?);/)[1]
let suffix = mime.split('/')[1]
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}.${suffix}`, {
type: mime
})
}
var base64Img = oGrayImg // base64编码的图片
console.log(oGrayImg, 'oGrayImg')
var imgFile = dataURLtoFile(base64Img, name)
console.log('imgFile====>', imgFile)
//发送到服务器
var param = new FormData()
param.append('file', imgFile)
this.$axios
.post('http://192.168.3.12:8026/video_cover.php', param)
.then((res) => {
console.log('success')
console.log(res)
var resData = res.data
this.videoImg = [resData.data.url]
this.videoImgObj = resData.data
console.log(resData.data, 'obj', this.videoImgObj)
})
.catch((err) => {
console.log('failed', err)
})
}
},
getFileURL (file) {
let getUrl = null
if (window.createObjectURL !== undefined) {
getUrl = window.createObjectURL(file)
} else if (window.URL !== undefined) {
getUrl = window.URL.createObjectURL(file)
} else if (window.webkitURL !== undefined) {
getUrl = window.webkitURL.createObjectURL(file)
}
return getUrl
},