Often we need to upload pictures manually or in other ways to first compress again to upload, we can not use external force pure front-end high quality picture compression?

Of course you can!

Let’s take a look at the original effect 1.26m

65.63 k after compression

In the code

<div class="picture"> <input type="file" Accept ="image/*" multiple@change="beforeUpload($event)"/> album </div>Copy the code

Files Input = 9 files input = 9 files Input = 9

async handle(files){ const fileList = []; for(let i = 0; i < files.length; i++){ if(i<9){ let item=files[i]; const base64Img = await this.getBase64(item); const compressImg = await this.compress(base64Img); fileList.push({ file: item.name, size: this.size(compressImg.length), img: compressImg, loading: True})}else{alert(' Send up to 9 pictures at a time! '); break; } } return fileList }Copy the code

Get base64 encoding implemented asynchronously with promise

getBase64(file){ return new Promise((resolve, reject) =>{ if(! / / /? : jpeg | JPG | PNG)/i.t est (file. Type)) {alert (' does not support the image type! '); return reject(); } let reader = new FileReader(); reader.onload = function(){ return resolve(this.result) }; reader.readAsDataURL(file); })}Copy the code

Use canvas compression to compress to 0.1 times mass, of course you can also cycle compression to smaller

compress(result){ return new Promise((resolve, reject) =>{ var image = new Image(); image.src = result; image.onload = function(){ var canvas = document.createElement("canvas"); Var context = canvas. GetContext ('2d'); canvas.width = image.width; canvas.height = image.height; context.drawImage(image, 0, 0, this.width, this.height); // Compress the original image to 0.1 times its original quality. Var dataURL = canvas.toDataURL('image/jpeg', 0.1); return resolve(dataURL) } }) }Copy the code

Image unit size algorithm

size(v){ 
    var unit = ["Byte", "KB", "M", "G", "T", "P", "E", "Z", "Y"];  
   var index = 0; 
    while(v >= 1000){       
      v = v / 1000;     
      index++;  
    }   
    return v.toFixed(2) + unit[index];
}
Copy the code
Compression done!