How to get the original size of an image using JavaScript All In One
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
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
https://stackoverflow.com/questions/77120785/display-images-side-by-side-with-equal-height
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17731964.html
未经授权禁止转载,违者必究!