43
votes

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?

10

10 Answers

49
votes

I use rn-fetch-blob, basically it provides lot of file system and network functions make transferring data pretty easy.

react-native-fetch-blob is deprecated

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

source Project Wiki

16
votes

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);
});
15
votes
 ImageEditor.cropImage(imageUrl, imageSize, (imageURI) => {
      ImageStore.getBase64ForTag(imageURI, (base64Data) => {
          // base64Data contains the base64string of the image
      }, (reason) => console.error(reason));
 }, (reason) => console.error(reason));
12
votes

The standalone expo FileSystem package makes this simple:

const base64 = await FileSystem.readAsStringAsync(photo.uri, { encoding: 'base64' });

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

7
votes

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.
});
5
votes

You can use react-native-image-base64. You have to give image url and it returns the base64 string of image.

ImgToBase64.getBase64String('file://youfileurl')
  .then(base64String => doSomethingWith(base64String))
  .catch(err => doSomethingWith(err));
3
votes

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

0
votes

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.

0
votes

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

In case you're using expo in a managed workflow and cannot use react-native-fs, you can do it using the expo-file-system library. Here's a helper function that will do the trick by only providing an image URL and will return a base64 encoded image. PS: It doesn't contain the base64 prefix, you need to include it yourself based on the image type you have.


import * as FileSystem from 'expo-file-system';


async function getImageToBase64(imageURL) {
  let image;

  try {
    const { uri } = await FileSystem.downloadAsync(
      imageURL,
      FileSystem.documentDirectory + 'bufferimg.png'
    );

    image = await FileSystem.readAsStringAsync(uri, {
      encoding: 'base64',
    });
  } catch (err) {
    console.log(err);
  }

  return image;
}

An example usage in a React Native Image component is as follows:

<Image
  style={{ width: 48, height: 48 }}
  source={{ uri: `data:image/png;base64,${image}` }}
/>