Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 19, 2024 . #HowTo . #image

JavaScript Get Image Width And Height From URL

In this article, you are going to learn how to retrieve the width and height of an image using JavaScript directly from its URL.

Method 1: Using the Image Object

To accomplish this, we can create a new Image() object in JavaScript and set its source to the desired image URL. Then, we can use the onload event to ensure the image is loaded before extracting its dimensions.

<script>
  const imageUrl = 'https://app.3schools.in/logo.jpg';
  const img = new Image();

  img.onload = function() {
    const width = this.width;
    const height = this.height;

    console.log(`Width: ${width}, Height: ${height}`);
  };

  img.src = imageUrl;
</script>
  1. We create an Image() object and assign the image URL.
  2. The onload event ensures the image is loaded before extracting its dimensions.

Method 2: Fetch API with Blob

Another approach involves using the Fetch API to retrieve the image as a Blob. This allows us to use the createObjectURL function to create a URL for the Blob and get the image dimensions.

<script>
  const imageUrl = 'https://app.3schools.in/logo.jpg';

  fetch(imageUrl)
    .then(response => response.blob())
    .then(blob => {
      const img = new Image();
      img.src = URL.createObjectURL(blob);

      img.onload = function() {
        const width = this.width;
        const height = this.height;

        console.log(`Width: ${width}, Height: ${height}`);
      };
    });
</script>
  1. The script fetches the image as a Blob using the Fetch API.
  2. createObjectURL creates a URL for the Blob, which is assigned to the src attribute of the Image object.
  3. Then the image dimensions are extracted after the image is loaded.

Conclusion

In this article, you learned two methods to get the width and height of an image using JavaScript from its url.

The first method uses the Image object, while the second method involves the Fetch API and Blobs.

save
listen
AI Answer
1 Answer
  1. You can also use the naturalWidth and naturalHeight properties of the Image object for a more straightforward method.<script>
    const imageUrl = 'https://app.3schools.in/logo.jpg';
    const img = new Image();

    img.src = imageUrl;
    img.onload = () =>{
    const width = img.naturalWidth;
    const height = img.naturalHeight;
    console.log(`Width: ${width}, Height: ${height}`);
    };
    </script>
    Reply Delete
    Share
Write Your Answer
loading
back
View All