Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)? 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.

like image 881
Martin Bean Avatar asked Sep 16 '11 08:09

Martin Bean


People also ask

What will happen if width and height of the image is not specified?

If width and height are not specified, the page will flicker while the image loads.

How do you get the image width and height using JS?

Answer: Use the JavaScript clientWidth property You can simply use the JavaScript clientWidth property to get the current width and height of an image. This property will round the value to an integer.

Can we specify the width and height of an image in a Web page?

The height and width of an image can be set using height and width attribute. The height and width can be set in terms of pixels. The <img> height attribute is used to set the height of the image in pixels. The <img> width attribute is used to set the width of the image in pixels.


2 Answers

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';
like image 90
Ian Oxley Avatar answered Oct 09 '22 16:10

Ian Oxley


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"?

like image 32
Michael Lorton Avatar answered Oct 09 '22 14:10

Michael Lorton