Get Real Image Height and Width Dimensions

By  on  

One massive help provided by CSS in aiding developers to create responsive designs is max-width.  I always set img, iframe, and embed tags to max-width: 100% so that they aren't allowed bleed through their parent and stretch the page on mobiles, but I recently asked myself if it was possible to get an image's "true" size with JavaScript.  I wanted the real image dimensions without any CSS modifications.  MDN informed me of a property I'd never heard of  which provided me the information I wanted!

The JavaScript

Using some JavaScript magic, we can get the real dimensions of an image:

myImage.addEventListener('load', function() {
	console.log('My width is: ', this.naturalWidth);
	console.log('My height is: ', this.naturalHeight);
});

I had never heard of these read only naturalWidth and naturalHeight properties but I'm happy they're available.  No matter how terrible CSS mangles an img element, the original image dimensions are available.  Of course the image's onload event should be triggered before checking the image dimensions as you cannot know them without the image being loaded.

Recent Features

  • By
    Interview with a Pornhub Web Developer

    Regardless of your stance on pornography, it would be impossible to deny the massive impact the adult website industry has had on pushing the web forward. From pushing the browser's video limits to pushing ads through WebSocket so ad blockers don't detect them, you have...

  • By
    CSS Animations Between Media Queries

    CSS animations are right up there with sliced bread. CSS animations are efficient because they can be hardware accelerated, they require no JavaScript overhead, and they are composed of very little CSS code. Quite often we add CSS transforms to elements via CSS during...

Incredible Demos

  • By
    Create a Simple Dojo Accordion

    Let's be honest:  even though we all giggle about how cheap of a thrill JavaScript accordions have become on the web, they remain an effective, useful widget.  Lots of content, small amount of space.  Dojo's Dijit library provides an incredibly simply method by which you can...

  • By
    Introducing MooTools LazyLoad

    Once concept I'm very fond of is lazy loading. Lazy loading defers the loading of resources (usually images) until they are needed. Why load stuff you never need if you can prevent it, right? I've created LazyLoad, a customizable MooTools plugin that...

Discussion

  1. Adam

    Looks like Chrome, IE9+ support for sure… any idea for FF, Safari, and Opera?

  2. MaxArt

    Nice and useful properties, they can even be used to tell if an image is correcly loaded (they must be non-zero).

    Alas, they’re not available in IE8 and older versions, and IIRC Presto-based Opera.

  3. Solution for unsupported browsers (create dummy image to get real dimensions):

    function realImgDimension(img) {
        var i = new Image();
        i.src = img.src;
        return {
            naturalWidth: i.width, 
            naturalHeight: i.height
        };
    }
      
    var myImage = document.getElementById('myImage');
    myImage.addEventListener('load', function() {
        var realSize = realImgDimension(this);
    	console.log('My width is: ', realSize.naturalWidth);
    	console.log('My height is: ', realSize.naturalHeight);
    });
    
  4. Zach

    These attributes come in handy when building image galleries. I used it to iterate through the heights and widths of each image in a photo album, size their soon-to-be parent based on the tallest and widest dimensions, and then add them to the page.

  5. Brendon

    This is fantastic!

  6. How to get image size (height & width) using JavaScript? and store the values

  7. Zahoor

    Good, but remember that load event won’t be triggered in case image is already cached by the browser. So you will need do some tweaks like trigger the load again in case image was cached(e.g we can look for “complete” property for an image object and trigger the loading again.)

    • This has previously been an issue for me so thanks for that workaround. Can I ask how doing this affects performance? I currently get my CMS to spit out dimensions into data-attrs when i need this information reliably.

  8. Jim Hawkins

    naturalWidth and naturalHeight don’t work in ie8; I use:

    imageWith =  '\v' == 'v' ? this.width : this.naturalWidth;
    
  9. Sam Foster

    Ouch, this is a terribly brittle hack:

    imageWith =  '\v' == 'v' ? this.width : this.naturalWidth;

    Do something like this to degrade gracefully:

      imageWith =  this.naturalWidth || this.width;
      // or, maybe better:
      imageWith =  this.hasOwnProperty('naturalWidth') ? this.naturalWidth : this.width;
    
  10. This works great to get the image size that are present in the html file. But What I was looking for is “To get the image size before uploading to the server”

    I found this solution. Hope it would work for others who are searching for similar solutions.

    http://stackoverflow.com/questions/8903854/check-image-width-and-height-on-upload-with-javascript

  11. HEnk

    How to use it for multiple images on one page? I only get dimensions from the first image.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!