React-Native: Convert image url to base64 string

匿名 (未验证) 提交于 2019-12-03 03:04:01

问题:

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); }); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!