51

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?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Avishay Bar
  • 783
  • 1
  • 7
  • 12

15 Answers15

57

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

Wasi Sadman
  • 1,382
  • 1
  • 15
  • 27
Ven Jest
  • 690
  • 6
  • 4
26

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);
});
David Madi
  • 565
  • 5
  • 6
  • Works on RN `0.63.3` – Kasra Nov 03 '20 at 11:22
  • When I try to save into a variable, it saves as `[object Object]` instead of the base64 string. How to save the base64 string to a variable? – velkoon Aug 30 '21 at 21:56
  • It says "At the command line, in your project folder, type: react-native link react-native-fs. Done! No need to worry about manually adding the library to your project."And then down it says Android usage and all that stuff ? Update the documentation plz – Ali Yar Khan Nov 27 '21 at 15:56
14

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

Ulad Kasach
  • 11,558
  • 11
  • 61
  • 87
13
 ImageEditor.cropImage(imageUrl, imageSize, (imageURI) => {
      ImageStore.getBase64ForTag(imageURI, (base64Data) => {
          // base64Data contains the base64string of the image
      }, (reason) => console.error(reason));
 }, (reason) => console.error(reason));
shrutim
  • 1,058
  • 2
  • 12
  • 21
  • 11
    React Native warns developers not to use ImageEditor anymore: Warning: ImageStore is deprecated and will be removed in a future release. To get a base64-encoded string from a local image use either of the following third-party libraries:* expo-file-system: `readAsStringAsync(filepath, 'base64')`* react-native-fs: `readFile(filepath, 'base64')` – Cornel May 15 '19 at 08:29
9

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.
});
vijayst
  • 20,359
  • 18
  • 69
  • 113
6

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));
Shehzad Osama
  • 1,222
  • 12
  • 13
  • [!] CocoaPods could not find compatible versions for pod "React/Core": In Podfile: react-native-fetch-blob (from `../node_modules/react-native-fetch-blob`) was resolved to 0.10.6, which depends on React/Core None of your spec sources contain a spec satisfying the dependency: `React/Core`. You have either: * out-of-date source repos which you can update with `pod repo update` or with `pod install --repo-update`. * mistyped the name or version. * not added the source repo that hosts the Podspec to your Podfile. – Kasra Nov 03 '20 at 10:43
5

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}` }}
/>
Henrique Aron
  • 1,316
  • 1
  • 5
  • 6
4

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

zematdev
  • 163
  • 1
  • 7
2

No library need, use built in JS features

export default async function base64File(url) {
  const data = await fetch(url);
  const blob = await data.blob();
  return new Promise(resolve => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onloadend = () => {
      const base64data = reader.result;
      resolve(base64data);
    };
  });
}
Dragos UniqQum
  • 388
  • 4
  • 12
  • I needed to generate a base64 using the url of an image saved in cloudinary and this was super helpful. I didn't need to install any library or whatsoever. PS: I am on RN Version: 0.70.4 and React Version: 18.1.0 – Segun Jan 05 '23 at 16:37
  • Same here, React 18.2.0 and RN 0.71.3 – Sanchitos Apr 26 '23 at 19:22
1
If You are using **react-native-image-picker**
Then it includes base64 string in response object

    if you are  using any  other library i.e. **react-native-document-picker**
    then you have to use **react-native-fs** library 
    
    import RNFS from 'react-native-fs';
    
      RNFS.readFile(item.uri, 'base64').then((res) => {
                  //Here in enter code here res you  will get base64 string 
                });

  
Naveen Tiwari
  • 301
  • 2
  • 12
1

i am using react-native-image-crop-picker add includeBase64 prop it will response in base64 converted image

ImagePicker.openPicker({
  width: 300,
  height: 400,
  includeBase64:true
}).then(image => {
  console.log(image.data);
});
Akram Syed
  • 11
  • 4
0

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

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
import ImgToBase64 from 'react-native-image-base64';
 
ImgToBase64.getBase64String(trainingRooms)
            .then(base64String => {
                console.log("Sourabh____ ImgToBase64 base64String "+base64String );
            })
            .catch(err => {
                console.log("Sourabh____ ImgToBase64 error "+err);
            })
Sourabh Gera
  • 862
  • 7
  • 7
-1

Convert url image to base64

const getBase64ImageFromUrl = url => fetch(url) .then(response => response.blob()) .then( blob => new Promise((resolve, reject) => { const reader = new FileReader(); reader.onloadend = () => resolve(reader.result); reader.onerror = reject; blob = new Blob([blob], {type: 'image/png'}); reader.readAsDataURL(blob); }), );

await getBase64ImageFromUrl("https://your image url");

Firoj
  • 1
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 09 '22 at 02:18