"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Determine the Original Image Size After Client-Side Resizing Across Browsers?

How to Determine the Original Image Size After Client-Side Resizing Across Browsers?

Published on 2024-11-09
Browse:836

How to Determine the Original Image Size After Client-Side Resizing Across Browsers?

Determining the Original Image Size Cross-Browser

Determining the original physical dimensions of an image that has been resized client-side can be a cross-browser challenge. However, there are reliable and framework-independent methods to achieve this:

Option 1: Dynamic Image Dimension Reading

Remove any predefined width and height attributes from the image HTML element. The system will automatically adjust the dimensions to fit display needs. Subsequently, utilize JavaScript to access the element's offsetWidth and offsetHeight properties, which represent the resized width and height.

Option 2: JavaScript Image Object

Create a JavaScript Image object and assign the resized image's source to its src property. Once the image has loaded, the object's width and height properties will hold the original dimensions. You can utilize the onload event to execute this operation asynchronously, ensuring that the image is fully loaded before retrieving the dimensions.

Code Example:

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; // Do this after setting `onload`
}

Note: If you encounter issues with large images not returning dimensions, consider using the onload event within the JavaScript object. This ensures that the image has fully loaded before accessing its properties.

Release Statement This article is reprinted at: 1729247237 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3