How to convert local image into base64 in react native and upload on server, please help anyone to solve this query. I already tried using library which available on google named image-to-base64 npm.
5 Answers
All guys we can get an base64 string of the image using Image picker in react native for Profile uses and many more. Here I put the piece of code which will help to get base64 string in react native using image picker function.
selectPhotoTapped() { const options = { quality: 1.0, maxWidth: 500, maxHeight: 500, storageOptions: { skipBackup: true, }, }; ImagePicker.showImagePicker(options, response => { console.log('Response = ', response.data); if (response.didCancel) { console.log('User cancelled photo picker'); } else if (response.error) { console.log('ImagePicker Error: ', response.error); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); } else { // let source = { uri: response.uri }; <-- here you can get uri of image // var RNFS = require('react-native-fs'); // You can also display the image using data: let source = 'data:image/jpeg;base64,'+ [response.data]; //<-- here you can get image with base64string this.setState({ avatarSource: source, }); // this.setState({ // Profile_Picture:this.state.avatarSource // }) // console.log(this.state.Profile_Picture) } }); }
After that you can using onPress event take image from your library but before that you have to grant permission for use android or IOS image from local storage. link of the installation for image picker Use This Link for Installation of Image picker in react native
Comments
Using react-native-image-base64:
import ImgToBase64 from 'react-native-image-base64'; ImgToBase64.getBase64String('file://path/to/file') .then(base64String => { // Send the base64String to server }) .catch(err => console.log(err)); 2 Comments
If you're using Expo you can also use readAsStringAsync from expo-file-system:
import * as FileSystem from "expo-file-system" const convertImageUriToBase64 = async (imageUri) => { const base64code = await FileSystem.readAsStringAsync(imageUri, { encoding: FileSystem.EncodingType.Base64, }) const dataConfig = "data:image/jpeg;base64," const base64File = `${dataConfig}${base64code}` return base64File } const base64Image = convertImageUriToBase64('file://...')