Angular4+ 实现

压缩服务封装

import{Injectable,Renderer2}from'@angular/core';@Injectable()exportclassImageCompressService{maxSize=500*1000;constructor(privaterenderer:Renderer2){}read(file:File){returnnewPromise((resolve,reject)=>{constreader=newFileReader();reader.readAsDataURL(file);reader.onload=function(){resolve(reader.result);};});}compress(imageDataUrlSource:any,render:Renderer2,ratio?:number,quality?:number):Promise<string>{ratio=ratio?ratio:1;quality=quality?quality:0.5;returnnewPromise((resolve,reject)=>{constsourceImage=newImage();// important for safari: we need to wait for onload eventsourceImage.onload=function(){constcanvas:HTMLCanvasElement=render.createElement('canvas');constctx:CanvasRenderingContext2D=canvas.getContext('2d');canvas.width=sourceImage.naturalWidth*ratio;canvas.height=sourceImage.naturalHeight*ratio;ctx.drawImage(sourceImage,0,0,canvas.width,canvas.height);constmime=imageDataUrlSource.substr(5,imageDataUrlSource[0].length);// TODO test on mimeconstresult=canvas.toDataURL('image/jpeg',quality);resolve(result);};sourceImage.src=imageDataUrlSource;});}convertBase64UrlToBlob(urlData):Blob{constarr=urlData.split(',');constmime=arr[0].match(/:(.*?);/)[1];constbstr=atob(arr[1]);letn=bstr.length;constu8arr=newUint8Array(n);while(n--){u8arr[n]=bstr.charCodeAt(n);}returnnewBlob([u8arr],{type:mime});}do(file:File){if(file.size>this.maxSize){constquality=this.maxSize/file.size;returnnewPromise((resolve,reject)=>{this.read(file).then(srcData=>{this.compress(srcData,this.renderer,1,quality).then(value=>{resolve(this.convertBase64UrlToBlob(value));});});});}else{returnnewPromise((resolve,reject)=>{resolve(file);});}}}