开发者

Is it possible to get the height/width of an image that's not in the DOM?

Is it possible to get the h开发者_如何学Goeight and width of an image in the file system using JavaScript (i.e. an image that is not part of the DOM)? Or would I have to use JavaScript to inject the image into the DOM and grab the dimensions that way?

I ask because I'm writing a JavaScript method to render a UI component on the fly generated by Raphaël, which takes three image paths as part of the method parameters. These are then used to render the aforementioned UI component, and I need the dimensions of the images for positioning purposes.

Thanks in advance.


I think as long as the image has loaded you can grab the width and height - you shouldn't have to inject it into the DOM though. For example:

var tmp = new Image();
tmp.onload = function() {
    console.log(tmp.width + ' x ' + tmp.height);
}
tmp.src = 'http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4';


You cannot necessarily get to "the file system", but you can do this:

v = new Image();
v.onload = function() {
  alert("size: " + String(v.width) + 'x' + String(v.height));
};
v.src = "http://www.gravatar.com/avatar/96269f5a69115aa0e461b6334292d651?s=32&d=identicon&r=PG";

Would you count that as "adding to the DOM"?


You can download image with code:

var img=new Image(),imgWidth,imgHeight;
img.onerror=img.onload=function(ev) {
  ev=ev||event;
  if(ev.type==="error") {
    imgWidth=imgHeight=-1; // error loading image resourse
  }
  else {
    imgWidth=this.width; // orimgWidth=img.width
    imgHeight=this.height; // imgHeight=img.height
  }
}
img.src="url_to_image_file";


Is it possible to get the height and width of an image in the file system using JavaScript (i.e. an image that is not part of the DOM)?

  • No

Or would I have to use JavaScript to inject the image into the DOM and grab the dimensions that way?

  • Yes
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜