微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从 localhost url 读取图像并在 javascript

如何解决如何从 localhost url 读取图像并在 javascript

大家好,我是 javascript 新手,我想在从图像 url 加载图像时获取图像的宽度和高度。怎么做?非常感谢您的帮助。

我知道它是从这个开始的,但并不真正了解如何继续..

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

}

谢谢

解决方法

您可以使用加载事件:

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'
,

如果要在浏览器中加载图像,则“加载”事件侦听器会起作用。

但是,如果情况并非如此,并且您真的不希望图像可见,那么您可以这样做。

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))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。