JavaScript: Get image dimensions

JavascriptHtmlImage

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

var img = new Image();

img.onload = function(){
  var height = img.height;
  var width = img.width;

  // code here to use the dimensions
}

img.src = url;

Solution 2 - Javascript

Make a new Image

var img = new Image();

Set the src

img.src = your_src

Get the width and the height

//img.width
//img.height

Solution 3 - Javascript

naturalWidth and naturalHeight

var img = document.createElement("img");
img.onload = function (event)
{
	console.log("natural:", img.naturalWidth, img.naturalHeight);
	console.log("width,height:", img.width, img.height);
	console.log("offsetW,offsetH:", img.offsetWidth, img.offsetHeight);
}
img.src = "image.jpg";
document.body.appendChild(img);

// css for tests
img { width:50%;height:50%; }

Solution 4 - Javascript

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);
});

Solution 5 - Javascript

if you have image file from your input form. you can use like this

let images = new Image();
images.onload = () => {
 console.log("Image Size", images.width, images.height)
}
images.onerror = () => result(true);

let fileReader = new FileReader();
fileReader.onload = () => images.src = fileReader.result;
fileReader.onerror = () => result(false);
if (fileTarget) {
   fileReader.readAsDataURL(fileTarget);
}

Solution 6 - Javascript

Combining promises & typescript typing:

/**
 * Returns image dimensions for specified URL.
 */
export const getImageDimensions = (url: string): Promise<{width: number, height: number}> => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve({
      width: img.width,
      height: img.height,
    });
    img.onerror = (error) => reject(error);
    img.src = url;
  });
};

Usage:

try {
  const {width, height} = await getImageDimensions(entry.NWS_IMAGE);
  console.log(`Image dimensions: ${width}px x ${height}px`);
} catch (e) {
  // Could not load image from specified URL
  console.error(e);
}

Solution 7 - Javascript

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){   
    var img = new Image();
    img.addEventListener("load", function(){
        alert( this.naturalWidth +' '+ this.naturalHeight );
    });
    img.src = url;
}

Use the above simply as: getMeta( "http://example.com/img.jpg" );

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

Solution 8 - Javascript

Similar question asked and answered using JQuery here:

https://stackoverflow.com/questions/11442712/javascript-function-to-return-width-height-of-remote-image-from-url

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

getMeta("http://page.com/img.jpg");

Solution 9 - Javascript

Following code add 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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJQueeeerView Question on Stackoverflow
Solution 1 - JavascriptShumiiView Answer on Stackoverflow
Solution 2 - Javascriptnc3bView Answer on Stackoverflow
Solution 3 - JavascriptBitterblueView Answer on Stackoverflow
Solution 4 - JavascriptDavidDunhamView Answer on Stackoverflow
Solution 5 - JavascriptRaka Adi NugrohoView Answer on Stackoverflow
Solution 6 - JavascriptQuentin S.View Answer on Stackoverflow
Solution 7 - JavascriptSunny MahajanView Answer on Stackoverflow
Solution 8 - JavascriptLuke KnepperView Answer on Stackoverflow
Solution 9 - JavascriptTestereView Answer on Stackoverflow