本地圖片壓縮工具

實現原理:canvas.toDataURL(https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLCanvasElement/toDataURL

實現方法:Compressor.js(https://github.com/fengyuanchen/compressorjs

壓縮效果


代碼示例

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>圖片壓縮</title>
    <style>
      .upinputBox {
        width: 300px;
        height: 300px;
        border: 1px dashed #ccc;
        position: relative;
        border-radius: 5px;
      }
      .upinput {
        width: 100%;
        height: 100%;
        opacity: 0;
      }
      .upTxt {
        position: absolute;
        left: 0;
        right: 0;
        top: 30%;
        text-align: center;
        color: #999;
        z-index: -1;
      }
      .qualitySpan {
        color: #999;
        font-size: 14px;
      }
      .qualityTxt {
        width: 140px;
        padding: 2px 6px;
        margin-top: 10px;
      }
    </style>
  </head>
  <body>
    <div class="upinputBox">
      <input class="upinput" type="file" id="file" accept="image/*" />
      <div class="upTxt">
        <p>將圖片拖到此處</p>
        <p>或點擊選擇</p>
      </div>
    </div>

    <div>
      <span class="qualitySpan">壓縮比率(1-100):</span>
      <input
        type="text"
        id="quality"
        value="80"
        placeholder="輸入1-100之間數字"
        onchange="upquality()"
        class="qualityTxt"
      />
    </div>

    <script src="https://unpkg.com/[email protected]/dist/compressor.js"></script>
    <script>
      document.getElementById("file").addEventListener("change", (e) => {
        // console.log('獲取圖片:', e);
        const file = e.target.files[0];
        if (!file) {
          return;
        }
        let qval = document.getElementById("quality").value;
        qval = qval.trim();
        qval = Number(qval);
        console.log("壓縮:", qval);
        if (qval > 1 && qval < 100) {
          new Compressor(file, {
            quality: qval / 100,
            success(result) {
              console.log("壓縮成功:", result);
              let alink = document.createElement("a");
              alink.href = webkitURL.createObjectURL(result);
              alink.download = result.name; //圖片名
              alink.click();
            },
            error(err) {
              console.log("壓縮失敗:", err.message);
            },
          });
        } else {
          alert("輸入1-100之間數字");
        }
      });
      // 重置內容
      function upquality() {
        document.getElementById("file").value = "";
      }
    </script>
  </body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章