碎片化学习前端之JavaScript(JS 压缩图片)

发布时间 2023-06-15 17:03:19作者: 深巷酒

前言

图片压缩是前端开发中常见的需求,目前前端主流的解决方案有:Canvas 手动实现压缩以及第三方库压缩两种方案。

Canvas 手动实现压缩

Canvas 实现压缩主要原理是:将图片绘制到 canvas 上,然后通过调整 canvas 的宽高来实现压缩。

function compressImage(file, maxWidth, maxHeight, quality) {
  return new Promise((resolve, reject) => {
  
    const reader = new FileReader();
    reader.readAsDataURL(file);
    
    reader.onload = function(event) {
	
      const img = new Image();
      img.src = event.target.result;
      // 图片加载完成以后再进行 canvas 绘制
      img.onload = function() {

        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        let width = img.width;
        let height = img.height;
        if (width > height) {
          if (width > maxWidth) {
            height *= maxWidth / width;
            width = maxWidth;
          }
        } else {
          if (height > maxHeight) {
            width *= maxHeight / height;
            height = maxHeight;
          }
        }
        canvas.width = width;
        canvas.height = height;

        ctx.drawImage(img, 0, 0, width, height);

        canvas.toBlob(function(blob) {
          resolve(blob);
        }, file.type || 'image/png', quality); // quality 为图片质量
      };
    };
  });
}

第三方库压缩

第三方库可以使用 compressorjs 来实现。

import Compressor from 'compressorjs';

document.getElementById('file').addEventListener('change', (e) => {
  const file = e.target.files[0];

  if (!file) {
    return;
  }

  new Compressor(file, {
    quality: 0.6,
    success(result) {},
    error(err) {},
  });

});

后记

什么有损和无损压缩,咱就不考虑了,超纲了,容易掉头发,要求高了找 UI !哈哈哈哈~嗝