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

如何使用JavaScript获取图像大小(高度和宽度)?,javascript,jquery,image,Javascript,Jquery,Image,是否有任何JavaScript或jQuery API或方法可以获取页面上图像的维度?并且是显示DOM元素内部维度(不包括边距和边框)的当前浏览器内大小的DOM属性。因此,对于IMG元素,这将得到可见图像的实际尺寸 var img = document.getElementById('imageid'); //or however you get a handle to the IMG var width = img.clientWidth; var height = img.clientHei

是否有任何JavaScript或jQuery API或方法可以获取页面上图像的维度?

并且是显示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;

使用JQuery可以执行以下操作:

var imgWidth = $("#imgIDWhatever").width();
此外(除了雷克斯和伊恩的答案外),还有:

imageElement.naturalHeight


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

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

您还可以使用:

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

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

const img=new Image();
img.onload=函数(){
警报(this.width+'x'+this.height);
}

img.src=http://www.google.com/intl/en_ALL/images/logo.gif';您只能使用加载事件的回调来真正做到这一点,因为在图像实际加载完成之前,图像的大小是未知的。类似下面的代码

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';
JQuery答案:

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

好了,伙计们,我想我改进了源代码,使其能够在尝试查找其属性之前让图像加载,否则它将显示“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并请求图像大小,则必须等待它们加载,否则只能得到零

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

尼基·德·梅耶在一张背景照片后问道;我只是从css中获取它并替换“url()”:


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

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

我认为对这些答案的更新是有用的,因为一个投票结果最好的回复建议使用
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

<img style="height:120px;width:150px;" id="img1" src="img/Butterfly.jpg" />
然后,我将HTML更改为以下内容:

<img height="90" width="115" id="img1" src="img/Butterfly.jpg" />
<img height="90" width="115" style="height:120px;width:150px;" id="img1" src="img/Butterfly.jpg" />
然后,我将HTML更改为以下内容:

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

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

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

这是我的一个TYPO3项目示例,我需要图像的真实属性以正确的关系缩放它

最近,我在flex滑块中遇到了同样的问题。由于加载延迟,第一个图像的高度设置得更小。我尝试了下面的方法来解决这个问题,效果很好

// 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';
//使用引用id创建图像。id将用于以后从dom中删除它。
var tempImg=$('

这将为您提供相对于所设置宽度的高度,而不是原始宽度或零。

当页面在js或jquery中加载时,您可以应用onload handler属性,如下所示:-

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

 });
这是我的方法,希望对您有所帮助。:)

函数outmeInside(){
var output=document.getElementById('preview_product_image');
如果(此高度<600 | |此宽度<600){
output.src=”http://localhost/danieladenew/uploads/no-photo.jpg";
警告(“您选择的图像是低亮度图像。您的图像宽度=“+this.width+”,Heigh=“+this.height+”。请选择大于或等于600x600的图像,谢谢!”);
}否则{
output.src=URL.createObjectURL(event.target.files[0]);
}
返回;
}
img.src=URL.createObjectURL(event.target.files[0]);
}

这项工作的多个图像预览和上传。如果必须为每个图像逐个选择。然后复制并通过所有预览图像功能并验证

简单地说,您可以这样测试

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

(函数($){
$(文档).ready(函数(){
控制台日志(“就绪…”);
var i=0;
var-img;
对于(i=1;i此宽度){
log(this.src+“:肖像”);
}
else if(this.width>this.height){
log(this.src+“:横向”);
}
否则{
log(this.src+“:square”);
}
}
}
});
}(jQuery));
带库-

使用
.width()
.height()

更多的在和

示例代码-
$(文档).ready(函数(){
$(“按钮”)。单击(函数()
{
警报(“图像宽度:+$(“#img_exmpl”).Width();
警报(“图像高度:+$(“#img_exmpl”).Height();
});
});


显示img的尺寸在获取元素属性之前,文档页面应为onload:

window.onload=function(){
    console.log(img.offsetWidth,img.offsetHeight);
}
答案正是我想要的(在jQuery中):


让我们把在这里学到的所有知识组合成一个简单的函数(
imageDimensions()
)。它使用

//获取图像尺寸的助手
常量imageDimensions=文件=>
新承诺((解决、拒绝)=>{
常量img=新图像()
//
$(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_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.
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]);
}
  <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>
window.onload=function(){
    console.log(img.offsetWidth,img.offsetHeight);
}
var imageNaturalWidth = $('image-selector').prop('naturalWidth');
var imageNaturalHeight = $('image-selector').prop('naturalHeight');
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;
}
import {
  NextApiRequest,
  NextApiResponse,
} from 'next';
import probe from 'probe-image-size';

export const analyzeImage = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
  try {
    const result = await probe('http://www.google.com/intl/en_ALL/images/logo.gif');

    res.json(result);
  } catch (e) {
    res.json({
      error: true,
      message: process.env.NODE_ENV === 'production' ? undefined : e.message,
    });
  }
};

export default analyzeImage;
{
"width": 276,
"height": 110,
"type": "gif",
"mime": "image/gif",
"wUnits": "px",
"hUnits": "px",
"length": 8558,
"url": "http://www.google.com/intl/en_ALL/images/logo.gif"
}
// image path
const imageUrl = '/path/to/your/image.jpg'

// Create dummy image to get real width and height
$('<img alt="" src="">').attr("src", imageUrl).on('load', function(){
    const realWidth = this.width;
    const realHeight = this.height;
    alert(`Original width: ${realWidth}, Original height: ${realHeight}`);
})