Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Javascript access native image size?

I'm writing a jQuery function where I'd like to access both the native size of an image, and the size specified for it on the page. I'd like to set a variable for each.

How is that done?

like image 708
Nathan Long Avatar asked Jul 07 '09 15:07

Nathan Long


3 Answers

Modern browsers

When I wrote this answer back in 2009 the browser landscape was much different. Nowadays any reasonably modern browser supports Pim Jager's suggestion using img.naturalWidth and img.naturalHeight. Have a look at his answer.

Legacy answer compatible with super old browsers

// find the element
var img = $('#imageid');

/* 
 * create an offscreen image that isn't scaled
 * but contains the same image.
 * Because it's cached it should be instantly here.
 */

var theImage = new Image();
theImage.src = img.attr("src");

// you should check here if the image has finished loading
// this can be done with theImage.complete

alert("Width: " + theImage.width);
alert("Height: " + theImage.height);
like image 195
Georg Schölly Avatar answered Oct 15 '22 01:10

Georg Schölly


This should work:

var img = $('#imageid')[0]; //same as document.getElementById('imageid');
var width = img.naturalWidth;
var height = img.naturalHeight;

The naturalWidth and naturalHeight return the size of the image response, not the display size.

According to Josh' comment this is not supported cross browser, this might be correct, I tested this in FF3

like image 42
Pim Jager Avatar answered Oct 15 '22 02:10

Pim Jager


EDIT - new idea... see http://jsbin.com/uzoza

  var fixedW = $("#imageToTest").width(); 
  $("#imageToTest").removeAttr("width"); 
  var realW = $("#imageToTest").width(); 
  $("#imageToTest").attr("width", fixedW); 

ORIGINAL ANSWER

see How to get image size (height & width) using JavaScript?

var img = $('#imageid'); 

var width = img.clientWidth;
var height = img.clientHeight;
like image 42
Josh Avatar answered Oct 15 '22 02:10

Josh