web移动端对上传头像图片进行压缩,当图片过大的时候压缩不成功但是也没有报错

这两天在做移动端上传头像功能,想对大于400kb的图片进行压缩再上传,压缩大于400kb的图片一直没成功,也没有报什么错误,后来我重新看了自己的代码,发现是因为当图片大小大于400kb的时候,压缩图片函数传入的base64Img参数我写错了,真的是太粗心,现在将正确的代码附上:
uploadImg(){
letvm=this;
console.log(vm.temp);
varimg=document.getElementById("phoneImage"),
maxSize=400*1024;//400kb
varimgFile=newFileReader();
imgFile.readAsDataURL(img.files[0]);
imgFile.onload=function(){
vm.temp.base64Img=imgFile.result;
if(vm.temp.base64Img.length//图片直接上传
alert("<=100kb;size="+vm.temp.base64Img.length);
uploadImage(vm.temp).then(response=>{
constdata=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=>{
constdata=response.data;
setTimeout(()=>{
vm.$router.push({
path:"/setting"
});
window.location.reload();
},5);
});
});
}
};
},
compress(base64Img,callback){
varimg=newImage();
img.src=base64Img;
img.onload=function(){
varwidth=img.width;
varheight=img.height;
varcanvas=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));
};
}
翻阅古今
浏览 362回答 2
2回答

汪汪一只猫

你这个压缩图片有问题你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){varimg=newImage();img.src=base64img;img.onload=function(){varwidth=img.width;varheight=img.height;varcanvas=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))}}//调用vm.compress(vm.temp.base64img,function(base64img){uploadImage({base64img}).then(response=>{constdata=response.data;//...});});promise:functioncompress(base64img,callback){returnnewPromise(function(resolve){varimg=newImage();img.src=base64img;img.onload=function(){varwidth=img.width;varheight=img.height;varcanvas=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))}})}//调用vm.compress(vm.temp.base64img).then(base64img=>uploadImage({base64img})).then(response=>{constdata=response.data;//...});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript