简体   繁体   中英

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. 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. I want to reduce this image to below 80kb.

I tried using canvas.toDataURL('image/png', 0.2) but no use.

The quality setting is only valid when the type of image is either jpeg or webp . Try using the following:

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

For example, from the 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 say that the second argument is not supported for PNG images. The specification says the second argument is just for image/jpeg ; MDN says image/jpeg or image/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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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