Sorry if this has already been answered, but I can't find it if so.
I want to find the height and width of an image file in Javascript. I don't actually need to show the image in the page, just the height and width.
At the moment I've got the following code, but it's returning height and width 0 (in Mozilla 5).
var img = new Image(); img.src = "./filename.jpg"; var imgHeight = img.height; var imgWidth = img.width; alert("image height = " + imgHeight + ", image width = " + imgWidth);
The file definitely exists, it's in the same directory as the HTML, and it doesn't have height and width 0 :)
What am I doing wrong?
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.
Answer: Use the HTML5 naturalWidth and naturalHeight You can easily find the original or intrinsic width and heigh of an image using the HTML5 image naturalWidth and naturalHeight properties. These properties are supported in all major web browsers such as Chrome, Firefox, Safari, Opera, Internet Explorer 9 and above.
width(); alert(imageWidth); var imageHeight = Imgsize. height();
If the image is not loaded, it won't have its' height and width set. You have to wait until the image is fully loaded, then inspect its' size. Maybe something along these lines:
function getWidthAndHeight() { alert("'" + this.name + "' is " + this.width + " by " + this.height + " pixels in size."); return true; } function loadFailure() { alert("'" + this.name + "' failed to load."); return true; } var myImage = new Image(); myImage.name = "image.jpg"; myImage.onload = getWidthAndHeight; myImage.onerror = loadFailure; myImage.src = "image.jpg";
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