Ega Setya Putra
Ega Setya Putra

Reputation: 1695

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?

Upvotes: 7

Views: 18888

Answers (2)

Francois Nadeau
Francois Nadeau

Reputation: 7463

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.

Upvotes: 10

ide
ide

Reputation: 20838

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}`);
});

Upvotes: 11

Related Questions