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.
If width and height are not specified, the page will flicker while the image loads.
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.
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.
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"?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With