Getting the Size of an Image Using JavaScript

In web development, you may encounter scenarios where you need to determine the size (width and height) of an image dynamically using JavaScript.

This information can be useful for various purposes, such as responsive design, image optimization, or displaying image dimensions to users.

In this article, we'll explore how to use JavaScript to get the size of an image.

Using the Image Object

The Image object in JavaScript provides a way to work with images dynamically.

By creating an Image object and setting its src attribute to the image URL, you can load the image asynchronously and obtain its dimensions once it's loaded.

Let's create a simple function to get the size of an image:

// Function to get the size of an image
function getImageSize(imageUrl) {
  // Create a new Image object
  const img = new Image();

  // Set the image URL
  img.src = imageUrl;

  // Wait for the image to load
  img.onload = function() {
    // Access the image dimensions
    const width = img.width;
    const height = img.height;

    // Log or use the dimensions as needed
    console.log(`Image dimensions: ${width} x ${height}`);
  };
}

In this code:

Example: Getting Image Size on Button Click

Let's create a complete example where clicking a button triggers the retrieval of an image's size:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Image Size Example</title>
  <style>
    /* Optional styling for better presentation */
    body {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100vh;
      margin: 0;
    }

    button {
      padding: 10px;
      font-size: 16px;
      cursor: pointer;
    }
  </style>
</head>
<body>

  <button onclick="getImageSize('example-image.jpg')">Get Image Size</button>

  <script>
    // Function to get the size of an image
    function getImageSize(imageUrl) {
      // Create a new Image object
      const img = new Image();

      // Set the image URL
      img.src = imageUrl;

      // Wait for the image to load
      img.onload = function() {
        // Access the image dimensions
        const width = img.width;
        const height = img.height;

        // Log or use the dimensions as needed
        console.log(`Image dimensions: ${width} x ${height}`);
      };
    }
  </script>
</body>
</html>

In this example:

Conclusion

Obtaining the size of an image dynamically using JavaScript is a valuable capability for web developers.

By using the Image object and waiting for the image to load, you can access its dimensions and use the information for various purposes in your web applications.

Incorporate this technique into your projects to work with images more effectively and provide a better user experience.