Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
133
rated 0 times [  137] [ 4]  / answers: 1 / hits: 33380  / 11 Years ago, thu, may 2, 2013, 12:00:00

I have this code so far:



var img = document.getElementById('draggable');
var width = img.clientWidth;
var height = img.clientHeight;


However this gets me the html attributes - css styles. I want to get dimensions of the actual image resource, of the file.



I need this because upon uploading an image, it's width gets set to 0px and I have no idea why or where this is happening. To prevent it I want to get the actual dimension and reset them. Is this possible?



Edit: Even when I try to get naturalWidth I get 0 as a result. I've added a picture. The weird thing is that it only happens when I upload new files and upon refresh it's working as it should.



http://oi39.tinypic.com/3582xq9.jpg


More From » jquery

 Answers
45

You could use naturalWidth and naturalHeight, these properties contain the actual, non-modified width and height of the image, but you have to wait until the image has loaded to get them



var img = document.getElementById('draggable');

img.onload = function() {
var width = img.naturalWidth;
var height = img.naturalHeight;
}


This is only supported from IE9 and up, if you have to support older browser you could create a new image, set it's source to the same image, and if you don't modify the size of the image, it will return the images natural size, as that would be the default when no other size is given



var img     = document.getElementById('draggable'),
new_img = new Image();

new_img.onload = function() {
var width = this.width,
heigth = this.height;
}

new_img.src = img.src;


FIDDLE


[#78471] Tuesday, April 30, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isaacvalentinn

Total Points: 325
Total Questions: 120
Total Answers: 131

Location: North Korea
Member since Tue, Jun 16, 2020
4 Years ago
isaacvalentinn questions
Mon, Jan 18, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Wed, Sep 23, 20, 00:00, 4 Years ago
;