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


当前回答

简单地说,您可以像这样进行测试。

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

其他回答

在我的例子中,我有一个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')

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

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

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

只需传递input元素获得的“img”文件对象。当我们选择正确的文件时,它将给出图像的自然高度和宽度。

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

假设,我们想要得到<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将为我们提供元素在文档上呈现的尺寸。

我对jQuery的看法

免责声明:这并不一定能回答这个问题,但可以拓宽我们的能力。它在jQuery 3.3.1中进行了测试

让我们考虑一下:

你有图像的URL/路径,你想要得到图像的宽度和高度,而不是在DOM上渲染它, 在DOM上呈现图像之前,您需要将offsetParent节点或图像div包装器元素设置为图像的宽度和高度,以便为不同的图像大小创建一个流体包装器,即,当单击按钮以查看模式/灯箱上的图像时

我要这样做:

// 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}`);
})