Home >Web Front-end >JS Tutorial >How to Retrieve Original Image Dimensions Cross Browser?
Retrieving Original Image Dimensions Cross Browser
Determining the physical dimensions of an image resized client-side can be a challenge across different browsers. However, there are two reliable and framework-independent options available:
Option 1: Using offsetWidth and offsetHeight
Remove the width and height attributes from the image element ( tag). Then, use the offsetWidth and offsetHeight properties to retrieve the true width and height of the resized image:
<code class="javascript">const img = document.querySelector('img'); img.removeAttribute('width'); img.removeAttribute('height'); const width = img.offsetWidth; const height = img.offsetHeight;</code>
Option 2: Using JavaScript Image Object
Create a new JavaScript Image object, set its src attribute to the image URL, and then use the width and height properties to retrieve the original dimensions:
<code class="javascript">function getImgSize(imgSrc) { const newImg = new Image(); newImg.onload = function() { const width = newImg.width; const height = newImg.height; // Do something with the dimensions... }; newImg.src = imgSrc; }</code>
Note that in this option, the image doesn't have to be added to the page for it to load and have its dimensions determined.
The above is the detailed content of How to Retrieve Original Image Dimensions Cross Browser?. For more information, please follow other related articles on the PHP Chinese website!