So, I tried to use function that provided by React Native which is Image.getSize. But when I try to use height and width outside the function it appears to be nil. Here is my code:
var theHeight = 0;
Image.getSize(url,(height, width)=>{
theHeight = height;
})
console.log("test get height "+theHeight);
and the result would be
test get height 0
What did I do wrong?
There are two problems with your code. The first is that Image.getSize
invokes its callbacks asynchronously. You need to put your code that relies on the image size within the callbacks.
The second problem is that the arguments to the success callback are (width, height)
, not the other way around.
You should write:
Image.getSize(url, (width, height) => {
console.log(`The image dimensions are ${width}x${height}`);
}, (error) => {
console.error(`Couldn't get the image size: ${error.message}`);
});
Here is how I do this within a Redux Saga (where I need it to block until it is competed):
const getImageSize = new Promise(
(resolve, reject) => {
Image.getSize(filePath, (width, height) => {
resolve({ width, height });
});
},
(error) => reject(error)
);
const { width, height } = yield getImageSize;
console.log(`width ${width}, height ${height}`);
You could also call the promise with an await (inside an async function), just in case someone else needs this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With