JavaScript获取图片宽高

核心代码很简单:

let imgSrc = "图片路径";
let img = new Image();
img.src = imgSrc;
return {
	width: img.width,
	height: img.height
}

但是,很不凑巧,在js中,图片的加载是异步的,类似于:文档中dom元素的加载,css样式的渲染,js脚本的执行,ajax请求等等。在img.src属性被赋值以后,如果图片路径被浏览器正确解析,则img的onload事件就会随之触发,如果有缓存,即img是在complete状态下,则会立即得到图片宽高,但是如果是图片第一次加载,会导致onload函数触发。

这里做一个简单的封装,相当于把onload事件回调封装成Promise的形式,然后加一个超时失败机制,代码如下:

  async function getImgWidthHeight(src, maxWaitLoad = 2500) {
    return new Promise((resolve, reject)=> {
      let img = new Image();
      img.src = src;
      if (img.complete) {
        const {width,height} = img;
        resolve({
          width,
          height
        });
      } else {
        let timeOut = setTimeout(() => {
          reject("图片加载失败!");
        },maxWaitLoad);
        img.onload = function () {
          const {width,height} = img;
          window.clearTimeout(timeOut);
          resolve({
            width,
            height
          });
        }
      }
    })
  }

实际使用只需要调用下面那个方法getImgWidthHeight(src)即可。

用法很简单,这里写一个用例:

  let url = "https://im0.baidu.com/it/u=2893908510,4203750994&fm=15&fmt=auto&gp=0.jpg";
  getImgWidthHeight(url).then(res => {
    console.log(res);
  }, reason => {
    console.error(reason);
  })

这里用的是一张网络图片,当然本地图片也是没有任何问题的。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐