Home > Web Front-end > JS Tutorial > body text

How to Retrieve Original Image Dimensions Cross Browser?

Susan Sarandon
Release: 2024-10-18 18:22:03
Original
658 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!