JS Code block 代码块–图片压缩

星期一, 2023-04-17 | Author: Lee | computer, 前端 | 237 views

图片压缩

/**
 * 图片压缩
 * @param  {string}   file [压缩文件]
 * @param  {object}   obj [压缩参数]
 * @param  {function} cb   [回调函数]
 * @return {string}        [返回压缩前和压缩后的格式]
 */
/* istanbul ignore next */
function photoCompress(file, obj, cb) {
// obj = {
//    width: 图片宽,
//    height: 图片高,
//    quality: 图像质量,
//    blob: 是否转换成Blob
//  }
  // 将以base64的图片url数据转换为Blob
  function convertBase64UrlToBlob(urlData) {
    let arr = urlData.split(',');
    let mime = arr[0].match(/:(.*?);/)[1];
    let bstr = atob(arr[1]);
    let n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type: mime});
  }
 
  // canvas 绘制图片
  function canvasDataURL(oldBase64) {
    let img = new Image();
    img.src = oldBase64;
    img.onload = function () {
      let that = this;
      // 默认按比例压缩
      let w = that.width,
        h = that.height,
        scale = w / h;
      w = obj.width || w;
      h = obj.height || (w / scale);
      let quality = 0.7;  // 默认图片质量为0.7
      //生成canvas
      let canvas = document.createElement('canvas');
      let ctx = canvas.getContext('2d');
      // 创建属性节点
      let anw = document.createAttribute('width');
      anw.nodeValue = w;
      let anh = document.createAttribute('height');
      anh.nodeValue = h;
      canvas.setAttributeNode(anw);
      canvas.setAttributeNode(anh);
      ctx.drawImage(that, 0, 0, w, h);
      // 图像质量
      if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
        quality = obj.quality;
      }
      // quality值越小,所绘制出的图像越模糊
      let base64 = canvas.toDataURL('image/jpeg', quality);
      // 回调函数返回base64的值
      if (obj.blob) {
        cb && cb(convertBase64UrlToBlob(base64), convertBase64UrlToBlob(oldBase64))
      } else {
        cb && cb(base64, oldBase64);
      }
    }
  }
 
  // 读取图片的base64格式
  let ready = new FileReader();
  ready.readAsDataURL(file);
  ready.onload = function () {
    let re = this.result;
    canvasDataURL(re)
  }
}

Tags:

文章作者: Lee

本文地址: https://www.pomelolee.com/2373.html

除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址

No comments yet.

Leave a comment

Search

文章分类

Links

Meta