Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get image height and width from uri on React Native?

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?

like image 944
Ega Setya Putra Avatar asked Dec 03 '22 13:12

Ega Setya Putra


2 Answers

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}`);
});
like image 91
ide Avatar answered Dec 06 '22 11:12

ide


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.

like image 29
Francois Nadeau Avatar answered Dec 06 '22 10:12

Francois Nadeau