Convert static image to Base64 in ReactNative

Ravi picture Ravi · Apr 11, 2017 · Viewed 9.3k times · Source

I have static image which i need to convert in Base64 and then send it to Android/iOS native code.

If i select an image from file i am able to send it to native code and convert that to Base64.

But what if i have static image and then send it to native code.

<Image source={require('./img/icon.png')}/>

I want icon.png to be sent in Android/iOS native module.

I have done native coding, it is something like this

@ReactMethod
public void filterBase64(String base64, Callback stringCallback) {

}

But stucked at how to send Base64

I have checked react-native-image-to-base64 but not able to get solution, when i use

NativeModules.RNImageToBase64.getBase64String(uri, (err, base64) => {
    // Do something with the base64 string 
})

It shows error undefined is not an object

Answer

Amit Sharma picture Amit Sharma · Apr 11, 2017

With the help of RNFS plugin you can access React Native assets and convert them to Base64.

var RNFS = require('react-native-fs')
base64data = await RNFS.readFile('./img/icon.png', 'base64').then();
console.log(base64data);