React-Native:将图像 url 转换为 base64 字符串 [英] React-Native: Convert image url to base64 string
问题描述
我正在构建一个 React Native 应用,该应用需要以 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 请求才能获取它?我的逻辑是肯定的,但是在 React Native 中,您可以在
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.
在 React Native 中执行此操作的最佳选择是什么?
What would be the best option to do this in react native?
推荐答案
我使用 rn-fetch-blob,基本上它提供了很多文件系统和网络功能,使传输数据变得非常容易.
I use rn-fetch-blob, basically it provides lot of file system and network functions make transferring data pretty easy.
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);
});
源项目维基
这篇关于React-Native:将图像 url 转换为 base64 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!