首页 > Web开发 > 详细

JS快速获取图片宽高

时间:2020-07-12 15:01:30      阅读:63      评论:0      收藏:0      [点我收藏+]

方法一:

function getImgInfo (url) {
            return new Promise((resolve, reject) => {
                let img = new Image();
                img.src = url;
                img.onload = function () {
                    resolve({
                        width: 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({
                            width: 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下来,但是已经先有占位符,然后一点一点的加载。既然有占位符那应该是请求图片资源服务器响应后返回了宽和高。可服务器什么时候响应并返回宽高的数据没有触发事件,所以只能用轮询的方法。这个方法应该会比第一种方法能更早的取得图片的宽和高。

JS快速获取图片宽高

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!