图像的宽度和高度不会出现在jQuery中

时间:2016-04-14 13:21:20

标签: php jquery file filereader

我必须使用jQuery获取图像的宽度和高度,但我坚持到这里。 这里图片宽度和高度显示未定义,请建议我。 谢谢你的任何建议。

以下是代码

$(document).ready(function () {
  $("#file").change(function () {
      var files = this.files[0];
      var reader = new FileReader();
      var img = new Image();
      reader.onload = function (e) {
        img.src = e.target.result;
        var fileSize = Math.round(files.size / 1024);///output is coming.
        alert("File size is " + fileSize + " kb");
        alert("width=" + this.width + " height=" + this.height);//showing undefined
      };
      reader.readAsDataURL(files);
  });
});
<input type="file" class="cropit-image-input hii" id="file" style="display: none;" >

2 个答案:

答案 0 :(得分:2)

您可以使用img代替this

 alert("width=" + img.width + " height=" + img.height); 

&#13;
&#13;
$(document).ready(function() {
  $("#file").change(function() {
    var files = this.files[0];
    var reader = new FileReader();
    var img = new Image();
    reader.onload = function(e) {
      img.src = e.target.result;
      var fileSize = Math.round(files.size / 1024); ///output is coming.
      alert("File size is " + fileSize + " kb");
 
      alert("width=" + img.width + " height=" + img.height); //showing undefined

    };
    reader.readAsDataURL(files);

  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" class="cropit-image-input hii" id="file">
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我在桌面上查了一下。

当我更改this.width&amp; this.heightimg.width&amp;分别为img.height。它奏效了。

更改

alert("width=" + this.width + " height=" + this.height);//showing undefined

alert("width=" + img.width + " height=" + img.height);//showing undefined