JS获取图片尺寸宽高的方法

14 min read
export const getImgSize = function (img, callback) {
    if (!(img instanceof HTMLImageElement)) {
        throw new Error('Invalid image element');
    }

    if (img.naturalWidth) { // 现代浏览器
        callback({ w: img.naturalWidth, h: img.naturalHeight });
    } else { // IE6/7/8
        var image = new Image();
        image.src = img.src;
        image.onload = function () {
            callback({ w: image.width, h: image.height });
        };
        image.onerror = function () {
            console.error('There was an error loading the image.');
        };
    }
};

  1. 获取是图片的实际尺寸,不受 CSS 影响的原始尺寸

  2. 对于现代浏览器,直接使用 naturalWidthnaturalHeight 属性即可,无需创建新的 Image 对象。对于旧版 IE 浏览器,确保不会重复加载图像。