How to get image size (height & width) using JavaScript?

前端 未结 29 3096
忘了有多久
忘了有多久 2020-11-21 05:23

Are there any JavaScript or jQuery APIs or methods to get the dimensions of an image on the page?

29条回答
  •  天涯浪人
    2020-11-21 05:47

    just pass the img file object which is obtained by the input element when we select the correct file it will give the netural height and width of image

    function getNeturalHeightWidth(file) {
         let h, w;
         let reader = new FileReader();
          reader.onload = () => {
            let tmpImgNode = document.createElement("img");
            tmpImgNode.onload = function() {
              h = this.naturalHeight;
              w = this.naturalWidth;
            };
            tmpImgNode.src = reader.result;
          };
          reader.readAsDataURL(file);
        }
       return h, w;
    }
    

提交回复
热议问题