如何用JavaScript获得图片的大小(高度& 宽度)?

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

对该问题的评论 (1)

你可以用Javascript编程获取图片并检查尺寸......

<!--开始片段。 js hide: false console: true babel.false -->-- begin snippet: js hide: false console: true false -->

var img = new Image().onload = function() { img.onload = function() { alert(this.width + 'x'

如果图片不是标记的一部分,这很有用。

评论(13)

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;
评论(10)

另外(除了Rex和Ian'的答案之外)还有。

imageElement.naturalHeight

imageElement.naturalWidth

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

评论(6)

如果你使用jQuery,并且你要求图片的大小,你必须等到它们加载,否则你将只能得到零。

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

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

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

首先,我使用了一个名为Dash的程序来了解图像API的概况。 它指出,"height "和 "width "是图像的渲染高度/宽度,而 "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来表示高度和宽度。

结果:{{{5578595}}

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

/*Actual Rendered size*/    120                  150

然后我把HTML改成了下面的内容。

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

结果:{{{5578597}}

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

/*Actual Rendered size*/     90                  115

然后我把HTML改成了下面的内容。

即 同时使用属性和CSS,看哪个优先。

结果。

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

/*Actual Rendered size*/    120                  150
评论(2)

使用JQuery你可以做到这一点。

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

其他所有的人都忘了一件事,那就是你不能在加载之前检查图像的大小。 当作者检查所有发布的方法时,它可能只在本地主机上工作。 由于jQuery可以在这里使用,记住,'ready' 事件是在图片加载之前被触发的。 $('#xxx').width()和.height()应该在onload事件中或稍后启动。

评论(3)

你只能使用加载事件的回调来真正做到这一点,因为图像的大小在实际加载完成之前是不知道的。 就像下面的代码...

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';
评论(1)

用[jQuery][1] library-

使用.width().height()

更多内容请参考[jQuery width][2]和[jQuery heigth][3]。

示例代码

<!--开始片段。 js hide.false --> -- begin snippet: js hide: false -->

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


Display dimensions of img

[1]: https://jquery.com/ [2]: http://api.jquery.com/width/ [3]: http://api.jquery.com/height/

评论(0)

好吧,我想我改进了源码,在试图找出其属性之前,能够让图片加载,否则它会显示'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']);
}
评论(0)

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

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

这个][1]答案正是我想要的(jQuery)。

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

[1]: https://stackoverflow.com/a/30035502/2715309

评论(0)

假设,我们要获取图片尺寸为<img id="an-img&quot。 src"...">

// 在页面上所有元素加载完毕后进行查询。
// 或者,使用 "onload "来检查某个元素是否加载完毕。
document.addEventListener(&#39;DOMContentLoaded&#39;, function () {
var el = document.getElementById("an-img")。

console.log({
"naturalWidth"。
el.naturalWidth, //只在HTMLImageElement上使用。
"naturalHeight"。
el.naturalHeight, //只在HTMLImageElement上使用。
"offsetWidth"。
el.offsetWidth,
"offsetHeight"。
el.offsetHeight
});

自然尺寸

el.naturalWidthel.naturalHeight将得到[natural dimensions][1],即图像文件的尺寸。

布局尺寸

el.offsetWidthel.offsetHeight将得到元素在文档中呈现的尺寸。

[1]: https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-naturalwidth

评论(2)

JQuery回答。

$height = $('#image_id').height();
$width  = $('#image_id').width();
评论(1)

很简单,你可以这样测试。

  <script>
  (function($) {
        $(document).ready(function() {
            console.log("ready....");
            var i = 0;
            var img;
            for(i=1; i this.width) {
                        console.log(this.src + " : portrait");
                    }
                    else if(this.width > this.height) {
                        console.log(this.src + " : landscape");
                    }
                    else {
                        console.log(this.src + " : square");
                    }
                }
            }
        });
    }(jQuery));
  </script>
评论(0)

当页面在js或jquery中加载时,你可以像这样应用onload handler属性:-。

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

 });
评论(0)
var imgSrc, imgW, imgH;
function myFunction(image){
    var img = new Image();
    img.src = image;
    img.onload = function() {   
        return {
            src:image,
            width:this.width,
            height:this.height};
        }
    return img;
}
var x = myFunction('http://www.google.com/intl/en_ALL/images/logo.gif');
    //Waiting for the image loaded. Otherwise, system returned 0 as both width and height.
x.addEventListener('load',function(){
    imgSrc = x.src;
    imgW = x.width;
    imgH = x.height;
});
x.addEventListener('load',function(){
    console.log(imgW+'x'+imgH);//276x110
});
console.log(imgW);//undefined.
console.log(imgH);//undefined.
console.log(imgSrc);//undefined.

这是我的方法,希望对大家有所帮助。 :)

评论(0)

您也可以使用。

var image=document.getElementById("imageID");
var width=image.offsetWidth;
var height=image.offsetHeight;
评论(0)

最近我在flex滑块中出现了同样的问题,因为一个错误。 第一个图像'的高度设置较小,由于加载延迟。 我尝试了下面的方法来解决这个问题,它'的工作。

// create image with a reference id. Id shall be used for removing it from the dom later.
var tempImg = $('');
//If you want to get the height with respect to any specific width you set.
//I used window width here.
tempImg.css('width', window.innerWidth);  
tempImg[0].onload = function () {
    $(this).css('height', 'auto').css('display', 'none');
    var imgHeight = $(this).height();
    // Remove it if you don't want this image anymore.
    $('#testImage').remove();
}
//append to body
$('body').append(tempImg);
//Set an image url. I am using an image which I got from google.
tempImg[0].src ='http://aspo.org/wp-content/uploads/strips.jpg';

这将给你相对于你设置的宽度的高度,而不是原始宽度或零。

评论(0)

如果你不害怕使用Promises,你可以有一个像下面这样的简单函数(imageDimensions())。

<!--开始片段。 js hide: false console: true babel.true -->--开始snippet: js hide: false console: true true -->

const imageDimensions = file => new Promise((resolve, reject) => {
  try {
    const img = new Image()    
    img.onload = () => {
      const { naturalWidth: width, naturalHeight: height } = img
      resolve({ width, height })
    }
    img.onerror = () => {
      reject('There was some problem during the image loading')
    }
    img.src = URL.createObjectURL(file)
  } catch (error) {
    reject(error)
  }
})

const getInfo = ({ target: { files } }) => {
 const [file] = files
 imageDimensions(file)
   .then(result => {
     console.info(result)
   })
   .catch(error => {
     console.error(error)
   })
}
Select an image:
<input
  type="file"
  onchange="getInfo(event)"
/>

<!--结束片段-->

评论(0)