How to Convert Image to Base64 in React Native

When it comes to handling images, sometimes we may need to convert them to Base64 format. In this tutorial, let’s learn how to convert an image to Base64 string in react native.

We use react native blob util library to generate Base64 from the image. You can install the library using the following command.

npm install --save react-native-blob-util

Also, run the pod install command inside the ios folder. Then you can use the library by importing as given below.

import ReactNativeBlobUtil from 'react-native-blob-util';

In the following example, we convert an image from a remote URL into a Base64 string. See the following code.

import {StyleSheet, Button, View} from 'react-native';
import React from 'react';
import ReactNativeBlobUtil from 'react-native-blob-util';

function App() {
  const convert = () => {
    ReactNativeBlobUtil.fetch(
      'GET',
      'https://cdn.pixabay.com/photo/2016/03/23/20/49/music-note-1275650_1280.png',
    )
      .then(res => {
        let status = res.info().status;

        if (status === 200) {
          let base64Str = res.base64();
          console.log(base64Str);
        } else {
          // handle other status codes
        }
      })
      // Something went wrong:
      .catch(err => {
        // error handling
        console.log(err);
      });
  };

  return (
    <View style={styles.container}>
      <Button title="Click to Convert" onPress={() => convert()} />
    </View>
  );
}

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

The ‘convert’ function uses the ‘fetch’ method from the ‘react-native-blob-util’ library to make a GET request to an image URL. The image is then converted to Base64 format using the ‘base64’ method, and the resulting string is logged to the console.

If the image fetch request is unsuccessful, the error is caught and logged to the console.

That’s how you convert an image to base64 in react native.

Similar Posts

Leave a Reply