Search code examples
javascriptimagebase64react-native

React-Native: Convert image url to base64 string


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?


Solution

  • 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