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


当前回答

这是我的方法:

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.

其他回答

此外(除了Rex和Ian的回答)还有:

imageElement.naturalHeight

and

imageElement.naturalWidth

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

要得到自然的高度和宽度:

.naturalHeight document.querySelector (img); .naturalWidth document.querySelector (img); < img src = " img.png " >

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

document.querySelector(“img”).offsetHeight; document.querySelector(“img”).offsetWidth;

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

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

最近我有同样的问题,在一个错误的伸缩滑块。由于加载延迟,第一张图像的高度被设置得较小。我尝试了以下方法来解决这个问题,它是有效的。

// Create an 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';

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

const file = event.target.files[0];
const img = new Image();
img.onload = function () {
  width = img.width;
  height = img.height;
};
img.src = URL.createObjectURL(file);
alert(width + "x" + height);