[英]Why canvas doubles the size of an image?
I was trying to compress an image from file input
using canvas
. 我试图使用canvas
从file input
压缩图像。 I read answers here, some say canvas makes the file larger , some use it to compress images, and since I am new to this : 我在这里阅读答案,有人说canvas使文件变大 ,有人用它来压缩图像,并且由于我是新来的 :
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 对于Mac说170万的图像,我得到了
size1 2,318,839 1号2,318,839
size2 4,702,282 . size2 4,702,282 。
So - can you really compress an image ? 所以-您真的可以压缩图像吗?
I just need to reduce file size to under 2M . 我只需要将文件大小减小到2M以下即可 。
Change the below line: 更改以下行:
const data = ctx.canvas.toDataURL(img, "image/jpeg", 0.1);
To: 至:
const data = canvas.toDataURL("image/jpeg", 0.1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.