是否有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')

其他回答

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

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

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

让我们将在这里学到的所有内容组合成一个简单的函数(imageDimensions())。它使用承诺。

// helper to get dimensions of an image const imageDimensions = file => new Promise((resolve, reject) => { const img = new Image() // the following handler will fire after a successful loading of the image img.onload = () => { const { naturalWidth: width, naturalHeight: height } = img resolve({ width, height }) } // and this handler will fire if there was an error with the image (like if it's not really an image or a corrupted one) img.onerror = () => { reject('There was some problem with the image.') } img.src = URL.createObjectURL(file) }) // here's how to use the helper const getInfo = async ({ target: { files } }) => { const [file] = files try { const dimensions = await imageDimensions(file) console.info(dimensions) } catch(error) { console.error(error) } } <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.0.0-beta.3/babel.min.js"></script> Select an image: <input type="file" onchange="getInfo(event)" /> <br /> <small>It works offline.</small>

clientWidth和clienttheight是DOM属性,显示DOM元素内部维度的当前浏览器大小(不包括边距和边框)。在IMG元素的情况下,这将得到可见图像的实际尺寸。

var img = document.getElementById('imageid'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;

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

imageElement.naturalHeight

and

imageElement.naturalWidth

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

这是Node.js的替代答案。这可能不是OP的意思,但它可能会派上用场,似乎在问题的范围内。

这是一个使用Node.js的解决方案,该示例使用Next.js框架,但它可以与任何Node.js框架一起工作。它使用探针图像大小的NPM包从服务器端解析图像属性。

示例用例:我使用下面的代码从Airtable Automation脚本解析图像的大小,该脚本调用我自己的analyzeImage API并返回图像的道具。

import {
  NextApiRequest,
  NextApiResponse,
} from 'next';
import probe from 'probe-image-size';

export const analyzeImage = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
  try {
    const result = await probe('http://www.google.com/intl/en_ALL/images/logo.gif');

    res.json(result);
  } catch (e) {
    res.json({
      error: true,
      message: process.env.NODE_ENV === 'production' ? undefined : e.message,
    });
  }
};

export default analyzeImage;

收益率:

{
"width": 276,
"height": 110,
"type": "gif",
"mime": "image/gif",
"wUnits": "px",
"hUnits": "px",
"length": 8558,
"url": "http://www.google.com/intl/en_ALL/images/logo.gif"
}