图片压缩
changeFile() {var that = this;var Files = document.getElementById('file').files[0];this.uploadSectionFile(Files);
},
uploadSectionFile(f) { // 附件上传let that &#61; this;let Orientation;let ndata;let url;if (f.size <&#61; 1 * 1024 * 1024) {//判断图片是否大于1M,是就直接上传ndata &#61; f;that.uploadimg &#61; ndata;that.show &#61; true;} else {//反之压缩图片let reader &#61; new FileReader();// 将图片2将转成 base64 格式reader.readAsDataURL(f);// 读取成功后的回调reader.onloadend &#61; function () {let result &#61; this.result;let img &#61; new Image();img.src &#61; result;img.onload &#61; function () {ndata &#61; that.compress(img, Orientation);that.uploadimg &#61; ndata;that.show &#61; true;that.imgurl &#61; ndata.substring(ndata.indexOf(&#39;base64,&#39;) &#43; 7, ndata.length);}}}
},
compress(img, Orientation) {let canvas &#61; document.createElement("canvas");let ctx &#61; canvas.getContext(&#39;2d&#39;);//瓦片canvaslet tCanvas &#61; document.createElement("canvas");let tctx &#61; tCanvas.getContext("2d");let initSize &#61; img.src.length;let width &#61; img.width;let height &#61; img.height;//如果图片大于四百万像素&#xff0c;计算压缩比并将大小压至400万以下let ratio;if ((ratio &#61; width * height / 4000000) > 1) {ratio &#61; Math.sqrt(ratio);width /&#61; ratio;height /&#61; ratio;} else {ratio &#61; 1;}canvas.width &#61; width;canvas.height &#61; height;//铺底色ctx.fillStyle &#61; "#fff";ctx.fillRect(0, 0, canvas.width, canvas.height);//如果图片像素大于100万则使用瓦片绘制let count;if ((count &#61; width * height / 1000000) > 1) {count &#61; ~~(Math.sqrt(count) &#43; 1); //计算要分成多少块瓦片// 计算每块瓦片的宽和高let nw &#61; ~~(width / count);let nh &#61; ~~(height / count);tCanvas.width &#61; nw;tCanvas.height &#61; nh;for (let i &#61; 0; i }