是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?


当前回答

只需传递input元素获得的“img”文件对象。当我们选择正确的文件时,它将给出图像的自然高度和宽度。

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;
}

其他回答

我认为这可能对2019年使用JavaScript和/或TypeScript的人有所帮助。

我发现以下内容是不正确的,就像一些人认为的那样:

let img = new Image();
img.onload = function() {
  console.log(this.width, this.height) // Error: undefined is not an object
};
img.src = "http://example.com/myimage.jpg";

这是正确的:

let img = new Image();
img.onload = function() {
  console.log(img.width, img.height)
};
img.src = "http://example.com/myimage.jpg";

结论:

在onload函数中使用img,而不是this。

jQuery的答案:

$height = $('#image_id').height();
$width  = $('#image_id').width();

当页面在JavaScript或jQuery中加载时,你可以像这样应用onload处理程序属性:

$(document).ready(function(){
   var width = img.clientWidth;
   var height = img.clientHeight;
 });

这个答案正是我所寻找的(在jQuery):

var imageNaturalWidth = $('image-selector').prop('naturalWidth');
var imageNaturalHeight = $('image-selector').prop('naturalHeight');

只需传递input元素获得的“img”文件对象。当我们选择正确的文件时,它将给出图像的自然高度和宽度。

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;
}