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 .