React-Native:将图像 url 转换为 base64 字符串

新手上路,请多包涵

我正在构建一个反应本机应用程序,需要以 base64 字符串格式存储图像以实现离线查看功能。

什么库/函数会给我将图像存储为 base64 字符串的最佳结果?假设我的网址是“ http://www.example.com/image.png ”。

另外,在将它存储为字符串之前,我是否需要发出 http 请求来获取它?我的逻辑是肯定的,但是在本机反应中,您可以在 组件上加载图像,而无需先从服务器请求它们。

在本机反应中执行此操作的最佳选择是什么?

原文由 Avishay Bar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

我使用 rn-fetch-blob ,基本上它提供了很多文件系统和网络功能,使传输数据变得非常容易。

react-native-fetch-blob 已弃用

import RNFetchBlob from "rn-fetch-blob";
const fs = RNFetchBlob.fs;
let imagePath = null;
RNFetchBlob.config({
  fileCache: true
})
  .fetch("GET", "http://www.example.com/image.png")
  // the image is now dowloaded to device's storage
  .then(resp => {
    // the image path you can use it directly with Image component
    imagePath = resp.path();
    return resp.readFile("base64");
  })
  .then(base64Data => {
    // here's base64 encoded image
    console.log(base64Data);
    // remove the file from storage
    return fs.unlink(imagePath);
  });

项目维基

原文由 Ven Jest 发布,翻译遵循 CC BY-SA 4.0 许可协议

有一个更好的方法:安装这个 react-native-fs ,如果你还没有的话。

 import RNFS from 'react-native-fs';

RNFS.readFile(this.state.imagePath, 'base64')
.then(res =>{
  console.log(res);
});

原文由 David Madi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题