There is no way to get the image size until it is attached to the DOM unless you decode the response and check the image metadata, which is explained here: https://stackoverflow.com/a/74710020/7134134
A simpler alternative would be appending the element, getting the required data and removing it immediately:
async function getImageDimentions(src: string) {
return new Promise(resolve => {
const img = new Image();
img.src = src;
document.body.appendChild(img);
img.onload = () => {
img.remove();
resolve({ width: img.naturalWidth, height: img.naturalHeight });
};
});
}
The whole thing runs asynchronously because of the way browser works.
Edit: Although it does not make much difference, the ResizeObserver callback is executed before the onload event, so it may be a little better to use ResizeObserver.
async function getImageDimentions(src: string) {
return new Promise((resolve) => {
const img = new Image();
img.src = src;
new ResizeObserver((_e, observer) => {
img.remove();
observer.disconnect();
if (img.naturalWidth) resolve({ width: img.naturalWidth, height: img.naturalHeight });
}).observe(img);
document.body.appendChild(img);
});
}