如何使用JavaScript获取图像的尺寸(高度和宽度)

734

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


18
使用现代浏览器很容易:http://davidwalsh.name/get-image-dimensions - Yarin
5
下面的大多数答案只是获取样式的宽度和高度,而不是实际图像的宽度和高度。使用imgElement.naturalWidthimgElement.naturalHeight来获取宽度和高度。 - Bamdad
无论您想使用JavaScript还是jQuery,在浏览器中显示图像至关重要。实际上,图像和父元素都不能有规则display:none; - Vincenzo Di Gaetano
33个回答

911

您可以使用JavaScript编程获取图像并检查其尺寸...

const img = new Image();
img.onload = function() {
  alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

如果图像不是标记的一部分,则这可能很有用。


472

clientWidthclientHeight是DOM属性,用于显示DOM元素内部尺寸(不包括边距和边框)在浏览器中的当前大小。因此,在IMG元素的情况下,这将获取可见图像的实际尺寸。

var img = document.getElementById('imageid'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;

38
@Nicky说得非常准确。它给出了图像在该实例中呈现时的尺寸。 - Rex M
8
$.fn.width$.fn.height 是 jQuery 中的两个方法,用于获取或设置元素的宽度和高度。这两个方法可以用于几乎所有 HTML 元素,包括块级元素和行内元素。调用这些方法时可以传递一个参数来设置元素的宽度或高度,也可以不传递参数以获取当前元素的宽度或高度。 - yckart
252
正确答案是使用img.naturalWidth和img.naturalHeight。 - Octopus
7
document.getElementById 的输入更长,但比 $('#...')[0] 快10倍。 - bfontaine
20
在Chrome 35上,速度快了16倍:http://jsperf.com/document-getelementbyid-vs-jquery/5 - bfontaine
显示剩余2条评论

463

除了Rex和Ian的回答外,还有:

imageElement.naturalHeight

imageElement.naturalWidth

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


谢谢。在将一些图像插入数据库之前,我遇到了获取宽度和高度的问题。由于某种原因,图像的尺寸会变成0x0。将"clientWidth"和"clientHeight"替换为这个方法后,我成功解决了这个bug(希望如此)。需要等待并观察未来的情况,因为当它开始固定在0x0时,我以为另一种方法也能正常工作。这个方法同样有效,但是一旦页面刷新,它会插入正确的尺寸。谢谢。 - Wayne Barron
谢谢。在将一些图像插入数据库之前,我遇到了获取图像宽度和高度的问题。由于某种原因,图像的尺寸为0x0。在将"clientWidth"和"clientHeight"替换为这个代码后,我成功解决了这个错误(希望如此)。需要等待并观察未来的情况,因为当它开始固定在0x0时,我原本认为另一种方法也是有效的。这个方法同样有效,但是一旦页面刷新,它会插入正确的尺寸。谢谢。 - undefined

113

如果你正在使用jQuery并请求图像大小,那么你必须等待它们加载完成,否则你只会得到零值。

$(document).ready(function() {
    $("img").load(function() {
        alert($(this).height());
        alert($(this).width());
    });
});

在加载处理程序中,宽度和高度是否总是可用? - Anders Lindén
@AndersLindén - 请查看Akseli添加的有关加载事件的链接。其中有一个专门讨论图片的部分。从技术上讲,答案是否定的,但实际上我们使用这种方法的网站从来没有出现过问题。 - mrtsherman
但如果技术上的答案是否定的,那它就没用了吗?不是吗? - Anders Lindén
在图像加载之前获取图像属性是否可能? - no nein

104

我认为使用clientWidthclientHeight已经过时了。

我进行了一些HTML5实验,查看实际返回的值。

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

它说明heightwidth是图像的渲染高度/宽度,而naturalHeightnaturalWidth是图像的固有高度/宽度(仅适用于HTML5)。

我使用了一张美丽的蝴蝶图片,宽度为400,高度为300的文件,并运行了以下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

1
“我认为现在已经过时了”,这是什么意思?你是指已被弃用?还是已被移除?而且你确定吗?如果我要依赖一个答案,“我认为”并不是很令人放心。 - TylerH

65

使用jQuery,你可以这样做:

var imgWidth = $("#imgIDWhatever").width();

67
如果图片还没有加载呢? - James Westgate

27

其它人都忘了一件事,那就是在图片加载前你无法检查其尺寸。当作者检查所有已发布的方法时,这些方法可能只在本地主机上有效。

既然可以使用jQuery,则需要记住“ready”事件是在图像加载之前触发的。$('#xxx').width().height() 应该在onload事件或此后触发。


11
发布一些更新的代码,你可能会得到赞和甚至得到令人垂涎的“反转徽章”! - James Westgate

20

你只能在图像完成加载后才能知道它的大小,因此只能使用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';

2
在jQuery中,您可以使用$.proxy来实现此功能。 - Jochem Van Der Spek

19

让我们把在这里学到的东西结合成一个简单的函数(imageDimensions())。它使用promises

// helper to get dimensions of an image
const imageDimensions = file => 
    new Promise((resolve, reject) => {
        const img = new Image()

        // the following handler will fire after a successful loading of the image
        img.onload = () => {
            const { naturalWidth: width, naturalHeight: height } = img
            resolve({ width, height })
        }

        // and this handler will fire if there was an error with the image (like if it's not really an image or a corrupted one)
        img.onerror = () => {
            reject('There was some problem with the image.')
        }
    
        img.src = URL.createObjectURL(file)
})

// here's how to use the helper
const getInfo = async ({ target: { files } }) => {
    const [file] = files
 
    try {
        const dimensions = await imageDimensions(file)
        console.info(dimensions)
    } catch(error) {
        console.error(error)
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.0.0-beta.3/babel.min.js"></script>

Select an image:
<input
  type="file"
  onchange="getInfo(event)"
/>
<br />
<small>It works offline.</small>


谢谢您提供这段代码,但是在Firefox中,对于没有定义宽度和高度属性的SVG图像(例如,只设置了viewBox的图像),它返回0。 - Crashalot
@Crashalot,没错,这不适用于矢量图像,只适用于光栅图像。 - Neurotransmitter

12

获取自然高度和宽度:

document.querySelector("img").naturalHeight;
document.querySelector("img").naturalWidth;
<img src="img.png">

如果您想获取样式的高度和宽度:

document.querySelector("img").offsetHeight;
document.querySelector("img").offsetWidth;


最佳解决方案。应标记为官方答案。谢谢! - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接