Question

I have an input text field where the user provides the source url of the image , for example http://mysite/images/STARTPAGE_LOGO.gif is a valid value.

I dont have any img tag or something else in my html document. How can i determine the dimensions of the image which is present at the URL the user has entered .

Was it helpful?

Solution

There is no method to find out the width and height of the image without loading it so you will have to dynamically load it , and to do so you can use

function getDimensions(_src,_callback){
     /* create a new image , not linked anywhere in document */
     var img = document.createElement('img');
     /* set the source of the image to what u want */
     img.src=_src;
     /* Wait the image to load and when its so call the callback function */
     /* If you want the actual natural dimensions of the image use naturalWidth and natural height instead */
     img.onload = function () { _callback(img.width,img.height) };
}

After declaring the above function in pure javascript spirit you can do something like

getDimensions('http://mysite/images/STARTPAGE_LOGO.gif',function(w,h){
 console.log( "Height : ",h,"Width:",w);
});

OTHER TIPS

HTML:

   <input id="src" type="text" value="https://www.google.pl/images/srpr/logo3w.png"/>

JAVASCRIPT:

var img = new Image; // create tmp image element  
                     // is equal to document.createElement('img');

Bind function on onload event, it will be called automatically when image is loaded.

   img.onload = function(){
     alert( this.width +" : " + this.height );
   }; 

Set the source of image;

img.src = document.getElementById('src').value // get the value of input element;

for curiosity in jQuery:

$('<img/>').attr('src',$('#src').val()).bind('load',function(){
     alert( this.width +' x ' + this.height );
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top