VUE文件压缩

/**
 * @name 文件压缩
 * @description
 *  1、将文件转img对象
 *  2、获取文件宽高比例
 *  3、自定义等比例缩放宽高属性,高度是等比例缩放
 *  4、canvas重新绘制图片
 *  5、canvas转二进制对象转文件对象,返回
 * @returns { File } 文件
 */
export async function imgCompress(file: any) {
  // 将文件转img对象
  const img = (await fileToImg(file)) as any;
  return new Promise((resolve, reject) => {
    const canvas = document.createElement('canvas');
    const context: CanvasRenderingContext2D | any = canvas.getContext('2d');
    // 获取文件宽高比例
    const { width: originWidth, height: originHeight } = img;
    // 自定义等比例缩放宽高属性,高度是等比例缩放
    const scale = +(originWidth / originHeight).toFixed(2); // 比例取小数点后两位)
    const targetWidth = 800; // 固定宽
    const targetHeight = Math.round(800 / scale); // 等比例缩放高

    canvas.width = targetWidth;
    canvas.height = targetHeight;
    context.clearRect(0, 0, targetWidth, targetHeight);
    // canvas重新绘制图片
    context.drawImage(img, 0, 0, targetWidth, targetHeight);
    // canvas转二进制对象转文件对象,返回
    const type = 'image/png';
    canvas.toBlob(function (blob: any) {
      const f = new File([blob], file.name, {
        type,
        lastModified: file.lastModified,
      });
      resolve(f);
    }, type);
  });
}

// file转换成img对象
function fileToImg(file: any) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    const reader = new FileReader();
    reader.onload = function (e: HTMLElement | any) {
      img.src = e.target.result;
    };
    reader.onerror = function (e) {
      reject(e);
    };
    reader.readAsDataURL(file);
    img.onload = function () {
      resolve(img);
    };
    img.onerror = function (e) {
      reject(e);
    };
  });
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值