简体   繁体   English

压缩图片大小JavaScript

[英]Compress Image size JavaScript

I am doing project where we can take snap shots from video. 我正在做一个项目,我们可以从视频中拍摄快照。 You can view my code snippet below. 您可以在下面查看我的代码段。

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

w,h are nothing but width and height of video. w,h只是视频的宽度和高度。 Those are calculated as shown below. 这些计算如下。

            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);

The base64 Image I am getting here is approximately 260kb. 我在这里获得的base64映像大约为260kb。 I want to reduce this image to below 80kb. 我想将此图像减小到80kb以下。

I tried using canvas.toDataURL('image/png', 0.2) but no use. 我尝试使用canvas.toDataURL('image/png', 0.2)但没有用。

The quality setting is only valid when the type of image is either jpeg or webp . 仅当图像类型为jpegwebp时,质量设置才有效。 Try using the following: 尝试使用以下内容:

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

For example, from the Docs : 例如,从Docs中

A Number between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp . 0到1之间的数字表示所请求的类型是image/jpegimage/webp图像质量。
If this argument is anything else, the default value for image quality is used. 如果此参数为其他任何参数,则使用图像质量的默认值。 Other arguments are ignored. 其他参数将被忽略。

The specification and MDN say that the second argument is not supported for PNG images. 规范MDN表示PNG图片不支持第二个参数。 The specification says the second argument is just for image/jpeg ; 规范说第二个参数仅用于image/jpeg MDN says image/jpeg or image/webp . MDN表示image/jpegimage/webp

Note that browsers are not required to support anything other than PNG, and if you request something they don't support, they give back PNG. 请注意,浏览器不需要支持PNG以外的任何功能,并且如果您请求它们不支持的功能,它们会返回PNG。 So you can do: 因此,您可以执行以下操作:

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

...and you'll either get a JPEG low quality ( 0.2 is really low), or a PNG ignoring the second argument. ...而您将得到JPEG低质量( 0.2确实很低),或忽略第二个参数的PNG。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM