Get an Images Native Width

If you select and image with jQuery and then use .width(), you'll get the images current width, even if it's been scaled (e.g. max-width: 100%;). You can access the images native width (even if it doesn't have any attributes which declare it) like this:

// Get on screen image
var screenImage = $("#image");

// Create new offscreen image to test
var theImage = new Image();
theImage.src = screenImage.attr("src");

// Get accurate measurements from that.
var imageWidth = theImage.width;
var imageHeight = theImage.height;

Comments

  1. User Avatar
    Hans Kuijpers
    Permalink to comment#

    Hi Chris,

    When I look at the code I don’t understand two things:
    1. Why don’t you use the first created var screenImage further in the script?
    2. Where does mainScreenshot come from?

    (I’m trying to learn jQuery a bit)

    • User Avatar
      Chris Coyier
      Permalink to comment#

      I just had that a bit screwed up, variable reference is correct now.

  2. User Avatar
    Saeed Neamati
    Permalink to comment#

    Very subtle Chris. This is a great usage of native objects of JavaScript. I think it can simply become a jQuery plugin, like:

    
    $('#image-id').realWidth();
    
  3. User Avatar
    Richard
    Permalink to comment#

    I discovered that Chrome/FF had an extra attribute for images when working on a custom carousel. Here is a little function I wrote that uses the properties if they exist, and sets them if they don’t. One big assumption (as with the original example) is that the sizes are available immediately. Technically having a separate function on browsers without ‘natural(width|height)’ that fills in the value before you need it would be ‘safer’.

    function imgRealSize(img) {
    	var $img = $(img);
    	if ($img.prop('naturalWidth') == undefined) {
    		var $tmpImg = $('<img/>').attr('src', $img.attr('src'));
    		$img.prop('naturalWidth', $tmpImg[0].width);
    		$img.prop('naturalHeight', $tmpImg[0].height);
    	}
    	return { 'width': $img.prop('naturalWidth'), 'height': $img.prop('naturalHeight') }
    }
    
  4. User Avatar
    Kwadwo
    Permalink to comment#

    Hi Chris,
    Thumbs up for your help. I find the ‘RevealingPhotoSlider’ very interesting, however, it is not compatible with Chrome. On clicking ‘MORE INFO’, in Chrome, the image does not show up but rather shrinks. Also in IE8. Am just creating my website so don’t have the ‘live’ link, hence could not put a web address, sorry, and I hope to hear back from you soon.

    Thank you.

  5. User Avatar
    Graham
    Permalink to comment#

    I found this would only work in Chrome within $(window).load — $(document).ready seems to fire too soon.

  6. User Avatar
    clemi
    Permalink to comment#

    @Graham: only the image has to be loaded before calculating, you can use $(‘#image’).load
    works in all browsers I tested so far, mobile as well

    thanks a lot, chris

  7. User Avatar
    Ravi
    Permalink to comment#

    returning native height and width as zero.

  8. User Avatar
    Liam Monticelli
    Permalink to comment#

    There are bound to be cases where we need the dimensions of an image that hasn’t loaded yet, e.g. an image in a hidden layer. Here’s the workaround I’ve come up with for such situations:

      $(imgs).each(function(){
    
        // Create new offscreen image to test
        var theImage = new Image();
        theImage.src = $(this).attr("src");
        // Add a reference to the original.
        $(theImage).data("original",this);
    
        // Get accurate measurements from that.
        $(theImage).load(function(){
          var imageWidth = this.width;
          var imageHeight = this.height;
          $($($(this).data("original")).css("width",imageWidth+"px");
        });
      });
    

    where imgs is a collection of <img> elements.

  9. User Avatar
    Adam
    Permalink to comment#

    There is an issue on getting the native width on firefox and IE

    is there a way to get that issue fixed?

  10. User Avatar
    Tharaka
    Permalink to comment#

    If image is cached (for eg. using output cached in IIS 7.5) above method didn’t work in iPhone 5+

  11. User Avatar
    Jens
    Permalink to comment#

    Good idea, but don’t work…follwoing script do the trick for me.

    jQuery.fn.realSize = function() {

    var i = $(this.filter( 'img')).first();
    
    if( i) {
    
        if( !i.data( 'realSize')) {
    
            var _w = i.width(),
                _h = i.height();
    
            i.width( 'auto').height( 'auto');
    
            i.data( 'realSize', { width: i.width(),
                                  height: i.height()});
    
            i.width( _w).height( _h);
    
    
        }
    
        return i.data( 'realSize');
    
    }
    
    return undefined;
    

    };

    jQuery.fn.realWidth = function( options) {

    var rs = this.realSize();
    
    return rs ? rs.width : undefined;
    

    };

    jQuery.fn.realHeight = function( options) {

    var rs = this.realSize();
    
    return rs ? rs.height : undefined;
    

    };

    $( ‘img’).realSize(); // Object {width: 960, height: 720}

  12. User Avatar
    angel
    Permalink to comment#

    Jens your solution work fine for me ;)
    I addon this on jQuery JavaScript Library v2.1.0

    Perfect thk man

  13. User Avatar
    jamie
    Permalink to comment#

    Just what I needed today! Thanks – even a couple of years on still useful :)

  14. User Avatar
    Ian
    Permalink to comment#

    Chris / All
    Is there any way to do something like this?

    img width:100%;
    img max-width:NATURAL;

    So I don’t want an image to become pixelated but if it’s big enough go to 100%.

    • User Avatar
      slomo
      Permalink to comment#

      Ian, that should be simple as

      img {
          width: auto;
          max-width: 100%;
      }
      
  15. User Avatar
    jens
    Permalink to comment#

    Hey Chris,

    i think following do the trick for you.

    $( ‘img’).css( ‘max-width’: $( ‘img’).realSize().width);

  16. User Avatar
    Ian
    Permalink to comment#

    jQuery is fine but I was looking for a CSS only answer. Seems odd that you can’t specify the natural image width unless you omit the CSS width altogether.

  17. User Avatar
    Kenyon
    Permalink to comment#

    This is works great for me on local images but when using images on a CDN, it seems to only pick up the size on first load only, if you call the function on window.resize the function returns 0.

    Here’s a jsFiddle: http://jsfiddle.net/WKzJ4/2/

    Any solutions to this?

    • User Avatar
      Brian
      Permalink to comment#

      Kenyon,

      Did you ever find a solution for finding the natural size of an image on a CDN? Thanks for any help.

  18. User Avatar
    Jens
    Permalink to comment#

    Hey Kenyon,

    i’m not sure what do you like to do. The sense of the code was determine the original size of an image.

    Btw. : get original size of an image with «new Image()» works not fine.

  19. User Avatar
    Mark Stickling
    Permalink to comment#

    In iOS 8:
    Does anyone else get this code returning,
    the height for the width
    and the width for the height
    when you take a portrait photo with the camera?

    I guess the photo taken isn’t rotated at this point or something. But when the image is loaded to the screen it’s the right way up. Confused.

  20. User Avatar
    Pavel
    Permalink to comment#

    You need to wait for image to load
    Something like this:

    var img = new Image();
    img.onload = function() {
      console.log(this.width + 'x' + this.height);
    };
    img.src = /whatever you need/
    
  21. User Avatar
    Andreas Böhrnsen
    Permalink to comment#

    Works great! Thanks.

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag