vue图片压缩成bse64转二进制流,并且更改文件名
created() {
//创建canvas
this.canvas = document.createElement('canvas')
this.context = this.canvas.getContext('2d')
},
//长传图片
onUplaod(e, index, type) {
let that = this
//创建img对象
let imgobj = new Image()
var reader = new FileReader()
// 上传图片拿到的文件流
const file = e.file
reader.readAsDataURL(file)
//准备好后
reader.onload = (e) => {
imgobj.src = e.target.result
//this.cutImg = e.target.result
}
reader.onerror = () => {
Toast("图片上传失败,麻烦稍后再试试~")
}
imgobj.onload = () => {
const originWidth = imgobj.width
const originHeight = imgobj.height
// 计算出目标压缩尺寸
var maxWidth = 1200, maxHeight = 1200;
// 目标尺寸
var targetWidth = originWidth, targetHeight = originHeight;
if (originWidth > maxWidth || originHeight > maxHeight) {
// 图片尺寸超过1200x1200的限制
if (originWidth / originHeight > maxWidth / maxHeight) {
// 更宽,按照宽度限定尺寸
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
that.canvas.width = targetWidth;
that.canvas.height = targetHeight;
// 清除画布
that.context.clearRect(0, 0, targetWidth, targetHeight);
// 图片压缩
this.context.drawImage(imgobj, 0, 0, targetWidth, targetHeight)
// base64文件流
let base64Code2 = this.canvas.toDataURL('image/jpeg', 1)
// base64转二进制流
let blob = this.dataURLtoBlob(base64Code2)
// 更改文件名
const newFileName = 'task.jpg'; // 新文件名
// 生成新的file对象
const file = new File([blob], newFileName, {
type: blob.type });
const param = {
file: file,
type: 'image',
group_id: 0
}
uploadFile(param).then((res) => {
this.$message({
message: '上传成功',
type: 'success'
})
// 请求后端接口拿到的图片
let imgurl = res.data.file_path
this.form.task_step[index][type].push(imgurl)
}).catch(error => {
})
}
},
// base64 转 二进制流(blob)
dataURLtoBlob(dataurl) {
var arr = dataurl.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {
type: mime,
});
},