Danny
Danny

Reputation: 327

How to read an image from the localhost url and get its width and height in javascript

Hey guys I am new to javascript and react, I want to get the image's width and height when its loaded from the image url. How to do it? Help would be much appreciated.

I know it starts with this but doesn't really understand how to continue..

const imageDimension = (img) => {
   let reader = new FileReader();
   

}

Thanks

Upvotes: 2

Views: 322

Answers (2)

fortunee
fortunee

Reputation: 4332

The "load" event listener works if the image is going to be loaded in the browser.

However, if that is not the case, and you really don't want the image to be visible then you could do this.

const getImageDimension = (imgUrl) => {
  const img = new Image();
  
  // set some styles to hide the img
  img.src = imgUrl;
  img.style.left = -9999;
  img.style.position = 'absolute';
  img.style.visibility = 'hidden';
  
  // inject it into the page
  document.body.appendChild(img);

  // resolve when image has been injected and
  // img.height and width is available
  return new Promise((resolve) => {
    const interval = setInterval(() => {
      const height = img.naturalHeight;
      const width = img.naturalWidth;

      if (height && width) {
        clearInterval(interval);
        document.body.removeChild(img);
        resolve({
          height,
          width,
        })
      }
    })
  })
}

const SAMPLE_IMAGE = "https://asia.olympus-imaging.com/content/000107507.jpg";

getImageDimension(SAMPLE_IMAGE)
.then((dimension) => console.log(dimension))

Upvotes: 0

badsyntax
badsyntax

Reputation: 9650

You can use the load event:

const image = new Image();

image.addEventListener('load', () => {
  console.log('image height', image.height);
  console.log('image width', image.width);
})

image.src = 'http://localhost/image.png'

Upvotes: 4

Related Questions