Learner85
Learner85

Reputation: 51

How to find image data size using javascript?

On a webpage, once images have been downloaded and rendered, I need to determine an image's file size (kb) within the browser context (so I could display that info on the page, just below the image)

Upvotes: 4

Views: 175

Answers (1)

Daryl Ginn
Daryl Ginn

Reputation: 1424

The easiest way is probably with a HEAD request returning the Content-Length:

function fileSize(img, func) {
  var xhr = new XMLHttpRequest();
  xhr.open('HEAD', img.src, true);
  xhr.onreadystatechange = function() {
    if(xhr.readyState == 4 && xhr.status == 200) {
      func(xhr.getResponseHeader('Content-Length')) 
    }
  }
  xhr.send()
}

Usage

fileSize(imgNode, function(size) {
  // ...
})

Upvotes: 3

Related Questions