JS快速获取图片宽高

方法一:

function getImgInfo (url) {
            return new Promise((resolve, reject) => {
                let img = new Image();
                img.src = url;
                img.onload = function () {
                    resolve({
                         img.width,
                        height: img.height
                    });
                };
                img.onerror = function () {
                    reject(new Error("图片加载错误!"));
                }

            });
        }
        
        getImgInfo('http://b.zol-img.com.cn/desk/bizhi/image/2/2560x1600/.jpg').then(imgInfo => {
            console.log(imgInfo);
        }).catch(error => {
            console.log(error);
        });
 

方法二:

function getImgInfo (url) {
            return new Promise((resolve, reject) => {
                let img = new Image();
                img.src = url;
                let timer = setInterval(function () {
                    if (img.width > 0 || img.height > 0) {
                        resolve({
                             img.width,
                            height: img.height
                        })
                        clearInterval(timer);
                    }
                }, 50);
            });
        }
        
        getImgInfo('http://b.zol-img.com.cn/desk/bizhi/image/2/2560x1600/1365477614755.jpg').then(imgInfo => {
            console.log(imgInfo);
        });

注: 我们常常知道有些图片虽然没有完全download下来,但是已经先有占位符,然后一点一点的加载。既然有占位符那应该是请求图片资源服务器响应后返回了宽和高。可服务器什么时候响应并返回宽高的数据没有触发事件,所以只能用轮询的方法。这个方法应该会比第一种方法能更早的取得图片的宽和高。

原文地址:https://www.cnblogs.com/wxb1314/p/13288199.html