最近写运营后台要实现一个功能,H5端上传的照片在运营后台查看会旋转90°,要实现一个编辑旋转后保存上传的功能。
<img :src="currentImg" id="picrota"></img>
<el-button @click="editPic(url)">编辑图片</el-button>
editPic(url){
this.downloadIamge(url)
},
base64ToFile(urlData, fileName) {
let arr = urlData.split(",");
let mime = arr[0].match(/:(.*?);/)[1];
let bytes = atob(arr[1]); // 解码base64
let n = bytes.length;
let ia = new Uint8Array(n);
while (n--) {
ia[n] = bytes.charCodeAt(n);
}
// console.log(urlData,fileName)
return new File([ia], fileName, { type: mime });
},
downloadIamge(imgSrc, name) {
//下载图片地址和图片名
var image = new Image();
// 解决跨域 Canvas 污染问题
image.setAttribute("crossOrigin", "anonymous");
var that = this
image.onload = function () {
var canvas = document.createElement("canvas");
console.log(document.getElementById("picrota").width,document.getElementById("picrota").height)
let line = document.getElementById("picrota").width>document.getElementById("picrota").height?document.getElementById("picrota").width:document.getElementById("picrota").height
console.log(line)
var width = document.getElementById("picrota").width
var height = document.getElementById("picrota").height
var w = that.deg % 180 == 0 ? width : height
var h = that.deg % 180 == 0 ? height : width
canvas.width = w;
canvas.height = h;
var context = canvas.getContext("2d");
context.translate(w/2, h/2);
context.rotate(that.deg * Math.PI / 180);
context.translate(-w/2, -h/2);
context.drawImage(image, w/2 - document.getElementById("picrota").width/ 2, h/2 - document.getElementById("picrota").height / 2, document.getElementById("picrota").width, document.getElementById("picrota").height);
var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
that.cro = that.base64ToFile(url,`avatar${new Date().getTime()}.jpg`);
that.picUpload(that.base64ToFile(url,`avatar${new Date().getTime()}.jpg`))
};
image.src = imgSrc;
},
picUpload(file) {
let param = new FormData(); // 创建form对象
param.append("file", file);
let config = {
headers: { "Content-Type": "multipart/form-data" },
};
this.$axios.post(this.uploadPath, param, config).then((res) => {
console.log(res)
}).catch(err => {
this.$message.error(err.msg || err)
});
},