tianyun 1 year ago
parent
commit
60e86226af
1 changed files with 18 additions and 5 deletions
  1. 18 5
      simple-demo/webp.html

+ 18 - 5
simple-demo/webp.html

@@ -46,7 +46,7 @@
         handleClipboardItems(event.dataTransfer.items);
     });
 
-    function compressImage(blobFile) {
+    function compressImage(blobFile, quality = 0.8) {
         // 返回一个Promise对象
         return new Promise((resolve, reject) => {
             // 创建一个Image对象
@@ -61,7 +61,7 @@
                 canvas.toBlob((webpBlob) => {
                     // 解决Promise,并传递压缩后的Blob对象
                     resolve(webpBlob);
-                }, "image/webp", 0.8);
+                }, "image/webp", quality);
                 // 如果在转换过程中发生错误,拒绝Promise
             };
             image.src = URL.createObjectURL(blobFile);
@@ -87,11 +87,20 @@
 
                 // 压缩为webp格式
                 compressImage(blobFile).then((webpBlob) => {
+                    let size = webpBlob.size;
+                    // 如果图片大于300kb,再次压缩
+                    if (size > 300 * 1024) {
+                        compressImage(webpBlob, 0.5).then((webpBlob2) => {
+                            size = webpBlob2.size;
+                            // 将压缩后的webp图片展示在页面上
+                            imageDisplay.src = URL.createObjectURL(webpBlob2);
+                            showSize(webpBlob2);
+                        });
+                        return;
+                    }
                     // 将压缩后的webp图片展示在页面上
                     imageDisplay.src = URL.createObjectURL(webpBlob);
-
-                    document.getElementById("status").innerText = " 已压缩 ☺";
-                    document.getElementById("afterSize").innerText = formatSize(webpBlob.size);
+                    showSize(webpBlob);
                 });
 
                 // 防止页面跳转
@@ -100,6 +109,10 @@
             }
         }
     }
+    function showSize(webpBlob){
+        document.getElementById("status").innerText = " 已压缩 ☺";
+        document.getElementById("afterSize").innerText = formatSize(webpBlob.size);
+    }
 
     // 选择90度旋转
     function rotateImage() {