2 回答

TA貢獻1818條經(jīng)驗 獲得超8個贊
你這個壓縮圖片有問題
你this.compress(vm.temp.base64Img);傳入的是base64格式的字符串
canvas.width = img.width; canvas.height = img.height;這里base64格式的字符串是獲取不到寬高的
這句canvas.toDataURL("image/jpeg", 0.15)你之前沒有把圖片畫到canvas上所以的canvas上是空的
callback:
compress(base64img,callback) {
var img = new Image();
img.src = base64img;
img.onload = function(){
var width = img.width;
var height = img.height;
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(img,0,0,width,height);
callback(canvas.toDataURL("image/jpeg", 0.15))
}
}
//調(diào)用
vm.compress(vm.temp.base64img, function (base64img) {
uploadImage({ base64img }).then(response => {
const data = response.data;
//...
});
});
promise:
function compress(base64img, callback) {
return new Promise(function (resolve) {
var img = new Image();
img.src = base64img;
img.onload = function () {
var width = img.width;
var height = img.height;
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(img, 0, 0, width, height);
resolve(canvas.toDataURL("image/jpeg", 0.15))
}
})
}
//調(diào)用
vm.compress(vm.temp.base64img)
.then(base64img => uploadImage({ base64img }))
.then(response => {
const data = response.data;
//...
});

TA貢獻1719條經(jīng)驗 獲得超6個贊
很感謝李十三大神的幫忙,現(xiàn)在附上正確的代碼
uploadImg() {
let vm = this;
console.log(vm.temp);
var img = document.getElementById("phoneImage"),
maxSize = 400 * 1024; //400kb
var imgFile = new FileReader();
imgFile.readAsDataURL(img.files[0]);
imgFile.onload = function() {
vm.temp.base64Img = imgFile.result;
if (vm.temp.base64Img.length < maxSize) {
//圖片直接上傳
alert("<=100kb;size=" + vm.temp.base64Img.length);
uploadImage(vm.temp).then(response => {
const data = response.data;
vm.temp = data.data;
setTimeout(() => {
vm.$router.push({
path: "/setting"
});
window.location.reload();
}, 5);
});
} else {
// >400kb,壓縮再上傳
vm.compress(vm.temp.base64Img, function(base64Img) {
uploadImage({ base64Img }).then(response => {
const data = response.data;
setTimeout(() => {
vm.$router.push({
path: "/setting"
});
window.location.reload();
}, 5);
});
});
}
};
},
compress(base64Img, callback) {
var img = new Image();
img.src = base64Img;
img.onload = function() {
var width = img.width;
var height = img.height;
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(img, 0, 0, width, height);
callback(canvas.toDataURL("image/jpeg", 0.05));
};
}
添加回答
舉報