Aamir Aamir - 2 months ago 9
Javascript Question

Get Image Dimensions (Height and Width) Js or jquery

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.

Code

<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
<script>
$(document).on('change','#tt' , function(){
var img = document.getElementById('tt');
var nheight = img.clientHeight;
var nwidth = img.clientWidth;
alert(nheight)
alert(nwidth)
});
</script>
</head>
<body>
<input type="file" id="tt" name="tt" >
</body>
</html>


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.....

Answer

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" >