Angular5中croppie图片裁剪以及 canvas图片压缩

关于croppie的图片裁剪工具的使用

裁剪图如下

 前端html: 
  <div id="crop-box"></div>
 用来盛放将会使用的裁剪区域
 
 基本用法(搭配angular5)
 1. 生成一个新的裁剪区域
 private newCroppie(data, height) {
    if (this.croppie) {
      this.destroyCroppie();
    }
    this.croppie = new Croppie(document.querySelector('#crop-box'), this.resizeCroppie(height));
    this.croppie.bind({
      url: data
    });
  }
  
 2. 裁剪区域的基本配置
   private resizeCroppie(height) {
    return this.resizeObj = {
      viewport: { width: 1200, height: this.value },
      boundary: { width: 1250, height: Number(this.value) + 50 },
      showZoomer: true,
      enableOrientation: true
    }
  }
  
 3. 获取裁剪的数据
   private getResult() {
    this.croppie.result({ type: 'rawcanvas' }).then((result) => {
      return this.compressImg(result, 1024)
    });
  }
  
 4. 销毁裁剪区域
   private destroyCroppie() {
    this.cropBarDisplay = false;
    this.croppie.destroy();
    this.croppie = null; //这个手动将整个裁剪区域为空,因为在ngOnChange周期使用的原因
  }
复制代码

关于canvas.toDataUrl(type, encoderOptions)去压缩图片的使用

  • 第一个参数是图片的类型
  • 注意:
  1. 这个类型不支持image/jpg,如果你将.jpg的进行转换成base64,他会直接将image的类型转换成image/jpeg.
  2. 如果你使用的的图片类型不属于MIME的范围,那么会直接转换成image/png
  • 第二个参数是针对图片质量压缩的比例,范围是(0-1)
  • 注意:
  1. 这个0到1的范围,并不是精确的比例,还要综合考虑图片的质量等因素
  2. 对于图片类型是image/png的图片是没办法进行图片压缩的,image/jpeg,image/webp是可以进行图片压缩的
  • 举个例子
private compressImg(canvasResult, size) {
    let imgBase64 = canvasResult.toDataURL('image/jpeg', 1);
    let base64Kilobyte = (imgBase64.length - 814) / 1.37 / 1024; //将base64的结果转换成kb
    let currentQuality = 1
    //通过循环 进行图片质量的压缩,直到小于规定的大小才停止
    if (base64Kilobyte > size) {
      for (let i = 10; i > 0; i--) {
        currentQuality -= 0.1;
        const quality = parseFloat((currentQuality).toFixed(2));
        imgBase64 = canvasResult.toDataURL('image/jpeg', quality);
        base64Kilobyte = (imgBase64.length - 814) / 1.37 / 1024;
        if (base64Kilobyte < size) {
          break;
        }
      }
    }
    return imgBase64;
  }
复制代码
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值