开发者

Determine image size in JavaScript without `<img>` tag

Using JavaScript, how can I determine the size of an image which is not in the document without inserting it in the document?

Could I download the image using AJAX and check its height and width programmatically?

Something like...

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 开发者_如何学编程{
        var imageSize = MEGIC_GET_FILE_SIZE_FUNCTION(xmlhttp);
        alert("The image is "+imageSize.width+","+imageSize.height+".");
    }
}
xmlhttp.open("GET","lena.jpg",true);
xmlhttp.send();

I'll be using Raphael, so if it offers functionality to this effect, that suits my needs.


You don't need ajax.

var img = new Image();
img.onload = function() {
    alert("The image is " + this.width + "x" + this.height);
}
img.src = "lena.jpg";


var img = new Image();
img.src = url; 
var height = img.height;
var width = img.width;


Here's a fiddle for you. Just use the Image object.


You don't need to add it to the document to measure it's size, but you do have to wait for it to at least partially load. If you need to do it for possibly more than one image at a time, and have it call a callback as soon as the size is available, you can use my imageloader module:

var ImageLoader = {
maxChecks: 1000,
list: [],
intervalHandle : null,

loadImage : function (callback, url) {
  var img = new Image ();
  img.src = url;
  if (img.width && img.height) {
    callback (mg.width, img.height, url, 0);
    }
  else {
    var obj = {image: img, url: url, callback: callback, checks: 1};
    var i;
    for (i=0; i < this.list.length; i++)    {
      if (this.list[i] == null)
        break;
      }
    this.list[i] = obj;
    if (!this.intervalHandle)
      this.intervalHandle = setInterval(this.interval, 30);
    }
  },

// called by setInterval  
interval : function () {
  var count = 0;
  var list = ImageLoader.list, item;
  for (var i=0; i<list.length; i++) {
    item = list[i];
    if (item != null) {
      if (item.image.width && item.image.height) {
        item.callback (item.image.width, item.image.height, item.url, item.checks);
        ImageLoader.list[i] = null;
        }
      else if (item.checks > ImageLoader.maxChecks) {
        item.callback (0, 0, item.url, item.checks);
        ImageLoader.list[i] = null;
        }
      else {
        count++;
        item.checks++;
        }
      }
    }
  if (count == 0) {
    ImageLoader.list = [];
    clearInterval (ImageLoader.intervalHandle);
    delete ImageLoader.intervalHandle;
    }
  }
};


If you know the source of the image you could use a javascript image object:

function MEGIC_GET_FILE_SIZE_FUNCTION(src){
    var img = new Image();
    img.src = src;
    return {height: img.height, width: img.width};
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜