Skip to content

前端实现图片压缩功能

devicePixelRatio 属性

devicePixelRatio 返回当前显示设备的物理像素分辨率与 CSS 像素分辨率之比。此值也可以解释为像素大小的比率:一个 CSS 像素的大小与一个物理像素的大小。简单来说,它告诉浏览器应使用多少屏幕实际像素来绘制单个 CSS 像素。

devicePixelRatio 用法(MDN)

html
<div class="app">
  <div class="util">
    <input type="file" name="" id="file" />
    <button class="green" onclick="file.click()">选择要压缩的图片</button>
    <button class="yellow" onclick="handleCompress()">压缩</button>
  </div>
  <div class="canvas-box">
    <canvas id="canvas" width="300" height="300"></canvas>
  </div>
</div>
javascript
<script>
  let file = document.getElementById('file');
  let canvas = document.getElementById('canvas');
  let img;
  file.addEventListener(
    'change',
    function (e) {
      let file = e.target.files[0];
      let reader = new FileReader();
      //转为base64
      reader.readAsDataURL(file);
      reader.onload = e => {
        img = new Image();
        img.src = e.target.result;
        img.onload = function () {
          // 计算缩放比例,避免页面上无法显示
          const scale = Math.min(
            canvas.width / img.width,
            canvas.height / img.height
          );
          const width = img.width * scale * devicePixelRatio;
          const height = img.height * scale * devicePixelRatio;
          canvas.width = width;
          canvas.height = height;
          let ctx = canvas.getContext('2d');
          ctx.drawImage(img, 0, 0, width, height);
        };
      };
    },
    false
  );

  function handleCompress() {
    //预览画板被缩放过,需要重新创建画板
    const canvas2 = document.createElement('canvas');
    const ctx2 = canvas2.getContext('2d');
    const width = img.width * devicePixelRatio;
    const height = img.height * devicePixelRatio;
    canvas2.width = width;
    canvas2.height = height;
    ctx2.drawImage(img, 0, 0, width, height);

    const dataUrl = canvas2.toDataURL('image/jpeg', 0.8);
    const line = document.createElement('a');
    line.href = dataUrl;
    line.download = 'compress.jpg';
    line.click();
  }
</script>

上次更新时间:

Keep Reading, Keep Writing, Keep Coding