这两天在做移动端上传头像功能,想对大于400kb的图片进行压缩再上传,压缩大于400kb的图片一直没成功,也没有报什么错误,后来我重新看了自己的代码,发现是因为当图片大小大于400kb的时候,压缩图片函数传入的base64Img参数我写错了,真的是太粗心,现在将正确的代码附上:uploadImg(){letvm=this;console.log(vm.temp);varimg=document.getElementById("phoneImage"),maxSize=400*1024;//400kbvarimgFile=newFileReader();imgFile.readAsDataURL(img.files[0]);imgFile.onload=function(){vm.temp.base64Img=imgFile.result;if(vm.temp.base64Img.length{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));};}
2 回答
素胚勾勒不出你
TA贡献1827条经验 获得超9个赞
你这个压缩图片有问题你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;//...});
添加回答
举报
0/150
提交
取消