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


当前回答

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

$(document).ready(function() {
    $("img").load(function() {
        alert($(this).height());
        alert($(this).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 ...

Use

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 resolution image. Your image width=" + this.width + ", height=" + 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]);
}

这适用于多个图像预览和上传。如果你必须为每个图像逐一选择,然后复制粘贴到所有预览图像功能和验证!!

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

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

假设,我们想要得到<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
  });
})

自然维度

埃尔。naturalWidth和el。naturalHeight会得到图像文件的自然尺寸。

布局尺寸

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

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