Aamir Aamir - 10 months ago 63
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.


<!DOCTYPE html>
<script src="jquery.min.js"></script>
$(document).on('change','#tt' , function(){
var img = document.getElementById('tt');
var nheight = img.clientHeight;
var nwidth = img.clientWidth;
<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.....

Answer Source

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