压缩图片大小 JavaScript

Compress Image size JavaScript

我正在做一个项目,我们可以从视频中拍摄快照。您可以在下面查看我的代码片段。

             function snapshot(){
                context.drawImage(video, 0, 0, w, h);
                img = document.createElement("img");
                img.src = canvas.toDataURL();
             }

w,h 就是视频的宽度和高度。这些计算如下所示。

            video.addEventListener('loadedmetadata', function() {

               var ratio = video.videoWidth / video.videoHeight;
               w = video.videoWidth - 100;
               h = parseInt(w / ratio, 10);
               w= w-100; h= h-100;
               canvas.width = w;
               canvas.height = h;           
            }, false);

我在这里得到的base64图像大约是260kb。我想将这张图片缩小到 80kb 以下。

我尝试使用 canvas.toDataURL('image/png', 0.2) 但没有用。

质量设置仅在图片类型为jpegwebp时有效。尝试使用以下内容:

canvas.toDataURL("image/jpeg", 0.1);

例如,来自Docs

A Number between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp.
If this argument is anything else, the default value for image quality is used. Other arguments are ignored.

The specification and MDN 表示 PNG 图像不支持第二个参数。规范说第二个参数仅用于 image/jpeg; MDN 说 image/jpegimage/webp.

请注意,浏览器不需要支持除 PNG 以外的任何内容,如果您请求它们不支持的内容,它们会返回 PNG。所以你可以这样做:

img.src = canvas.toDataURL('image/jpeg', 0.2);

...你要么得到低质量的 JPEG(0.2 真的很低),要么得到忽略第二个参数的 PNG。