【问题标题】:Get image width and height. src is proxy获取图像的宽度和高度。 src 是代理
【发布时间】:2020-10-27 13:31:44
【问题描述】:

我有一个 Vue 组件,其中我有一个 img,我需要获取该图像的尺寸,最好是在显示图像之前(以适应容器的宽度或高度)。

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

该代码可能不起作用,图像 src 可以返回 401(尚不确定),我们使用代理并从服务器上的存储桶中获取该文件。比如 /api/getStorageResource?blob=

我能做什么?

有了链接,我可以通过 axios 获取图像并将其设置为元素,而不是 <img src=".." />

作为一个选项,我看到我可能可以拥有现在的元素 <img src="/api/getStorageResource?blob=" /> 和 getElementById 它并获取宽度和高度...不确定我的选项在这里。

【问题讨论】:

  • 我不完全理解你的问题。您的问题是某些图像可能会返回 401 错误,因此您将无法获取尺寸,或者您正在寻找获取图像尺寸的方法?

标签: javascript html css vue.js asynchronous


【解决方案1】:

您可以在try/catch 块内使用async/awaitfetch api 的组合从您的服务器获取图像URL,然后您可以继续创建<img> 元素,将检索到的图像URL 分配给img元素src,最后设置容器的widthheight等于img元素的宽高。

在下面的示例代码片段中,我添加了一个按钮,该按钮将在单击时将图像添加到容器中,这样即使在图像在 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 上面的代码:https://jsfiddle.net/AndrewL64/2hu3yxtq/104/

【讨论】:

    猜你喜欢
    • 2018-07-05
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 2011-11-26
    • 2011-01-02
    • 2014-07-15
    相关资源
    最近更新 更多