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

泄露秘密 提交于 2019-12-13 08:09:50

问题


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?


回答1:


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



回答2:


Here is how I do this within a Redux Saga (where I need it to block until it is competed):

const promise = new Promise(
      (resolve, reject) => {
        Image.getSize(filePath, (width, height) => {
          resolve({ width, height });
        });
      },
      error => reject(error)
    );

const { width, height } = yield promise;

You could also call the promise with an await (inside an async function), just in case someone else needs this.



来源:https://stackoverflow.com/questions/41735846/how-to-get-image-height-and-width-from-uri-on-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!