Felix
Felix

Reputation: 55

Get image width and height. src is proxy

I have a Vue component, in it I have an img, I need to get that image dimensions, preferably before showing the image (to fit in the container either by width or height).

this.img = new Image();
this.img.src = this.payload.src;
this.img.onload = () => {
  let width = this.img.naturalWidth;
  let height = this.img.naturalHeight;
}

That code might not work, the image src can return 401 (not sure yet), we use proxy and get that file from a storage bucket on the server. like /api/getStorageResource?blob=

What can I do?

Having the link, can I somehow fetch image through axios and set it as an element, instead of <img src=".." />

As an option I see that I can probably have the element as it is now <img src="/api/getStorageResource?blob=" /> and getElementById it and get the width and height... Not sure what my options here.

Upvotes: 0

Views: 763

Answers (1)

AndrewL64
AndrewL64

Reputation: 16311

You can use a combination of async/await and the fetch api inside a try/catch block to get the image URL from your server and then you can proceed with creating the <img> element, assign the retrieved image URL to the img element src and finally set the width and height of the container equal to the img element's width and height.

In the following example Code Snippet, I have added a button which will add the image to the container on click so you can see how the container has the retrieved image dimensions even before the image is rendered on the DOM:

const imgDiv = document.querySelector('#imgDiv');
const btn = document.querySelector('#imgBtn');

//The fetchImg function will fetch the image URL from the server and log error to console if file not found
const fetchImg = async () => {
  try {
    // replace the following example url with "this.payload.src"
    const imgURL = await fetch('https://picsum.photos/id/237/200/200');
    return imgURL;
  } catch (err) {
      // do something here if image not found
      console.log('Image not found!');
  } 
}

fetchImg().then((res) => {
  // create a new image element with the URL as the src
  const img = new Image();
  img.src = res.url; // change ".url" according to how the data you get from your server is structured

  // assign the retrieved width and height of img to container
  img.addEventListener('load', () => {
    imgDiv.style.width = img.naturalWidth + 'px';
    imgDiv.style.height = img.naturalHeight + 'px';
  });
  
  btn.addEventListener('click', () => imgDiv.appendChild(img));
});
html, body {margin: 0;padding: 10px;width: 100%; height: 100%;text-align: center;}
#imgDiv {background-color: #222;margin: 0 auto;}
<button id="imgBtn">Add Image</button>
<div id="imgDiv"></div>    


JSFiddle with above code: https://jsfiddle.net/AndrewL64/2hu3yxtq/104/

Upvotes: 1

Related Questions