March 22, 2012

Javascript: Get the original size of an image

Sometimes you need to know the original dimensions of an image that you've loaded via javascript, or that's already loaded in the DOM. Here's a little class that will take the location of an image, and a callback function that receives the original width and height:
var getImageSizeWithCallback = function( src, callback ) {
  var image = new Image();
  image.onload = function () {
    if( callback ) callback( image.width, image.height );
    image.onload = image.onerror = null;
  };
  image.onerror = function () {
    if( callback ) callback( -1, -1 );
    image.onload = image.onerror = null;
  };
  // load it
  image.src = src;
};

Usage:
getImageSizeWithCallback( 'images/path/to/img.jpg', function( w, h ) {
  console.log( 'image size:', w, h );
});

No comments:

Post a Comment