网站搜索

reactjs - React Native Expo 将 URL 图片转换为 Base64


我正在开发一个从 API 加载图像的应用程序。该应用程序的要求是将这些图像离线存储在基于 SQLite 的应用程序数据库中。我认为唯一的方法是将图像转换为 base64 字符串,这样我展示图像会更容易。

我以前用过 RN-Fetch-Blob 库,但 Expo 不支持它。所以我在寻找一种方法来实现,但我什么都没找到。

我尝试了这个库 react-native-image-base64

但是它不起作用

ImgToBase64.getBase64String('http://i.imgur.com/XP2BE7q.jpg')
        .then(base64String => console.log(base64String))
        .catch(err => console.log(err));

有人能告诉我如何在 Expo 中将图片转换为 base64 吗?

答案#1

虽然这并没有回答你的问题,但你可能想考虑将图像以 BLOB 类型存储在你的 sqlite 数据库中。你可以在这里查看一些示例:https://medium.com/@ericmorgan1/upload-images-to-firebase-in-expo-c4a7d4c46d06

想法是,使用 Expo,我们可以使用 ImagePicker 获取 URI,然后使用 fetch() API 来获取 BLOB 数据。

一旦我们获取了 BLOB 数据,就可以将其存储到我们的 SQLite 数据库中。

示例:

const imageUrl = 'http://i.imgur.com/XP2BE7q.jpg';
const response = await fetch(imageUrl);
// This will be the blob data that you will have to store inside your SQLite DB
const blob = await response.blob();