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


当前回答

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

其他回答

你还可以使用:

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

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

imageElement.naturalHeight

and

imageElement.naturalWidth

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

在使用真实图像大小之前,您应该加载源图像。如果使用jQuery框架,可以以简单的方式获得真实图像大小。

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

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

您可以通过编程方式获取图像并使用JavaScript检查尺寸…

const img = new Image(); img。Onload = function() { 警报(这。Width + 'x' + this.height); } img。src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

如果图像不是标记的一部分,这可能很有用。