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


当前回答

你只能使用load事件的回调来做到这一点,因为图像的大小直到它实际完成加载才知道。类似于下面的代码……

var imgTesting = new Image();

function CreateDelegate(contextObject, delegateMethod)
{
    return function()
    {
        return delegateMethod.apply(contextObject, arguments);
    }
}

function imgTesting_onload()
{
    alert(this.width + " by " + this.height);
}


imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
imgTesting.src = 'yourimage.jpg';

其他回答

此外(除了Rex和Ian的回答)还有:

imageElement.naturalHeight

and

imageElement.naturalWidth

它们提供了图像文件本身的高度和宽度(而不仅仅是图像元素)。

在使用真实图像大小之前,您应该加载源图像。如果使用jQuery框架,可以以简单的方式获得真实图像大小。

$("ImageID").load(function(){
  console.log($(this).width() + "x" + $(this).height())
})

其他所有人都忘记了的事情是,你不能在加载前检查图像大小。当作者检查所有发布的方法时,它可能只在本地主机上工作。

由于这里可以使用jQuery,请记住'ready'事件是在图像加载之前触发的。$('#xxx').width()和.height()应该在onload事件或以后触发。

我认为,使用clientWidth和clientHeight已经过时了。

我用HTML5做了一些实验,看看哪些值实际上会被返回。

首先,我使用了一个名为Dash的程序来获得图像API的概述。

它声明了高度和宽度是图像的渲染高度/宽度,而naturalHeight和naturalWidth是图像的固有高度/宽度(仅适用于HTML5)。

我使用了一个高300,宽400的文件中一个美丽的蝴蝶的图像。下面是JavaScript代码:

var img = document.getElementById("img1");

console.log(img.height,           img.width);
console.log(img.naturalHeight,    img.naturalWidth);
console.log($("#img1").height(),  $("#img1").width());

然后我使用这个HTML,内联CSS的高度和宽度。

<img style="height:120px;width:150px;" id="img1" src="img/Butterfly.jpg" />

结果:

/* Image element */ height == 300         width == 400
             naturalHeight == 300  naturalWidth == 400
/* jQuery */      height() == 120       width() == 150

/* Actual rendered size */    120                  150

然后我将HTML更改为以下内容:

<img height="90" width="115" id="img1" src="img/Butterfly.jpg" />

也就是说,使用高度和宽度属性而不是内联样式。

结果:

/* Image element */ height ==  90         width == 115
             naturalHeight == 300  naturalWidth == 400
/* jQuery */      height() ==  90       width() == 115

/* Actual rendered size */     90                  115

然后我将HTML更改为以下内容:

<img height="90" width="115" style="height:120px;width:150px;" id="img1" src="img/Butterfly.jpg" />

也就是说,同时使用属性和CSS来查看哪个优先级。

结果:

/* Image element */ height ==  90         width == 115
             naturalHeight == 300  naturalWidth == 400
/* jQuery */      height() == 120       width() == 150

/* Actual rendered size */    120                  150

只需传递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;
}