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

有没有任何jQuery或纯JS API或方法来获取页面上的图像的维度?

clientWidth和clientHeight是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; 

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

 var img = new Image(); img.onload = function() { alert(this.width + 'x' + this.height); } img.src = 'http://www.google.com/intl/en_ALLhttp://img.dovov.comlogo.gif'; 

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

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

 imageElement.naturalHeight 

 imageElement.naturalWidth 

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

如果你正在使用jQuery,你正在请求图像大小,你必须等待,直到他们加载或者只能得到零。

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

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

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

首先,我使用了一个名为Dash的程序来获取图像API的概述。 它指出heightwidth是图像的渲染高度/宽度,而naturalHeightnaturalWidth是图像的固有高度/宽度(仅限于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 

使用JQuery你这样做:

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

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

您只能使用加载事件的callback才能真正做到这一点,因为在实际完成加载之前,图像的大小是未知的。 像下面的代码…

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

好吧,我想我改进了源代码,以便能够让图像加载之前,试图找出它的属性,否则将显示“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']); } 

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

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

用jQuery库 –

使用.width().height()

更多在jQuery的宽度和jQuery heigth 。

示例代码 –

 $(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> <img id="img_exmpl" src="http://images.all-free-download.comhttp://img.dovov.comgraphicthumb/beauty_of_nature_9_210287.jpg"> <button>Display dimensions of img</button> 

这个答案正是我所期待的(在jQuery中):

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

JQuery答案:

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

简单地说,你可以像这样testing。

  <script> (function($) { $(document).ready(function() { console.log("ready...."); var i = 0; var img; for(i=1; i<13; i++) { img = new Image(); img.src = 'img/' + i + '.jpg'; console.log("name : " + img.src); img.onload = function() { if(this.height > 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> 

Nicky De Maeyer问了一张背景图片, 我只是从CSS获取它,并replace“url()”:

 var div = $('#my-bg-div'); var url = div.css('background-image').replace(/^url\(\'?(.*)\'?\)$/, '$1'); var img = new Image(); img.src = url; console.log('img:', img.width + 'x' + img.height); // zero, image not yet loaded console.log('div:', div.width() + 'x' + div.height()); img.onload = function() { console.log('img:', img.width + 'x' + img.height, (img.width/div.width())); } 
 var img = document.getElementById("img_id"); alert( img.height + " ;; " + img .width + " ;; " + img .naturalHeight + " ;; " + img .clientHeight + " ;; " + img.offsetHeight + " ;; " + img.scrollHeight + " ;; " + img.clientWidth + " ;; " + img.offsetWidth + " ;; " + img.scrollWidth ) //But all invalid in Baidu browser 360 browser ... 

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

 // create image with a reference id. Id shall be used for removing it from the dom later. var tempImg = $('<img id="testImage" />'); //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'; 

这会给你的高度,而不是原来的宽度或零。

当页面加载到js或jquery中时,可以应用onload处理程序属性: –

 $(document).ready(function(){ var width = img.clientWidth; var height = img.clientHeight; }); 
 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_ALLhttp://img.dovov.comlogo.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. 

这是我的方法,希望这有帮助。 🙂

你也可以使用:

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

从父div中删除浏览器解释的设置很重要。 所以如果你想要真正的图像宽度和高度,你可以使用

 $('.right-sidebar').find('img').each(function(){ $(this).removeAttr("width"); $(this).removeAttr("height"); $(this).imageResize(); }); 

这是我从一个TYPO3项目的例子,我需要图像的真实属性,以正确的关系进行缩放。

 function outmeInside() { var output = document.getElementById('preview_product_image'); if (this.height < 600 || this.width < 600) { output.src = "http://localhost/danieladenew/uploads/no-photo.jpg"; alert("The image you have selected is low resloution image.Your image width=" + this.width + ",Heigh=" + this.height + ". Please select image greater or equal to 600x600,Thanks!"); } else { output.src = URL.createObjectURL(event.target.files[0]); } return; } img.src = URL.createObjectURL(event.target.files[0]); } 

这项工作为多个图像预览和上传。 如果您必须逐一select每个图像。 然后复制并进入所有的预览图像function并validation!

在获取元素的属性之前,文档页面应该是onload:

 window.onload=function(){ console.log(img.offsetWidth,img.offsetHeight); }