gpt4 book ai didi

javascript - 为什么服务器上存在图像,但 Image().width = 0

转载 作者:行者123 更新时间:2023-12-03 00:02:55 25 4
gpt4 key购买 nike

我正在 Ionic 3 上创建一个函数,如果用户没有上传自己的头像,则使用缓存加载用户头像和默认头像。这是我的代码,后面是 https://gist.github.com/pabloleonalcaide/1e8ece835ea689894dd37a44f0ce7134

public get_UserIcon(id, cache = null) {
cache = cache || Math.floor(new Date().getMinutes() / 6); //cache for 10 minutes
let url = `${server}UserIcon${id}.jpg?c=${cache}`;
let image = new Image();
image.src = url;
if(image.width != 0){ // check if image exist
return url;
}else{
return DefaultImage;
}
}

但是,当我尝试运行代码时,image.width即使图像位于服务器上,也会显示 0 并返回默认图像。有时它会显示正确的宽度并返回正确的头像。

我尝试过使用

img.onload = () => { 
return url;
}
img.onerror = () =>{
return DefaultImage;
}

但我不确定为什么使用上面的代码会让我的应用程序滞后,它看起来像是卡在 JS 运行时堆栈中。我尝试在 onload 和 onerror 中放入 console.log,但没有被调用。

有人知道怎么解决吗?谢谢

更新:

我的用法是这样的,以便该函数将检查图像是否存在并返回用户头像或默认头像。

<img [src]="get_UserIcon(id)">

最佳答案

因为加载图像(像任何资源一样)是一个异步任务。

当你询问图片的宽度时,对服务器的请求可能还没有离开你的网卡,而浏览器需要有来自该服务器的响应,并能够解码和解析它媒体的元数据。

您必须等待图像加载才能获得以下信息:

var img = new Image();
img.src = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png';
console.log('before', img.width);
// wait for the iamge has loaded
img.onload = e => console.log('after', img.width);

因此,您的函数应该包含任务的异步性,例如通过返回 Promise:

const DefaultImage = 'default'
function get_UserIcon(id, cache = null) {
cache = cache || Math.floor(new Date().getMinutes() / 6); //cache for 10 minutes
const url = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png";
const image = new Image();
return new Promise((res, rej) => {
image.onload = e => res(url); // if onload fires, width is not 0
image.onerror = e => res(DefaultImage);
image.src = url;
});
}

get_UserIcon().then(console.log);

关于javascript - 为什么服务器上存在图像,但 Image().width = 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55095151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com