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

How to Determine Original Image Size Cross Browser?

Susan Sarandon
Release: 2024-10-18 18:23:29
Original
453 people have browsed it

How to Determine Original Image Size Cross Browser?

Determining Original Image Size Cross Browser

In web development, resizing images on the client side is a common practice to optimize page performance and responsiveness. However, determining the original physical dimensions of a resized image can be challenging due to browser inconsistencies. This article explores two reliable, framework-independent options for obtaining this information.

Option 1: Using OffsetWidth and OffsetHeight

This method involves removing the explicit width and height attributes from the element. Subsequently, you can access the offsetWidth and offsetHeight properties to retrieve the actual width and height of the resized image. This option is simple and supported by most major browsers.

Option 2: Using JavaScript Image Object

The second approach involves creating a JavaScript Image object, setting its src attribute to the image's source, and accessing its width and height properties. Note that the image does not need to be added to the page for this to work.

Here's an example code snippet:

<code class="javascript">function getImgSize(imgSrc) {
    var newImg = new Image();

    newImg.onload = function() {
      var height = newImg.height;
      var width = newImg.width;
      alert('The image size is ' + width + '*' + height);
    }

    newImg.src = imgSrc; // This must be done after setting onload
}</code>
Copy after login

Edit by Pekka:

To ensure accurate results with large images, the onload event of the image can be used to trigger the function. Otherwise, height and width may not be available before the image has finished loading.

The above is the detailed content of How to Determine Original Image Size 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!