如何获取image图片的实际宽高?

1,020 阅读1分钟

如何获取图片的实际宽高?

应用场景,有的时候,在操作图片超出部分滚动的时候,需要知道图片的真实宽高,但是图片的宽高不确定。

1、HTML5属性 natural(naturalWidth, naturalHeight)获取

const image = document.querySelector('.image');
console.log(image.naturalWidth, image.naturalHeight);

2、Image对象,异步获取图片尺寸

const url = 'https://d5cdn.cdollar.cn/d5/resource/guangbeiyewuzu/69a4ff1c-62f5-42cd-9efe-ee3753b6c88a.png';
​
function getImageSize(url) {
    return new Promise(function (resolve, reject) {
        let image = new Image();
        image.onload = function () {
            resolve({
                width: image.width,
                height: image.height
            });
        };
        image.onerror = function () {
            reject(new Error('error'));
        };
        image.src = url;
    });
}
​
(async () => {
    let size = await getImageSize(url);
    console.log(size);
})();

3、uniapp使用new image()获取图片信息报错

uni使用new image()报ReferenceError: Image is not defined或者获取不到对象

const url = 'https://d5cdn.cdollar.cn/d5/resource/guangbeiyewuzu/69a4ff1c-62f5-42cd-9efe-ee3753b6c88a.png'
uni.getImageInfo({
    src: url,
    success: function (image) {
        console.log('image', image)
        // image.height
        // image.width
    }
})