相信很多人前端在上传图片时,为了优化性能,都会做一个图片压缩的功能,这里提供一段压缩代码,采用ES6标准书写。希望大家采纳指点。
html代码:
<html> <body> <div class="form-upload">
<input type="file" name="logo" hidden="hidden" accept="image/*" />
</div>
</body>
</html>
js代码:
/** * @file CompressImg * @author (zhangx@nsw88.com) * @param file 需要压缩的图片流 * @param ratio 单次压缩率 * @param maxSize 压缩最大极限 */ class Compress { constructor(file, ratio = 0.6, maxSize = 100*1024){ this.time = 0; //压缩次数 this.file = file; this.ratio = ratio; this.maxSize = maxSize; this.reader = new FileReader(); } async init(){ let {file} = this; if( this.file.size > this.maxSize){ this.time++; this.file = await this.compressing(file); } //此处实现递归压缩,但是图片多次压缩后破损,暂时实现压缩一次,后期再改动 if( this.file.size > this.maxSize && this.time < 1){ this.file = await this.init() } else { return this.file; } } async compressing(file){ //图片压缩方法 let bold = await new Promise((resolve, reject)=>{ this.reader.onload = e =>{ var src = e.target.result; resolve(this.canvasData(src)) } this.reader.onerror = err => { reject(err) }; this.reader.readAsDataURL(file); }); return bold; } async canvasData(src){ //绘制canvas图片,输出压缩图片流 let path = src, bold = null; bold = await new Promise((resolve, reject) => { var img = new Image(); img.src = path; img.onload = e => { let {width,height} = e.target; let canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d'); canvas.width = width; canvas.height = height; ctx.drawImage(e.target, 0, 0, width,height); canvas.toBlob(blob => { resolve(blob) }, "image/jpeg", this.ratio); } }) return bold; } } export default Compress; //压缩调 var file = document.querySelector('.form-upload input').files[0]; 用let cfile= await new Compress(file).init();