ionic 压缩图片

ionic 压缩图片

通过降低图片分辨率和画质压缩图片。

基础函数

通过 url 读取图片。

readImg(path: string): Promise<HTMLImageElement> {
  return new Promise((resolve, reject) => {
    // ionic3
    const url = normalizeURL(path);
    // ionic4
    const url = (window as any).Ionic.WebView.convertFileSrc(path);

    let img = new Image();
    img.crossOrigin = 'anonymous';
    img.onload = () => {
      resolve(img);
      img = null;
    };
    img.onerror = () => {
      reject(`圖片加載失敗:${url}`);
      img = null;
    };
    img.src = url;
  });
}
复制代码

dataURL 转 Blob

  dataURLtoBlob(dataURL: string): Blob {
    const arr = dataURL.split(',');
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);

    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }

    const type = arr[0].match(/:(.*?);/)[1];
    return new Blob([u8arr], { type });
  }
复制代码

压缩图片

  async imageResizer(
    source: any,
    parame?: {
      quality?: number;
      resultType?: 'blob' | 'dataURL';
      maxSize: number;
    }
  ): Promise<any> {
    let path: string;

    const options = {
      quality: 0.9,
      resultType: 'blob',
      maxSize: 480
    };

    Object.assign(options, parame);

    if (source instanceof Blob) {
      path = await this.blobToDataURL(source);
    } else {
      path = source;
    }

    let img = await this.readImg(path);

    let targetWidth: number;

    let targetHeight: number;

    // 图片比例
    const ratio = img.width / img.height;

    targetWidth = img.width > options.maxSize ? options.maxSize : img.width;

    targetHeight = +(targetWidth / ratio).toFixed(0);

    let canvas = <HTMLCanvasElement>document.createElement('CANVAS'),
      ctx = canvas.getContext('2d');

    canvas.width = targetWidth;
    canvas.height = targetHeight;

    ctx.clearRect(0, 0, targetWidth, targetHeight);
    // 图片压缩
    ctx.drawImage(img, 0, 0, targetWidth, targetHeight);

    // 检测有没有透明数据
    const imageData = ctx.getImageData(0, 0, targetWidth, targetHeight).data;
    let isAlphaBackground = false;
    let length = imageData.length;
    for (let index = 3; index < length; index += 4) {
      if (imageData[index] !== 255) {
        isAlphaBackground = true;
        break;
      }
    }

    // 透明為png、不透明轉換成jng
    const type = isAlphaBackground ? 'image/png' : 'image/jpeg';

    const dataURL = canvas.toDataURL(type, options.quality);
    canvas = img = ctx = null;

    if (options.resultType === 'blob') {
      return this.dataURLtoBlob(dataURL);
    } else {
      return dataURL;
    }
  }
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值