可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm building a react native app that needs to store images at base64 string format for offline viewing capabilities.
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".
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?
回答1:
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 Project Wiki
回答2:
ImageEditor.cropImage(imageUrl, imageSize, (imageURI) => { ImageStore.getBase64ForTag(imageURI, (base64Data) => { // base64Data contains the base64string of the image }, (reason) => console.error(reason)); }, (reason) => console.error(reason));
回答3:
To convert image to base64 in React native, the FileReader utility is helpful:
const fileReader = new FileReader(); fileReader.onload = fileLoadedEvent => { const base64Image = fileLoadedEvent.target.result; }; fileReader.readAsDataURL(imagepath);
This requires react-native-file.
Another alternative, and probably the preferred alternative, is to use NativeModules. The Medium article shows how. It requires creating a native module.
NativeModules.ReadImageData.readImage(path, (base64Image) => { // Do something here. });
回答4:
There is a better way: Install this react-native-fs, IF you don't already have it.
import RNFS from 'react-native-fs'; RNFS.readFile(this.state.imagePath, 'base64') .then(res =>{ console.log(res); });