How can I get the real image dimension with javascript?

I tried

function getImageSizeReal(imgLink){
	var img = new Image()
	img.src = imgLink;
	return [img.width, img.height];
}

However this only seems to be working sometimes in Opera . No luck in firefox or chrome (dunno about IE)

Anyways to do it?

I thought of maybe using an Ajax call, but then the imgLink cannot be a relative position, which would be difficult to parse due to some address like http://example.com/directory as i tried to get everything before the last /

return [img.width, img.height];

Try

return [img.clientWidth, img.clientHeight];

instead.

Note, however, that if you need to know the total area occupied by the element (not just the area of the actual image) you will have to deal with borders, etc.

You need to save the height and width in your function that preloads the image and then pass those back in the return.

var img = new Image();
img.src = "images/myImage.png";

var height = img.height;
var width = img.width;
return [width,height];

save the height and width in your function that preloads the image and then pass those back in the return.

Err, those won't be the current sizes on the screen.

Ignore the return[] business; I very copied carelessly.

The values .clientWidth and .clientHeight are properties of the object as it is currently rendered.

No the height and width here are the image's dimensions. The image isn't in the dom yet it's a preloaded image that is stored in the browser cache.

the height and width here are the image's dimensions.

That's what I was pointing out.
Unless I misunderstood the whole point of the question, the OP is looking for the current rendered size.

If you are trying to grab the dimension of an image right after your page is loaded, you could use a function in IE (can't remember the name of that function). Though, if you want it to be cross browser, you need to attach a variable flag to your window.onload. If the value in the onload is not set, keep calling your function using window.setTimeout(). If you don't get what I mean, please post again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.