"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 Can I Get Image Dimensions Using JavaScript?

How Can I Get Image Dimensions Using JavaScript?

Published on 2025-01-10
Browse:435

How Can I Get Image Dimensions Using JavaScript?

Determining Image Dimensions Using JavaScript

Do you need to programmatically access the dimensions of an image displayed on your web page? JavaScript offers a simple solution.

Solution:

JavaScript provides a straightforward approach to retrieve image dimensions:

  1. Create a new Image object:

    const img = new Image();
  2. Set the onload event listener to capture the image dimensions when it becomes available:

    img.onload = function() {
      alert(this.width   'x'   this.height);
    }
  3. Load the image:

    img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

Upon image loading, the onload event triggers and displays the image's width and height in an alert box. By using this technique, you can easily access the size of any image on your web page.

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