//压缩图片
function compressImg(file) {
  let fileSize = parseFloat(parseInt(file['size']) / 1024 / 1024).toFixed(2);
  let read = new FileReader();
  read.readAsDataURL(file);
  return new Promise(function(resolve) {
    read.onload = function(e) {
      let img = new Image();
      img.src = e.target.result;
      img.onload = function() {
        //默认按比例压缩
        let w = this.width,
          h = this.height;
        //生成canvas
        let canvas = document.createElement('canvas');
        let ctx = canvas.getContext('2d');
        // 创建属性节点
        canvas.setAttribute('width', w);
        canvas.setAttribute('height', h);
        ctx.drawImage(this, 0, 0, w, h);
        let ratio = fileSize < 1 ? 0.95 : 0.85;
        canvas.toBlob(
          blob => {
            resolve(blob);
          },
          'image/jpeg',
          ratio
        );
      };
    };
  });
}
//结尾处将该方法暴露出来供外部调用
export default {
  compressImg
};
