我想知道使用js或jquery如何在加载后获得图像的大小(字节,KB,MB)。我不想使用任何ajax或发送任何额外的http请求。就像我们使用$(“#imageId”)。height()一样,我们如何获得内存大小?
答案 0 :(得分:6)
根据Determining image file size + dimensions via Javascript?
中的@CMS回答 var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'img/test.jpg', true);
xhr.onreadystatechange = function(){
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 ) {
alert('Size in bytes: ' + xhr.getResponseHeader('Content-Length'));
} else {
alert('ERROR');
}
}
};
xhr.send(null);
这是唯一可行的解决方案AFAIK。
更新的 我不知道这个解决方案有多精确,但这是我的猜测
function bytes(string) {
var escaped_string = encodeURI(string);
if (escaped_string.indexOf("%") != -1) {
var count = escaped_string.split("%").length - 1;
count = count == 0 ? 1 : count;
count = count + (escaped_string.length - (count * 3));
}
else {
count = escaped_string.length;
}
}
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
var base_64 = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
console.log(bytes(base_64));
来源:How can I estimate the disk size of a string with JavaScript?,Get image data in JavaScript?