[js] 使用js写一个图片压缩的小工具

93 阅读2分钟

"[js] 使用js写一个图片压缩的小工具

在前端开发中,经常会遇到需要压缩图片的场景,以提高网页加载速度和用户体验。下面是使用JavaScript编写一个简单的图片压缩工具的示例代码。

// 定义压缩函数
function compressImage(file, maxWidth, maxHeight, quality) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    // 加载图片
    img.src = URL.createObjectURL(file);
    img.onload = function () {
      let targetWidth = img.width;
      let targetHeight = img.height;

      // 根据最大宽度和最大高度计算目标尺寸
      if (targetWidth > maxWidth) {
        targetWidth = maxWidth;
        targetHeight = (targetWidth / img.width) * img.height;
      }
      if (targetHeight > maxHeight) {
        targetHeight = maxHeight;
        targetWidth = (targetHeight / img.height) * img.width;
      }

      // 设置canvas尺寸
      canvas.width = targetWidth;
      canvas.height = targetHeight;

      // 绘制压缩后的图片
      ctx.clearRect(0, 0, targetWidth, targetHeight);
      ctx.drawImage(img, 0, 0, targetWidth, targetHeight);

      // 将canvas转换为Blob对象
      canvas.toBlob(
        (blob) => {
          resolve(blob);
        },
        file.type || 'image/jpeg',
        quality
      );
    };

    img.onerror = function () {
      reject(new Error('Failed to load image'));
    };
  });
}

// 使用示例
const fileInput = document.getElementById('fileInput');
const compressButton = document.getElementById('compressButton');

compressButton.addEventListener('click', async () => {
  const file = fileInput.files[0];
  if (file) {
    try {
      const compressedBlob = await compressImage(file, 800, 600, 0.8);
      // 在此处可以将compressedBlob上传到服务器或者进行其他操作
      console.log('压缩后的图片Blob对象:', compressedBlob);
    } catch (error) {
      console.error('压缩图片出错:', error);
    }
  } else {
    console.error('请选择要压缩的图片');
  }
});

以上代码定义了一个compressImage函数,该函数接受一个图片文件对象、最大宽度、最大高度和压缩质量作为参数,并返回一个Promise对象。在函数内部,通过创建一个Image对象来加载图片,然后根据最大宽度和最大高度计算目标尺寸,并使用canvas绘制压缩后的图片。最后,将canvas转换为Blob对象,以便进行上传或其他操作。

在使用示例中,我们监听了一个文件输入框和一个压缩按钮的点击事件。当点击压缩按钮时,获取文件输入框中选择的文件,然后调用compressImage函数进行图片压缩。压缩完成后,可以将压缩后的Blob对象上传到服务器或者进行其他操作。

这只是一个简单的图片压缩工具示例,实际应用中还可以根据需求进行进一步的优化和功能扩展。"