从 React Native 中的 blob 获取图像尺寸
Get image dimension from blob in React Native
假设我正在调用一个 API,它提供随机尺寸的图像。
我需要在渲染之前知道每个图像的宽度和高度,因为我需要为我想要的精确布局做一些计算。
使用 Web Apis,我做了这个并且工作正常:
const res = await fetch("https://picsum.photos/200/300");
const blob = await res.blob();
const img = new Image();
img.src = URL.createObjectURL(blob);
console.log(img.src);
img.onload = () => {
console.log(img.width, img.height);
};
问题是使用 React Active,我们无法访问 Web Api Image 对象。
Image 是 React Native 上的一个组件。
这是我所在的位置:
const res = await fetch("https://picsum.photos/200/300");
const blob = await res.blob();
基本上二进制数据现在存储在 RAM 中,但我找不到任何方法将这些数据解释为图像并获取尺寸。
React Native Image组件内置了getSize方法。如果您可以将 blob 转换为 URI,则可以使用以下代码。
Image.getSize(myUri, (width, height) => { console.log(width, height)});
假设我正在调用一个 API,它提供随机尺寸的图像。 我需要在渲染之前知道每个图像的宽度和高度,因为我需要为我想要的精确布局做一些计算。
使用 Web Apis,我做了这个并且工作正常:
const res = await fetch("https://picsum.photos/200/300");
const blob = await res.blob();
const img = new Image();
img.src = URL.createObjectURL(blob);
console.log(img.src);
img.onload = () => {
console.log(img.width, img.height);
};
问题是使用 React Active,我们无法访问 Web Api Image 对象。 Image 是 React Native 上的一个组件。
这是我所在的位置:
const res = await fetch("https://picsum.photos/200/300");
const blob = await res.blob();
基本上二进制数据现在存储在 RAM 中,但我找不到任何方法将这些数据解释为图像并获取尺寸。
React Native Image组件内置了getSize方法。如果您可以将 blob 转换为 URI,则可以使用以下代码。
Image.getSize(myUri, (width, height) => { console.log(width, height)});