首页 > 解决方案 > 上传前如何检查图像尺寸(宽 x 高)?

问题描述

我正在使用 JavaScript 代码在 FireBase/FireStore 中上传图像。

核心功能已经可以了,我可以上传,但上传前还需要检查图片的大小。这就是我很乐意得到帮助的地方。

以下是我的重要代码。和行之间的部分:

// Trying to get the size:

和:

// End of trial code.

不管用。

upLdBtn.addEventListener('change', function(e) {
    // Get the file.
    var artWorkFile = e.target.files[0];

    // Trying to get the size:
    var img = new Image();
    img.onload = function() {
        window.alert('Size = ' + this.width + 'x' + this.height);
    }
    img.src = artWorkFile;
    // End of trial code.

    DoSomthingUseful(artWorkFile);
});

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


首先,我们需要设置上传 img frominput到一个img容器 src,从这个img元素之后,我们可能会得到图像的原始宽度和高度值。

这是代码片段:

function setSrc(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
      $('#proImg').attr('src', e.target.result);
    };

    reader.readAsDataURL(input.files[0]);
  }
}

$("#imgInp").change(function () {
  setSrc(this);
  setTimeout(getImgRatio,300);
});
function getImgRatio(){
 var imgStyleProp = getComputedStyle(proImg);
      var w =imgStyleProp.width;
      var h =imgStyleProp.height;
      console.log(w+"/"+h);
}
img{
 width:initial;
 height:initial;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="imgInp" required="required" class="custom-file-input">
<img id="proImg" src=""/>


推荐阅读