JavaScript实现图片压缩

可以使用HTML5的Canvas元素和JavaScript来实现图片压缩。具体步骤如下:

  1. 将图片读取到一个Image对象中。
  2. 创建一个Canvas元素并将图片绘制到其中。
  3. 获取Canvas元素上的图像数据,并进行压缩处理。
  4. 将压缩后的图像数据重新绘制到Canvas元素中。
  5. 将Canvas元素中的图像转换为压缩后的Base64编码字符串或Blob对象。

以下是一个基本的示例代码:

function compressImage(file, maxWidth, maxHeight) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      const canvas = document.createElement('canvas');
      let width = img.width;
      let height = img.height;

      if (width > maxWidth) {
        height *= maxWidth / width;
        width = maxWidth;
      }

      if (height > maxHeight) {
        width *= maxHeight / height;
        height = maxHeight;
      }

      canvas.width = width;
      canvas.height = height;

      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0, width, height);

      canvas.toBlob(
        blob => {
          resolve(blob);
        },
        file.type,
        0.8 // 压缩质量,可以根据需要调整
      );
    };

    img.onerror = reject;

    img.src = URL.createObjectURL(file);
  });
}

这个函数接收一个File对象、最大宽度和最大高度作为参数,并返回一个Promise对象,该Promise对象在图片压缩完成后解析为Blob对象。可以使用这个函数来实现图片上传前的压缩处理。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值