0

How can I check an image width and height if I only have the URL of the image, and not the image itself?

i.e. Url might be something like

http://www.myadvertiserprovider.com/images/myuserid/ad_image.png

What I am trying to do is to skip inserting an ad into my page if the image dimensions are not exactly what I am expecting. I don't want to resize the image, I require the image to be the exact dimensions that I am expecting.

  • 4
    The URL contains no information about the image, just its URI; you'd have to load the image, and insert it into the document, in order for JavaScript to do anything with it. – David Thomas Jan 21 '14 at 16:02
  • possible duplicate of [Determine original size of image cross browser?](http://stackoverflow.com/questions/1944280/determine-original-size-of-image-cross-browser) – billy Jan 21 '14 at 16:06
  • 1
    A quick google search "get height and width of image without rendering" turned up this: [Function to get image properties](http://www.webdeveloper.com/forum/showthread.php?251096-Get-image-width-without-rendering-it-to-screen) – Matt Jan 21 '14 at 16:08

2 Answers2

3

You will have to load the image. You can try something like

var img = new Image();
img.onload = function () { 
    alert("height: " + img.height + " width:" + img.width); 
};
img.src = "https://www.gravatar.com/avatar/d17c95dfa5820a212d979da58bc3435c?s=128&d=identicon&r=PG";

DEMO

Satpal
  • 132,252
  • 13
  • 159
  • 168
0

This cannot be done client-side without loading the image, unless the you request that the size of the image is written in the URI, something like image200x350.jpg.

If you want to load the image and check the image before placing it into your document:

var image = new Image();

image.onload = function() {
    console.log("Height: " + image.height + ", Width: " + image.width);

}

image.src = "http://tes.jpl.nasa.gov/css/homeWelcome.png";
Jonas Grumann
  • 10,438
  • 2
  • 22
  • 40