封装一个图片压缩函数

方法一

// Base64转file
function dataURLtoFile(dataurl, file) {
  const arr = dataurl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  // eslint-disable-next-line no-plusplus
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], file.name, { type: mime });
}

//  压缩图片 参数一:file对象,参数二:压缩图片质量,取值 0~1,默认0,5
export function compressImg(imgFile, quality = 0.5) {
  return new Promise((resolve, reject) => {
    const cvs = document.createElement('canvas');
    const ctx = cvs.getContext('2d');
    const filereader = new FileReader();
    filereader.readAsDataURL(imgFile);
    filereader.onload = e => {
      const img = new Image();
      img.src = e.target.result;
      img.onload = function () {
        cvs.width = this.width;
        cvs.height = this.height;
        ctx.drawImage(img, 0, 0, this.width, this.height);
        const dataURL = cvs.toDataURL(imgFile.type, quality);
        const file = dataURLtoFile(dataURL, imgFile);
        return resolve(file);
      };
      img.onerror = reject;
    };
  });
}

方法二:

// Base64转file
function dataURLtoFile(dataurl, file) {
  const arr = dataurl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  // eslint-disable-next-line no-plusplus
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], file.name, { type: mime });
}

//  压缩图片 参数一:file对象,参数二:压缩图片质量,取值 0~1,默认0,5
export function compressImg(imgFile, quality = 0.5) {
  return new Promise((resolve, reject) => {
    const cvs = document.createElement('canvas');
    const ctx = cvs.getContext('2d');
    const img = new Image();
    img.src = URL.createObjectURL(imgFile);
    img.onload = function () {
      cvs.width = this.width;
      cvs.height = this.height;
      ctx.drawImage(img, 0, 0, this.width, this.height);
      const dataURL = cvs.toDataURL(imgFile.type, quality);
      const file = dataURLtoFile(dataURL, imgFile);
      return resolve(file);
    };
    img.onerror = reject;
  });
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。