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


当前回答

尼基·德·梅耶要了一张背景照片;我只是从CSS内容中获取它,并替换“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()));
}

其他回答

在我的例子中,我有一个File类型(保证是一个图像),我想要图像的尺寸,而不是将其加载到DOM上。

一般策略:将文件转换为ArrayBuffer→将ArrayBuffer转换为base64字符串→使用此作为image类的图像源→使用naturalHeight和naturalWidth来获取维度。

const fr = new FileReader();
fr.readAsArrayBuffer(image); // Image the 'File' object
fr.onload = () => {
  const arrayBuffer: ArrayBuffer = fr.result as ArrayBuffer;

  // Convert to base64. String.fromCharCode can hit a stack overflow error if you pass
  // the entire arrayBuffer in, and iteration gets around this
  let binary = '';
  const bytes = new Uint8Array(arrayBuffer);
  bytes.forEach(b => binary += String.fromCharCode(b));
  const base64Data = window.btoa(binary);

  // Create an image object. Note, a default width/height MUST be given to the constructor (per
  // the documentation) or naturalWidth/Height will always return 0.
  const imageObj = new Image(100, 100);
  imageObj.src = `data:${image.type};base64,${base64Data}`;
  imageObj.onload = () => {
    console.log(imageObj.naturalWidth, imageObj.naturalHeight);
  }
}

这允许您从文件中获得图像尺寸和纵横比,而无需渲染它。它可以使用fromEvent轻松地将onload函数转换为RxJS Observables,以获得更好的异步体验:

// fr is the file reader, and this is the same as fr.onload = () => { ... }
fromEvent(fr, 'load')

其他所有人都忘记了的事情是,你不能在加载前检查图像大小。当作者检查所有发布的方法时,它可能只在本地主机上工作。

由于这里可以使用jQuery,请记住'ready'事件是在图像加载之前触发的。$('#xxx').width()和.height()应该在onload事件或以后触发。

jQuery的答案:

$height = $('#image_id').height();
$width  = $('#image_id').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 ...

这是我的方法:

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.