2

I have searched for this, but every time I implement the code it return 24 as height and width as 237 when I upload 400X400 image.

$(document).on('change','#tt' , function(){
    var img = document.getElementById('tt');
    var nheight = img.clientHeight;
    var nwidth = img.clientWidth;
    alert(nheight)
    alert(nwidth)
});
<input type="file" id="tt" name="tt" >

Is anyone know how can I get 400 as height and 400 as width in alert box when I upload 400X400 image. Any help is really much appreciated.....

3
  • 1
    You trying to get width and height of input not image. Commented Sep 24, 2016 at 18:42
  • Got that now..thanks. @Mohammad Commented Sep 24, 2016 at 18:50
  • img.naturalWidth and img.naturalHeight is correct answer. Commented Oct 9, 2019 at 5:29

2 Answers 2

5

Onchange event of file upload creating a Image object and attach uploaded file object as src to image object and then onload event of image object find height and width of image.

Please check below snippet for more understanding.

var _URL = window.URL || window.webkitURL;
$(document).on('change','#tt' , function(){    
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function () {
            alert("width : "+this.width + " and height : " + this.height);
        };
        img.src = _URL.createObjectURL(file);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="tt" name="tt" >

Sign up to request clarification or add additional context in comments.

2 Comments

URL.createObjectURL() is an experimental technology and doesn't support old version of browser.
It support to all latest browser. You can refer developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
1
var nheight = img.clientHeight;
var nwidth = img.clientWidth;

will just get you the dimension.

Refer this -

Try

var x = document.getElementById("myImg").naturalWidth;

the naturalHeight property to return the original height of an image, or the height property to set or return the value of the height attribute of an image

http://www.w3schools.com/jsref/prop_img_naturalwidth.asp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.