Reputation: 614
I want to know using js or jquery how can I get the size (Bytes,KB,MB) of an image after it is loaded. I don't wanna use any ajax or send any extra http request. Just like we use $("#imageId").height(), how can we get the memory size?
Upvotes: 3
Views: 4790
Reputation: 8389
As per @CMS answer in Determining image file size + dimensions via Javascript?
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);
This is the only possible solution AFAIK.
Update: I do not know how accurate this solution is, but here is my guess
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));
Sources : How can I estimate the disk size of a string with JavaScript?, Get image data in JavaScript?
Upvotes: 6