Paul Shan
Paul Shan

Reputation: 614

How to get the image size (memory) after it is loaded using js/jquery

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

Answers (1)

Exception
Exception

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

Related Questions