如何使用JavaScript获取图像大小(高度和宽度)?

San*_*eef 586 javascript jquery image jquery-plugins

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

Jos*_*ola 766

您可以使用Javascript以编程方式获取图像并检查尺寸...

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

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

  • 我刚在Firefox4中试过这个,它会输出0x0. (8认同)
  • IMO:这个问题的最佳答案.然后,如果您在需要时在DOM中加载了图像,那么确定. (6认同)
  • @ blo0p3r - 在此之前不需要将图像加载到DOM中.它加载图像,并触发onload以给我们尺寸.顺便说一句 - 这里最好的答案! (3认同)
  • img.onerror = function() { alert(0);// 未找到处理程序 } (2认同)

Rex*_*x M 426

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;
Run Code Online (Sandbox Code Playgroud)

  • 正确的答案是使用img.naturalWidth和img.naturalHeight (192认同)
  • @Nicky完全正确.它给出了在该实例中呈现的图像*的尺寸*. (32认同)
  • @RexM在Chrome 35上,速度提高了16倍:http://jsperf.com/document-getelementbyid-vs-jquery/5 (17认同)
  • @ Mat-visual` $ .fn.width`和`$ .fn.height`. (8认同)
  • `document.getElementById`输入的时间比`$('#...')[0]的快10倍. (5认同)

oll*_*iej 314

此外(除了雷克斯和伊恩的答案)还有:

imageElement.naturalHeight
Run Code Online (Sandbox Code Playgroud)

imageElement.naturalWidth
Run Code Online (Sandbox Code Playgroud)

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

  • IE9和所有现代Web浏览器现在都支持此功能. (14认同)

mrt*_*man 109

如果您正在使用jQuery并且要求图像大小,则必须等到它们加载或者您将只获得零.

$(document).ready(function() {
    $("img").load(function() {
        alert($(this).height());
        alert($(this).width());
    });
});
Run Code Online (Sandbox Code Playgroud)


pau*_*o62 97

我认为这些答案的更新很有用,因为其中一个最好的投票回复建议使用clientWidth和clientHeight,我认为现在已经过时了.

我已经用HTML5做了一些实验,看看实际返回了哪些值.

首先,我使用了一个名为Dash的程序来概述图像API.它表明heightwidth是图像的渲染高度/宽度,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());
Run Code Online (Sandbox Code Playgroud)

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

<img style="height:120px;width:150px;" id="img1" src="img/Butterfly.jpg" />
Run Code Online (Sandbox Code Playgroud)

结果:

/*Image Element*/ height == 300         width == 400
           naturalHeight == 300  naturalWidth == 400
/*Jquery*/      height() == 120       width() == 150

/*Actual Rendered size*/    120                  150
Run Code Online (Sandbox Code Playgroud)

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

<img height="90" width="115" id="img1" src="img/Butterfly.jpg" />
Run Code Online (Sandbox Code Playgroud)

即使用高度和宽度属性而不是内联样式

结果:

/*Image Element*/ height ==  90         width == 115
           naturalHeight == 300  naturalWidth == 400
/*Jquery*/      height() ==  90       width() == 115

/*Actual Rendered size*/     90                  115
Run Code Online (Sandbox Code Playgroud)

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

<img height="90" width="115" style="height:120px;width:150px;" id="img1" src="img/Butterfly.jpg" />
Run Code Online (Sandbox Code Playgroud)

即同时使用属性和CSS,以查看哪个优先.

结果:

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

/*Actual Rendered size*/    120                  150
Run Code Online (Sandbox Code Playgroud)


Ian*_*tle 62

使用JQuery你可以这样做:

var imgWidth = $("#imgIDWhatever").width();
Run Code Online (Sandbox Code Playgroud)

  • 如果图像还没有加载? (63认同)
  • 如果图像在div的background属性中?:) (11认同)
  • @JamesWestgate如果图像尚未加载,则无法确定其实际大小.但是,您可以尝试读取`img`元素的`width`和`height`属性. (3认同)

Thi*_*ker 25

所有其他人都忘记的事情是你无法在加载之前检查图像大小.当作者检查所有发布的方法时,它可能只在localhost上工作.由于jQuery可以在这里使用,请记住在加载图像之前触发'ready'事件.$('#xxx').width()和.height()应该在onload事件或更高版本中触发.

  • 发布一些更新的代码,您可能会获得投票,甚至获得梦寐以求的逆转徽章! (9认同)
  • 这不是答案.只是对其他答案的评论. (4认同)

小智 18

你只能使用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';
Run Code Online (Sandbox Code Playgroud)

  • 在 jquery 中,您可以使用 $.proxy 来实现此目的。 (2认同)

Tra*_*oud 14

让我们将在这里学到的所有内容组合成一个简单的函数 ( imageDimensions())。它使用承诺

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

        // the following handler will fire after the 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)
    }
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


小智 12

要获得自然高度和宽度:

document.querySelector("img").naturalHeight;
document.querySelector("img").naturalWidth;
Run Code Online (Sandbox Code Playgroud)
<img src="img.png">
Run Code Online (Sandbox Code Playgroud)

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

document.querySelector("img").offsetHeight;
document.querySelector("img").offsetWidth;
Run Code Online (Sandbox Code Playgroud)


San*_*eef 11

假设,我们想要获得的图像尺寸为 <img id="an-img" src"...">

// Query after all the elements on the page have loaded.
// Or, use `onload` on a particular element to check if it is loaded.
document.addEventListener('DOMContentLoaded', function () {
  var el = document.getElementById("an-img");

  console.log({
    "naturalWidth": el.naturalWidth, // Only on HTMLImageElement
    "naturalHeight": el.naturalHeight, // Only on HTMLImageElement
    "offsetWidth": el.offsetWidth,
    "offsetHeight": el.offsetHeight
  });

Run Code Online (Sandbox Code Playgroud)

自然尺寸

el.naturalWidth并将为el.naturalHeight我们提供自然尺寸,即图像文件的尺寸。

布局尺寸

el.offsetWidth并将为el.offsetHeight我们提供元素在文档上呈现的尺寸。

  • 只需对提供有用内容的现有答案进行投票即可;不要将其中的几个复制到新的中;那么你只是在复制内容。 (4认同)

Abr*_*hin 8

使用jQuery库 -

使用.width().height().

更多jQuery宽度jQuery高度.

示例代码 -

$(document).ready(function(){
    $("button").click(function()
    {
        alert("Width of image: " + $("#img_exmpl").width());
        alert("Height of image: " + $("#img_exmpl").height());
    });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<img id="img_exmpl" src="http://images.all-free-download.com/images/graphicthumb/beauty_of_nature_9_210287.jpg">
<button>Display dimensions of img</button>
Run Code Online (Sandbox Code Playgroud)


小智 7

好的家伙,我认为我改进了源代码,以便能够在尝试查找其属性之前加载图像,否则它将显示"0*0",因为下一个语句将在文件加载到之前被调用浏览器.需要jquery ......

function getImgSize(imgSrc){
    var newImg = new Image();
    newImg.src = imgSrc;
    var height = newImg.height;
    var width = newImg.width;
    p = $(newImg).ready(function(){
        return {width: newImg.width, height: newImg.height};
    });
    alert (p[0]['width']+" "+p[0]['height']);
}
Run Code Online (Sandbox Code Playgroud)


小智 6

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

$("ImageID").load(function(){
  console.log($(this).width() + "x" + $(this).height())
})
Run Code Online (Sandbox Code Playgroud)


Bri*_*ian 6

认为这可能对 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";
Run Code Online (Sandbox Code Playgroud)

这是对的:

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

结论:

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


dev*_*101 5

这个答案正是我在jQuery中寻找的:

var imageNaturalWidth = $('image-selector').prop('naturalWidth');
var imageNaturalHeight = $('image-selector').prop('naturalHeight');
Run Code Online (Sandbox Code Playgroud)