jQuery : Image : Calculate Image Height/Width when loaded

You can calculate the Image dimension and determine if the image orientation is landscape or portrait using jQuery. You can also calculate using packages like ‘RMagick’, ‘MiniMagick’ in ruby ( ROR ). However it has following disadvantages:

Disadvantage of calculating Image height / width using RMagick or MiniMagick in run time:

  • Its CPU intensive
  • It requires Internet to get image and calculate the dimensions.
  • Its a slow process

FYI You can also calculate the Image Height, Width after the Image is fully loaded by using the load event associated with the <img> tag with the help of jQuery.

For Example:

$(document).ready(function(){   
   var $image = $('.fixed-frame img');
   $image.load(function(){
      rePositionLogo($image);
   });

  if($image.prop('complete')){
    rePositionLogo($image);
  }

});

function rePositionLogo($image){
  var height = $image.height();
  var width = $image.width();
  if (width > height) {
    $image.parents('.header').addClass('landscape');
    var marginTop = (105 - $image.height())/2;
    $image.css('margin-top', marginTop + 'px')
  }else{
    $image.parents('.header').addClass('portrait');
  }
}

Be careful, because load() will not trigger when an image is already loaded. This can happens easily when an image is in the user’s browser cache.

You can check if an image is already loaded using $('#myImage').prop('complete'), which returns true when an image is loaded.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s