JS获取img图片的原始尺寸高度和宽度

简介: JS获取img图片的原始尺寸高度和宽度

方式一:obj.style.width

通过img对象的style属性获取,如果没有设置style,将返回空


<img class="image"
         style="width: 100px; height: 200px;"
         src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg9.51tietu.net%2Fpic%2F2019-091307%2Fntplrtyw2bvntplrtyw2bv.jpg&refer=http%3A%2F%2Fimg9.51tietu.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655389703&t=4423dd371c66b6064a1ed3c4dc5e05cd">
<script>
    let image = document.querySelector('.image');
    console.log(image.style.width); // 100px
    console.log(image.style.height); // 200px
</script>

方式二:width/height

直接通过img的属性值width/height获取,如果没有设置属性,会返回0


<style>
     .image {
         width: 200px;
         height: 100px;   
     }
 </style>
<img class="image"
     src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg9.51tietu.net%2Fpic%2F2019-091307%2Fntplrtyw2bvntplrtyw2bv.jpg&refer=http%3A%2F%2Fimg9.51tietu.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655389703&t=4423dd371c66b6064a1ed3c4dc5e05cd"
     alt="">
<script>
    let image = document.querySelector('.image');
    console.log(image.width, image.height);
    // 200 100
</script>

如果DOM图片完全加载后,就可以在控制台获取图片元素的尺寸了


document.querySelector('.image').height
// 1200

等待dom完全加载完成就可以获取img元素的尺寸


<img class="image"
         src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg9.51tietu.net%2Fpic%2F2019-091307%2Fntplrtyw2bvntplrtyw2bv.jpg&refer=http%3A%2F%2Fimg9.51tietu.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655389703&t=4423dd371c66b6064a1ed3c4dc5e05cd"
         alt="">
<script>
     // 等外部资源都加载完了就触发
     window.addEventListener('load', function () {
         console.log('load');
         let image = document.querySelector('.image')
         console.log(image.width, image.height);
         // 1920 1200
     })
     // 页面的DOM结构绘制完成了,这时候外部资源(带src属性的)还没有加载完
     window.addEventListener('DOMContentLoaded', function () {
         console.log('DOMContentLoaded');
         let image = document.querySelector('.image')
         console.log(image.width, image.height);
         // 0 0
     })
 </script>

方式三:offsetWidth/clientWidth

通过offset(offsetWidth/offsetHeight) 和 client(clientWidth/clientHeight)获取


<style>
    .image {
        width: 200px;
        height: 100px;
        padding: 20px;
        border: 2px solid green;
    }
</style>
<img class="image"
     src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg9.51tietu.net%2Fpic%2F2019-091307%2Fntplrtyw2bvntplrtyw2bv.jpg&refer=http%3A%2F%2Fimg9.51tietu.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655389703&t=4423dd371c66b6064a1ed3c4dc5e05cd"
     alt="">
<script>
    let image = document.querySelector('.image');
    // offset = width + padding  + border
    console.log(image.offsetWidth, image.offsetHeight);
    // 244 144
    // client = width + padding
    console.log(image.clientWidth, image.clientHeight);
    // 240 140
</script>

方法四: getComputedStyle和 currentStyle

通过 getComputedStyle和 currentStyle获取


<style>
    .image {
        width: 200px;
        height: 100px;
    }
</style>
<img class="image"
    src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg9.51tietu.net%2Fpic%2F2019-091307%2Fntplrtyw2bvntplrtyw2bv.jpg&refer=http%3A%2F%2Fimg9.51tietu.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655389703&t=4423dd371c66b6064a1ed3c4dc5e05cd"
     alt="">
<script>
    function getStyle(el, name) {
        if (window.getComputedStyle) {
            // 适用于Firefox/IE9/Safari/Chrome/Opera浏览器
            return window.getComputedStyle(el, null)[name];
        } else {
            // 适用于IE6/7/8
            return el.currentStyle[name];
        }
    }
    let image = document.querySelector('.image');
    console.log(getStyle(image, 'width'), getStyle(image, 'height'));
    // 200px 100px
</script>

方式五:Image对象

通过Image对象,异步获取图片尺寸


let url =
    'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg9.51tietu.net%2Fpic%2F2019-091307%2Fntplrtyw2bvntplrtyw2bv.jpg&refer=http%3A%2F%2Fimg9.51tietu.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655389703&t=4423dd371c66b6064a1ed3c4dc5e05cd';
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);
})();
// {width: 1920, height: 1200}

方法六:naturalWidth

通过HTML5属性 natural(naturalWidth, naturalHeight)获取


<style>
    .image {
        width: 200px;
        height: 100px;
    }
</style>
<img class="image"
     src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg9.51tietu.net%2Fpic%2F2019-091307%2Fntplrtyw2bvntplrtyw2bv.jpg&refer=http%3A%2F%2Fimg9.51tietu.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655389703&t=4423dd371c66b6064a1ed3c4dc5e05cd"
     alt="">
<script>
    // 适用于Firefox/IE9/Safari/Chrome/Opera浏览器
    let image = document.querySelector('.image');
    console.log(image.naturalWidth, image.naturalHeight);
    // 1920 1200
</script>

虽然设置了图片的显示宽和高,但是获取了图片真实的尺寸


方式七:兼容写法

<img class="image"

     

src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg9.51tietu.net%2Fpic%2F2019-091307%2Fntplrtyw2bvntplrtyw2bv.jpg&refer=http%3A%2F%2Fimg9.51tietu.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655389703&t=4423dd371c66b6064a1ed3c4dc5e05cd"
         alt="">
<script>
    function getImageSizeByUrl(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 function getImageSize(img) {
        if (img.naturalWidth) {
            // 适用于Firefox/IE9/Safari/Chrome/Opera浏览器
            console.log('naturalWidth');
            return {
                width: img.naturalWidth,
                height: img.naturalHeight
            }
        } else {
            console.log('getImageSizeByUrl');
            return await getImageSizeByUrl(img.src);
        }
    }
    (async () => {
        let image = document.querySelector('.image');
        let size = await getImageSize(image);
        console.log(size);
    })();
    // {width: 1920, height: 1200}
</script>

总结

image.png

相关文章
|
3月前
|
前端开发 JavaScript API
使用 JavaScript 实现图片上传
使用 JavaScript 实现图片上传
115 1
|
2月前
|
JavaScript 前端开发
【原创】用JavaScript动态获取网页中缩放图片的长度、宽度和显示比例
【原创】用JavaScript动态获取网页中缩放图片的长度、宽度和显示比例
|
3月前
|
JavaScript 前端开发
JavaScript的尺寸
JavaScript的尺寸
18 0
|
3月前
|
JavaScript 前端开发
JS - 如何上传 Base64 编码的图片
本文展示了如何将Base64编码的图片在前端转换为Blob对象,并使用`FormData`上传到服务器端的方法。
177 0
|
3月前
|
JavaScript
js之图片上传
js之图片上传
75 0
|
4月前
|
JavaScript Java 测试技术
基于springboot+vue.js+uniapp小程序的图片推荐系统附带文章源码部署视频讲解等
基于springboot+vue.js+uniapp小程序的图片推荐系统附带文章源码部署视频讲解等
44 0
|
4月前
|
JavaScript
js 滚动鼠标滑轮放大缩小图片
js 滚动鼠标滑轮放大缩小图片
24 0
|
4月前
|
前端开发 JavaScript
js 打开资源管理器(经典范例:纯前端选择并预览图片)
js 打开资源管理器(经典范例:纯前端选择并预览图片)
107 0
|
4月前
|
JavaScript
js document.compatMode【详解】(含准确获取浏览器宽高等尺寸的方法)
js document.compatMode【详解】(含准确获取浏览器宽高等尺寸的方法)
34 0