Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 839
Avishay Bar Avatar asked Jan 20 '16 18:01

Avishay Bar


People also ask

How do you convert URI to Base64 react native?

import RNFS from 'react-native-fs'; var data = await RNFS. readFile( "file://path-to-file", 'base64'). then(res => { return res }); This works fine.

What is base 64 format?

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.


1 Answers

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

like image 137
Ven Jest Avatar answered Oct 08 '22 03:10

Ven Jest