如何从 React Native 的 uri 获取图像的高度和宽度?
How to get image height and width from uri on React Native?
因此,我尝试使用 React Native 提供的功能 Image.getSize。但是当我尝试在函数之外使用高度和宽度时,它似乎是零。
这是我的代码:
var theHeight = 0;
Image.getSize(url,(height, width)=>{
theHeight = height;
})
console.log("test get height "+theHeight);
结果会是
test get height 0
我做错了什么?
您的代码有两个问题。首先是 Image.getSize
异步调用其回调。您需要将依赖于图像大小的代码放入回调中。
第二个问题是成功回调的参数是(width, height)
,而不是相反。
你应该写:
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}`);
});
这是我在 Redux Saga 中执行此操作的方法(我需要它在竞争完成之前阻塞):
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}`);
您也可以使用 await 调用 promise(在异步函数内),以防其他人需要它。
因此,我尝试使用 React Native 提供的功能 Image.getSize。但是当我尝试在函数之外使用高度和宽度时,它似乎是零。 这是我的代码:
var theHeight = 0;
Image.getSize(url,(height, width)=>{
theHeight = height;
})
console.log("test get height "+theHeight);
结果会是
test get height 0
我做错了什么?
您的代码有两个问题。首先是 Image.getSize
异步调用其回调。您需要将依赖于图像大小的代码放入回调中。
第二个问题是成功回调的参数是(width, height)
,而不是相反。
你应该写:
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}`);
});
这是我在 Redux Saga 中执行此操作的方法(我需要它在竞争完成之前阻塞):
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}`);
您也可以使用 await 调用 promise(在异步函数内),以防其他人需要它。