React-Native:将图片网址转换为base64字符串
我正在构建一个本机应用程序,需要以base64字符串格式存储图像以便离线查看功能。
I'm building a react native app that needs to store images at base64 string format for offline viewing capabilities.
哪个库/函数会给我最好的结果将图像存储为base64字符串?假设我的网址是 http://www.example.com/image.png 。
What library / function would give me the best result to store the image as base64 string? assuming my url is "http://www.example.com/image.png".
另外,在将其存储为字符串之前,是否需要发出http请求才能获取它?我的逻辑是肯定的,但是在本机中你可以在< Image>组件上加载图像而不首先从服务器请求它们。
Also, do I need to make http request to get it before storing it as a string? my logic says yes, but in react native you can load images on the <Image> component without request them first from the server.
什么是最好的选择做反应原生吗?
What would be the best option to do this in react native?
我用 react-native-fetch-blob ,基本上它提供了大量的文件系统和网络功能,使得传输数据非常容易。
I use react-native-fetch-blob, basically it provides lot of file system and network functions make transferring data pretty easy.
import RNFetchBlob from "react-native-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);
});
source 项目维基