Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get width height of remote image from url

So the alert gives undefined values for the width and height. I think the w and h values of the image from the img.onload calculation is not being passed to the values to return, or it may be returning w and h before the onload calculates them:

function getMeta(url){  var w; var h;  var img=new Image;  img.src=url;  img.onload=function(){w=this.width; h=this.height;};  return {w:w,h:h}     }  // "http://snook.ca/files/mootools_83_snookca.png" //1024x678 // "http://shijitht.files.wordpress.com/2010/08/github.png" //128x128  var end = getMeta("http://shijitht.files.wordpress.com/2010/08/github.png"); var w = end.w; var h = end.h; alert(w+'width'+h+'height'); 

How can I have the alert show the correct width and height?

http://jsfiddle.net/YtqXk/

like image 900
Wonka Avatar asked Jul 11 '12 22:07

Wonka


People also ask

How do you find the height and width of an uploaded image in react?

src = uploadedImage; console. log(image. naturalWidth,image. naturalHeight);


2 Answers

Get image size with jQuery

function getMeta(url) {     $("<img/>",{         load: function() {             alert( this.width +" "+ this.height );         },         src: url     }); } 

Get image size with JavaScript

function getMeta(url) {        var img = new Image();     img.onload = function() {         alert( this.width +" "+ this.height );     };     img.src = url; } 

Get image size with JavaScript (modern browsers, IE9+ )

function getMeta(url){        const img = new Image();     img.addEventListener("load", function() {         alert( this.naturalWidth +' '+ this.naturalHeight );     });     img.src = url; } 

Use like: getMeta( "http://example.com/img.jpg" );

https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement

like image 146
Roko C. Buljan Avatar answered Oct 11 '22 19:10

Roko C. Buljan


Just pass a callback as argument like this:

function getMeta(url, callback) {     const img = new Image();     img.src = url;     img.onload = function() { callback(this.width, this.height); } } getMeta(   "http://snook.ca/files/mootools_83_snookca.png",   (width, height) => { alert(width + 'px ' + height + 'px') } );
like image 39
feychu Avatar answered Oct 11 '22 19:10

feychu