简体   繁体   中英

Why canvas doubles the size of an image?

I was trying to compress an image from file input using canvas . I read answers here, some say canvas makes the file larger , some use it to compress images, and since I am new to this :

function compressImg(img){
    var canvas=document.createElement("canvas");
    var ctx=canvas.getContext("2d");
    canvas.width=img.width/2;
    canvas.height=img.height/2;
    ctx.drawImage(img,0,0,canvas.width,canvas.height);
    document.getElementById("imagePreview0").src = canvas.toDataURL();
    const data = ctx.canvas.toDataURL(img, "image/jpeg", 0.1);
    console.log("size2",data.length);
}


var img = new Image();
img.onload = function(){
    console.log("size1",file.length);
    compressImg(img);
};
img.src = file;

for an image that the mac says 1.7M , i get

size1 2,318,839

size2 4,702,282 .

So - can you really compress an image ?

I just need to reduce file size to under 2M .

Change the below line:

const data = ctx.canvas.toDataURL(img, "image/jpeg", 0.1);

To:

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

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