How to get the original size of an image using JavaScript All In One
如何使用 JavaScript 获取一个图片像的原始大小
naturalWidth
& naturalHeight
let output = document.querySelector(".output");
let image = document.querySelector("img");
window.addEventListener("load", (event) => {
output.innerHTML += `Natural size: ${image.naturalWidth} x ` + `${image.naturalHeight} pixels<br>`;
output.innerHTML += `Displayed size: ${image.width} x ` + `${image.height} pixels`;
});
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/naturalWidth
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/naturalHeight
Experimental ⚠️
https://developer.mozilla.org/en-US/docs/Web/API/PerformanceElementTiming/naturalWidth
https://developer.mozilla.org/en-US/docs/Web/API/PerformanceElementTiming/naturalHeight
WHATWG
The IDL attributes naturalWidth and naturalHeight must return the density-corrected natural width and height of the image, in CSS pixels, if the image has density-corrected natural width and height and is available, or else 0.
如果图像具有密度校正的自然宽度和高度并且可用,则 IDL 属性 naturalWidth 和 naturalHeight 必须返回图像的密度校正的自然宽度和高度(以 CSS 像素为单位),否则返回 0.
https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-naturalwidth
https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-naturalheight
https://caniuse.com/?search=naturalWidth %26 naturalHeight
demos
<img src="https://i.stack.imgur.com/deTzi.jpg?s=256&g=1" alt="xgqfrms's user avatar" width="128" height="128" class="bar-sm bar-md d-block">
const img = document.querySelector(`img`);
img.naturalHeight;
// 256
img.naturalWidth;
// 256
aspect ratio
/ 纵横比
Rendered size: 128 × 128 px
Rendered aspect ratio: 1∶1
Intrinsic size: 256 × 256 px
Intrinsic aspect ratio: 1∶1
File size: 27.0 kB
Current source: https://i.stack.imgur.com/deTzi.jpg?s=256&g=1
渲染尺寸:128 × 128 像素
渲染纵横比:1:1
内在尺寸:256 × 256 像素
固有长宽比:1:1
文件大小:27.0 kB
当前来源:https://i.stack.imgur.com/deTzi.jpg?s=256&g=1
https://stackoverflow.com/users/5934465/xgqfrms?tab=reputation