Home >Web Front-end >JS Tutorial >How to Determine Original Image Dimensions Despite Browser Resize?

How to Determine Original Image Dimensions Despite Browser Resize?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-18 18:24:03422browse

How to Determine Original Image Dimensions Despite Browser Resize?

Cross-Browser Determination of Original Image Dimensions

Determining the original size of an image that has been resized on the client side can be a challenge due to browser inconsistencies. However, there are a couple of reliable, framework-independent options you can consider:

Option 1: Remove Attributes and Read Offsets

Remove the width and height attributes from the image tag. This allows you to read the offsetWidth and offsetHeight properties to obtain the actual physical dimensions of the image.

Option 2: Create JavaScript Image Object

Create a JavaScript Image object and set its src attribute to the image source. Then, read the width and height properties of the object. You do not need to add the image to the page for this method to work. Here's an example function:

<code class="html">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;
}</code>

Note: As mentioned in the comments, it's important to run the function on the onload event of the image to ensure that the image is fully loaded before trying to read its dimensions.

The above is the detailed content of How to Determine Original Image Dimensions Despite Browser Resize?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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