首先,大部分人和网上能搜索到的获取图片分辨率或尺寸的方法,应该都是这样:
let url = 'url';
function getUrlInfo(url) {
let image = new Image();
let w,h;
image.src = url;
// 如果有缓存,读缓存
if(image.complete){
w = image.width; // 图片宽度
h = iamge.height; // 图片高度
}else { //否则加载图片
image.onload = function() {
w = image.width; // 图片宽度
h = iamge.height; // 图片高度
image.onload = null; // 避免重复加载
};
}
}
最多可能多个几行用了h5代码的。
另一种方法
getImgInfo(url){
return new Promise((resolve, reject) => {
let image = new Image();
image.src = url;
let timer = setInterval(() => {
if (image.width > 0 || image.height > 0) {
resolve(`${image.width}*${image.height}`); // 图片宽*高
clearInterval(timer);
}
}, 50)
})
},
调用
getImgInfo(url).then(res => { console.log(res); }) //res: 上面代码resolve中的内容
本人自己用的就是第二种方法,真的又快又好用。但是因人而异,可能大家会有各自喜欢的方法,欢迎分享。