React-Native:将图像url转换为base64字符串
问题描述:
我正在构建一个反应本机应用程序,需要以base64字符串格式存储图像以便进行脱机查看功能。React-Native:将图像url转换为base64字符串
什么库/函数会给我最好的结果来存储图像作为base64字符串?假设我的网址是“http://www.example.com/image.png”。
此外,我需要做出http请求才能将它存储为字符串之前?我的逻辑说是的,但在原生反应中,您可以将图像加载到Image>组件上,而无需先从服务器请求它们。
什么是最好的选择做到这一点在反应原生?
答
我用react-native-fetch-blob,基本上它提供了大量的文件系统和网络功能,使数据传输很容易。
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)
})
答
为了图像转换为base64在本地做出反应,在实用的FileReader是有帮助的:
const fileReader = new FileReader();
fileReader.onload = fileLoadedEvent => {
const base64Image = fileLoadedEvent.target.result;
};
fileReader.readAsDataURL(imagepath);
另一种替代方案,也许是首选的替代方案是使用NativeModules。 Medium article显示如何。它需要创建一个native module。
NativeModules.ReadImageData.readImage(path, (base64Image) => {
// Do something here.
});
答
ImageEditor.cropImage(imageUrl, imageSize, (imageURI) => {
ImageStore.getBase64ForTag(imageURI, (base64Data) => {
// base64Data contains the base64string of the image
}, (reason) => console.error(reason));
}, (reason) => console.error(reason));
如何使用像 '用户名/项目/ example.png' 地方形象? – Sathya