JavaScript: get image sizes

I only have the image url. I need to determine the height and width of this image using only JavaScript. The image may not be visible to the user on the page. How can I get its dimensions?

+54
javascript html image
Apr 12 '11 at 9:45 a.m.
source share
5 answers
var img = new Image(); img.onload = function(){ var height = img.height; var width = img.width; // code here to use the dimensions } img.src = url; 
+116
Dec 13 '13 at 14:37
source share

Make a new Image

 var img = new Image(); 

Install src

 img.src = your_src 

Get width and height

 //img.width //img.height 
+38
Apr 12 2018-11-11T00:
source share

This uses the function and waits for it to complete.

http://jsfiddle.net/SN2t6/118/

 function getMeta(url){ var r = $.Deferred(); $('<img/>').attr('src', url).load(function(){ var s = {w:this.width, h:this.height}; r.resolve(s) }); return r; } getMeta("http://www.google.hr/images/srpr/logo3w.png").done(function(test){ alert(test.w + ' ' + test.h); }); 
+5
Apr 27 '16 at 14:57
source share

The following code adds the image attribute Height and Width to each image on the page.

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Untitled</title> <script type="text/javascript"> function addImgAttributes() { for( i=0; i < document.images.length; i++) { width = document.images[i].width; height = document.images[i].height; window.document.images[i].setAttribute("width",width); window.document.images[i].setAttribute("height",height); } } </script> </head> <body onload="addImgAttributes();"> <img src="2_01.jpg"/> <img src="2_01.jpg"/> </body> </html> 
+2
Mar 08 '12 at 10:40
source share

A similar question was asked and answered using jQuery here:

Get height of width of remote image from url

 function getMeta(url){ $("<img/>").attr("src", url).load(function(){ s = {w:this.width, h:this.height}; alert(s.w+' '+sh); }); } getMeta("http://page.com/img.jpg"); 
0
Dec 09 '14 at 19:18
source share



All Articles