views:

42

answers:

3

Hi,

I'm loading a background image into a div. Is it possible to get the dimensions from this image?

I'm trying to make a function that will replace text with images on the fly, for use in the menu.

$.fn.MenuImages = function() {
  return this.each(function(i) {
    var name = $(this).find('a').attr('title');
    $(this).css("background-image","url(images/menu-"+name+"-h.png)");
  });
};

Problem is that the images do not all have the same size. I'm not sure how to read the file's dimensions unless i load it in a hidden div or something, but that sounds so dirty. Any recommendations? Thanks!

Fixed:

$.fn.MenuImages = function() {
return this.each(function(i) {
    var link = $(this).find('a');
    var name = link.attr('title');
    link.html("<img src='images/menu-"+name+"-h.png' />");
});

};

A: 
var img=new Image();
img.onload=function(){
    alert(img.width);
    alert(img.height);
};
img.src="image.png";
Maz
A: 

Jquery

w = $("img").width();
h = $("img").height();

Ruby

IO.read('image.png')[0x10..0x18].unpack('NN')

This yields an array [width,height] which you can extract a[0] for width etc...

nicholasklick
+1  A: 
​$('<img src='images/menu-"+name+"-h.png' />')​.attr('src',function(){
    return $('body').css('background-image');
})​​​.load(function(){
    w = $(this).width();
    h = $(this).height();
})​;

This waits till the image is loaded to grab the height and width.

Mark