I’m new to react native but I’ve been using JavaScript for a while. I’m trying to get the aspect ratio so my images look nice using Image.getSize, but I keep getting the following warning:
Failed to get size for image: https://books.google.com/books/content?id=NYMD0AEACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api
Here’s my code where I’m implementing getSize:
const handleIsbnSearch = async () => {
const books = await isbnSearch(isbn);
if (books.error) {
return setBookSearch([]);
}
let bookInfo = [];
for (let b in books) {
const volInfo = books[b].volumeInfo
const {width, height} = await Image.getSize(volInfo.imageLinks.thumbnail);
const aspectRatio = width/height;
console.log(aspectRatio);
bookInfo.push({
title: volInfo.title,
subtitle: volInfo.subtitle,
authors: volInfo.authors,
publisher: volInfo.publisher,
publishedDate: volInfo.publishedDate,
description: volInfo.description,
categories: volInfo.categories,
thumbnail: volInfo.imageLinks.thumbnail,
aspectRatio: aspectRatio
})
}
setBookSearch(bookInfo);
}
I know the uri is correct because I’m able to load the photo in the app, but for some reason, it can’t get the Image size.
Any help would be appreciated!
I’ve tried replacing "http" with "https", but that didn’t seem to make a difference. Initially, I was not using await
when calling Image.getSize()
, and had to change from a forEach
loop to a for
loop. I’ve also tried calling the method in other places in the code and have tried different uri
s.
3
Answers
Using the below javascript I can get the size of the image, may be it helps for you.
Image.getSize
does not return aPromise
. So you cannot call it with await. It takes three parameters which isuri
,success
callback andfailure
callback.For more info please check the link.
Here is an example of how to use
getSize
Instead of getting the size at api call you may consider getting it at your component.
Ive written this function to explain it better to you.
In react native Image.getSize function uses callback.
To get the dimensions, you can wrap Image.getSize in a promise object, and resolve width and height from it
Ive tested this code with your link on my machine, and it worked
Also worth noticing that you dont have error handlers in your code, which can help with debugging such functions. Its better to hold everything in try{}catch(error){}