我想知道如何使用js或jquery在图片加载后获取其大小(字节,KB,MB)。我不想使用ajax或发送任何额外的http请求。就像我们使用$("#imageId").height()一样,我们如何获取内存大小?
我想知道如何使用js或jquery在图片加载后获取其大小(字节,KB,MB)。我不想使用ajax或发送任何额外的http请求。就像我们使用$("#imageId").height()一样,我们如何获取内存大小?
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);
据我所知,这是唯一可能的解决方案。
更新:我不知道这个解决方案有多准确,但这是我的猜测。
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));