React-Native: Convert image url to base64 string

2020-02-04 07:09发布

问题:

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


回答5:

The standalone expo FileSystem package makes this simple:

const base64 = await FileSystem.readAsStringAsync(photo.uri, { encoding: 'base64' });
  • https://docs.expo.io/versions/latest/sdk/filesystem/
  • https://github.com/expo/expo/tree/master/packages/expo-file-system

As 2019-09-27 this package handles both file:// and content:// uri's



回答6:

react-native-image-picker includes a base64 data node in the returned object. fyi



回答7:

I used another package: react-native-fs

import RNFS from 'react-native-fs';

var data = await RNFS.readFile( "file://path-to-file", 'base64').then(res => { return res });

This works fine.



回答8:

For me upalod file mp4 from local file on devies to Facebook or another social:

var data = await RNFS.readFile( `file://${this.data.path}`, 'base64').then(res => { return res });
        const shareOptions = {
            title: 'iVideo',
            message: 'Share video',
            url:'data:video/mp4;base64,'+ data,
            social: Share.Social.FACEBOOK,
            filename: this.data.name , // only for base64 file in Android 
        };     
        Share.open(shareOptions).then(res=>{
           Alert.alert('Share Success`enter code here`!')
        }).catch(err=>{
            console.log('err share', err);
        });