1

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 .

yqlim
  • 6,898
  • 3
  • 19
  • 43
hkrly
  • 311
  • 3
  • 12
  • Afaik, toDataURL uses base64, which has more characters than binary by definition. That doesn't mean the saved image will be bigger as well. –  Jul 12 '19 at 08:13
  • toDataURL indeed larger but just about a quarter, not double. so it should still be smaller than original size because, still that was the goal. instead its doubled. why? – hkrly Jul 12 '19 at 08:20
  • You may use this method to get the size of your data: https://stackoverflow.com/questions/47852277/image-file-size-from-data-uri-in-javascript – enxaneta Jul 12 '19 at 08:28
  • 1
    @enxaneta thanks, i tried and i get 3526695, which is still 1M larger and not smaller. Not sure what is going on here and cant find a proper explanation. – hkrly Jul 12 '19 at 08:39

1 Answers1

0

Change the below line:

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

To:

const data = canvas.toDataURL("image/jpeg", 0.1);
Mr. X
  • 706
  • 12
  • 23