这个(getSizeFromObjectUrl
)函数可以很好地计算实际图像的高度和宽度。我尝试过使用文件(ObjectURL)而不是图像(例如:文本文件),代码永远不会到达try-catch中的catch块。使用img.onload
捕获错误/加载异常的方法有哪些
function getSizeFromObjectUrl(dataURL: string): Promise<{ width: number; height: number }> {
return new Promise((resolve) => {
try {
const img = new Image();
img.onload = () => {
const ratio = Math.min(maxImageWidth / img.width, maxImageHeight / img.height, 1);
resolve({
width: img.width * ratio,
height: img.height * ratio
});
};
img.src = dataURL;
} catch (exception) {
logCalculateImageSizeFailed(exception);
// handle error
}
});
}
发布于 2021-06-05 14:58:58
对img.onerror
使用promise reject
注意,在Promise executor回调中添加了reject
参数-请参阅代码中的注释
function getSizeFromObjectUrl(dataURL: string): Promise<{width: number;height: number}> {
return new Promise((resolve, reject) => { // amended this line
const img = new Image();
img.onerror = reject; // added this line
img.onload = () => {
const ratio = Math.min(maxImageWidth / img.width, maxImageHeight / img.height, 1);
if (img.width && img.height) {
resolve({
width: img.width * ratio,
height: img.height * ratio
});
} else {
reject('Bad Image');
}
};
img.src = dataURL;
}).catch(exception => {
logCalculateImageSizeFailed(exception);
// handle error
});
}
https://stackoverflow.com/questions/67847117
复制相似问题