js获取图片原始尺寸

版权声明: https://blog.csdn.net/qq_23521659/article/details/89454002

js获取图片原始尺寸:

代码:

function getImageInfo(url, callback) {

        var img = new Image();
        img.src = url;
        if (img.complete) {
        // 如果图片被缓存,则直接返回缓存数据
            callback(img.width, img.height);
        } else {
            img.onload = function () {
                callback(img.width, img.height);
            }
        }
    }

使用:

 getImageInfo("http://www.test.com/test.png", function (width, height) {
            // 在这里面使用
            console.log(width);
            console.log(height);
        })

如果图片没有缓存,是无法获取到原始宽高的,所以需要用img.onload。

欢迎大家留言探讨。

猜你喜欢

转载自blog.csdn.net/qq_23521659/article/details/89454002