JS - File Reader API get image file size and dimensions

半城伤御伤魂 提交于 2019-12-04 07:12:16

Something like this?

var oPreviewImg = new Image();
oPreviewImg.onload = function(){
  console.log(this.size);
  alert("'" + this.name + "' is " + this.width + " by " + this.height + " pixels in size.");
  return true;
};

oPreviewImg.onerror = function(){
  alert("'" + this.name + "' failed to load.");
  return true;
}

oPreviewImg.src = "//placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150";

var xhr = new XMLHttpRequest();
xhr.open('HEAD', oPreviewImg.src, true);
xhr.onreadystatechange = function() {
    console.log('this', this);
  if ( xhr.readyState == 4 ) {
    if ( xhr.status == 200 ) {
      alert('Size in bytes: ' + xhr.getResponseHeader('Content-Length'));
    } else {
      alert('ERROR');
    }
  }
};
xhr.send(null);

Live version

Update Live version replaced with Fiddle, however, due to cross site scripting concerns, the size is no longer being retrieved effectively.

I don't believe that JS is going to be capable of getting that data without first rendering the image to the viewport. That is to say, I am unfamiliar of any method that would do what you ask in the JavaScript, or JQuery libraries. Your best bet for getting data like that is going to be rendering the image to the page in a preview capacity or using a more powerful language like PHP and using an Ajax request to get the data you're looking for.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!