admin管理员组

文章数量:1319001

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

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

Share Improve this question edited Sep 24, 2016 at 18:55 Mohammad 21.5k16 gold badges56 silver badges84 bronze badges asked Sep 24, 2016 at 18:35 AamirAamir 2,2832 gold badges33 silver badges61 bronze badges 3
  • 1 You trying to get width and height of input not image. – Mohammad Commented Sep 24, 2016 at 18:42
  • Got that now..thanks. @Mohammad – Aamir Commented Sep 24, 2016 at 18:50
  • img.naturalWidth and img.naturalHeight is correct answer. – Kamlesh Commented Oct 9, 2019 at 5:29
Add a ment  | 

2 Answers 2

Reset to default 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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="tt" name="tt" >

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./jsref/prop_img_naturalwidth.asp

本文标签: javascriptGet Image Dimensions (Height and Width) Js or jqueryStack Overflow