Image to base64 in react native - react-native

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.

With expo API
import { ImageManipulator } from 'expo';
const response = await ImageManipulator.manipulateAsync("file to local path", [], { base64: true })
console.log('base64res' + JSON.stringify(response));

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

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));

only solution is react-native-fs
import RNFS from 'react-native-fs';
RNFS.readFile(this.state.imagePath, 'base64')
.then(res =>{
console.log(res);
});

Related

how to Scan qr code after capturing an image in react native

I am making a qr code scanner, where user can upload a qr code image from gallery and from that we can get the data of qr code.
Below is my code:
import RNQRGenerator from 'rn-qr-generator';
import {launchImageLibrary} from 'react-native-image-picker';
const options = {
title: 'photoUpload',
takePhotoButtonTitle: 'photoTake',
chooseFromLibraryButtonTitle: 'photoLibrary',
cancelButtonTitle: 'cancel',
quality: 0.7,
base64: true,
maxWidth: 728,
};
const App = () => {
const onPick = () => {
launchImageLibrary(options, response => {
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 {
RNQRGenerator.detect({uri: response.assets[0].uri})
.then(res => {
console.log('Detected value', res);
if (res.values.length === 0) {
console.log('Code not found');
} else {
console.log('value: ', res.values);
}
})
.catch(err => {
console.log('Cannot detect', err);
});
}
});
};
return (
<Button
title="Pick from library"
onPress={() => {
onPick();
}}
/>
);
};
This is working fine if user has the actual qr code image
I have an edge case: if user clicks an image of qr code, and then upload this image from gallery.
For this edge case, my written code is not working. I am not sure how to solve this edge case issue.
Try this
import RNQRGenerator from 'rn-qr-generator';
RNQRGenerator.detect({
uri: PATH_TO_IMAGE, // local path of the image. Can be skipped if base64 is passed.
base64: imageBase64String, // If uri is passed this option will be skipped.
})
.then(response => {
const { values } = response; // Array of detected QR code values. Empty if nothing found.
})
.catch(error => console.log('Cannot detect QR code in image', error));
To scan the image and get the information about that image barcode and qrcode...
you have to install npm i rn-qr-generator and to choose the image you have to install npm i react-native-image-picker
example:-
import {launchImageLibrary} from 'react-native-image-picker';
import RNQRGenerator from 'rn-qr-generator';
const openlibrary=async()=>{
const galleryOptions = {
mediaType: 'photo',
includeBase64: true,
};
launchImageLibrary(galleryOptions,(res)=>{
if(res.didCancel){
console.error("cancelled")
}else{
RNQRGenerator.detect({
base64:res?.assets[0]?.base64
}).then((item)=>{
console.log(item)
}).catch((err)=>{
console.log(err)
})
}
console.log(res)
}).catch(err=>{
console.log("err",err)
})
}

Undefined is not an object (evaluating 'response.assets[0]') React Native react-native-image-picker

I used react-native-image-picker;
import { launchImageLibrary } from 'react-native-image-picker';
And when I top add img, but close window I had a error
TypeError: undefined is not an object (evaluating 'response.assets[0]')
My code:
launchImageLibrary(options, (response) => {
if (response) {
let base64 = response?.assets[0]?.uri;
dispatch({
type: 'SET_PHOTO',
payload: {
photo: base64, photoNumber, photoType,
}
})
}
});
https://i.stack.imgur.com/wtOXg.png
What should I do? What kind of check to write? This only happens when you press button add photo from photo gallery, but changed my mind and closed the dialog window
You need to update the file path
const [filePath, setFilePath] = useState({
assets: [
{
uri: 'You CAN place here any random image link',
},
],
});
I advice you a similar but more extensive library for this. It is react-native-image-crop-picker.
import ImagePicker from 'react-native-image-crop-picker';
After importing, you can use it like this (though you may need to tweak it, please console log returning image data)
ImagePicker.openPicker({
width: 1536,
height: 2048,
includeBase64: true, // to get content as base64-encoded string
cropping: false,
}).then(image => {
dispatch({
type: 'SET_PHOTO',
payload: {
photo: image, photoNumber, photoType,
}
});
})
Further reading
react-native-image-crop-picker

TypeError: undefined is not an object (evaluating '_reactNativeImagePicker.default.showImagePicker')

Using React Image Picker i am facing this error:
TypeError: undefined is not an object (evaluating '_reactNativeImagePicker.default.showImagePicker')
This is what happens when i click on image picker function
Mobile Screenshot:
This is my Code:
import React from 'react';
import { View, Text,Button } from 'react-native';
import ImagePicker from 'react-native-image-picker';
const options = {
title: 'Select Avatar',
customButtons: [{ name: 'fb', title: 'Choose Photo from Facebook' }],
storageOptions: {
skipBackup: true,
path: 'images',
},
};
function Picker(){
const openPicker =()=>{
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
const source = { uri: response.uri };
// You can also display the image using data:
// const source = { uri: 'data:image/jpeg;base64,' + response.data };
console.log(source)
}
});
}
return(
<View>
<Button onPress={openPicker} title="Open image picker"></Button>
</View>
)
}
export default Picker;
I had this same issue and this is how I solved it.
import * as ImagePicker from "react-native-image-picker"
If your react-native-image-picker version is 3.x.x then, replace the above code with these lines,
import {launchCamera, launchImageLibrary} from 'react-native-image-picker'; // Migration from 2.x.x to 3.x.x => showImagePicker API is removed.
...
const openPicker =()=>{
launchCamera(options, (response) => { // Use launchImageLibrary to open image gallery
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
const source = { uri: response.uri };
// You can also display the image using data:
// const source = { uri: 'data:image/jpeg;base64,' + response.data };
console.log(source)
}
});
Read the docs
Issue:
import ImagePicker from "react-native-image-picker"
Solution:
import * as ImagePicker from "react-native-image-picker"
check your lib version if its 3x then try something like this
import * as ImagePicker from "react-native-image-picker"
<Button onPress={() =>
ImagePicker.launchImageLibrary(
{
mediaType: 'photo',
includeBase64: false,
maxHeight: 200,
maxWidth: 200,
},
(response) => {
console.log(response);
this.setState({resourcePath: response});
},
)
}
title="Select Image"/>
Replace
import { ImagePicker } from 'react-native-image-picker',
with
var ImagePicker = require('react-native-image-picker');
This is working for me.
you can downgrade your version of the image picker library I am facing same issue then I am using this CLI command to downgrade a version of the image picker
npm install react-native-image-picker#2.3.4
same like you can use this command
showImagePicker API is removed.
use Direct launchCamera or launchImageLibrary
import {launchCamera, launchImageLibrary} from 'react-native-image-picker';

App stop working when Image Picker is opened in React Native

I am developing a React Native application using React Native. I am using react native image picker library, https://www.npmjs.com/package/react-native-imagepicker to pick up the images from the Gallery. But when I opened the image picker, my app stopped working and exited.
This is my code
import React from "react";
import { CameraRoll, View, Text, Button, Alert, Image } from "react-native";
import ImagePicker from "react-native-image-picker";
// More info on all the options is below in the API Reference... just some common use cases shown here
const options = {
title: "Select Avatar",
customButtons: [{ name: "fb", title: "Choose Photo from Facebook" }],
storageOptions: {
skipBackup: true,
path: "images"
}
};
class Gallery extends React.Component {
constructor(props) {
super(props);
this.state = {
url:"https://www.designevo.com/res/templates/thumb_small/terrible-black-bat-icon.png",
avatarSource: null
};
}
saveToCameraRoll = () => {
let { url } = this.state;
};
_handlePickImageButton = () => {
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.didCancel) {
Alert.alert("User cancelled image picker")
} else if (response.error) {
//console.log("ImagePicker Error: ", response.error);
Alert.alert("ImagePicker Error:");
} else if (response.customButton) {
//console.log("User tapped custom button: ", response.customButton);
Alert.alert("Custom button");
} else {
const source = { uri: response.uri };
// You can also display the image using data:
// const source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source
});
}
});
};
render() {
return (
<View>
<Button
onPress={() => {
this._handlePickImageButton();
}}
title="Pick a image"
>
Pick image
</Button>
<Image source={this.state.avatarSource} />
</View>
);
}
}
export default Gallery;
What is wrong with my code? Also, I did not get any error info in the console as in the screenshot attached below.
I tried, opening in this way too
ImagePicker.launchImageLibrary(options, (response) => {
//nothing implemented yet
});
It just stopped working.
I added the following permission in the plist as well:
I tried this too
const options = {
noData: true
};
ImagePicker.launchImageLibrary(options, (response) => {
});
I found the issue. The problem was in the plist. When I was adding the permissions, I just copy-pasted from a post. Might be something was wrong with it. When I typed in the permissions in the XCode, I saw the suggestion box, so I just clicked on the suggestion box and added the description for each permission as below.
As you can see in the above screenshot, the String value in the Type column is grayed out and cannot be changed. In the screenshot attached in the question, those values can be changed. That is the difference.

undefined is not an object (evaluating '_expo.Permission.askAsync')

i don't know what's the problem exactly but when i click on the button to choose image that erreur fire in the console
here's my code
_checkPermissions = async () => {
try {
const { status } = await Permission.askAsync(Permission.CAMERA);
this.setState({ camera: status });
const { statusRoll } = await Permission.askAsync(Permission.CAMERA_ROLL);
this.setState({ cameraRoll: statusRoll });
} catch (err) {
console.log(err);
}
};
findNewImage = async () => {
try {
this._checkPermissions();
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: "Images",
allowsEditing: true,
quality: 1
});
if (!result.cancelled) {
this.setState({
image: result.uri
});
} else {
console.log("cancel");
}
} catch (err) {
// console.log(err);
}
};
to me what solved it was importing the permissions and imagePicker like this:
import * as Permissions from 'expo-permissions';
import * as ImagePicker from 'expo-image-picker';
instead of this:
import Permissions from 'expo-permissions';
import ImagePicker from 'expo-image-picker';
And that's basically because there is no default export
It is getAsync(), not askAsync()
https://docs.expo.io/versions/latest/sdk/permissions/
I know I'm a little late to the party, but I feel it's important to show a way that is currently working (as of 2022) and also askAsync is deprecated ...
Getting image from (native) CAMERA
TL;DR: Even though we want "camera", we will actually use expo-image-picker FOR THE CAMERA (yes, you read right!)
I REPEAT: DO NOT USE expo-camera FOR CAMERA!
REMEMBER: USE ImagePickerExpo.requestCameraPermissionsAsync()AND ImagePickerExpo.launchCameraAsync() NOT Camera....!
So install it first: expo install expo-image-picker
Then import everything, from it under 1 alias, I like to use ImagePickerExpo because ImagePicker itself is confusing since it can mean more libraries, + import all needed for this code - you can replace Button with any other button/pressable that supports onPress (to use react-native-elements, you need to install it with yarn add react-native-elements)
Create displaying component
Create a state & setter to save current image source
Create a function that requests the permissions and opens the camera
Return the coponent with button binding onPress on function from 5. and Image that is displayed from the state from 4. but only when available.
working & tested(so far on android in expo go) code:
import React, { useState } from 'react';
import { View, Image, Alert, StyleSheet } from 'react-native';
import { Button } from 'react-native-elements';
import * as ImagePickerExpo from 'expo-image-picker';
const MyCameraComponent = () => {
const [selectedImage, setSelectedImage] = useState(null);
const openCameraWithPermission = async () => {
let permissionResult = await ImagePickerExpo.requestCameraPermissionsAsync();
if (permissionResult.granted === false) {
Alert.alert("For this to work app needs camera roll permissions...");
return;
}
let cameraResult = await ImagePickerExpo.launchCameraAsync({
// ...
});
console.log(cameraResult);
if (cameraResult.cancelled === true) {
return;
}
setSelectedImage({ localUri: cameraResult.uri });
};
return (
<View>
<Button title='Take a photo' onPress={openCameraWithPermission}></Button>
{(selectedImage !== null) && <Image
source={{ uri: selectedImage.localUri }}
style={styles.thumbnail}
/>}
</View>
);
}
const styles = StyleSheet.create({
thumbnail: {
width: 300,
height: 300,
resizeMode: "contain"
}
});
export default MyCameraComponent;
Note that I had to style the Image for it to display, it didn't display to me without proper styling which I find misleading, but I guess that's the react native way...
BTW: This also works in Android emulator (besides expo go in real Android device)
It also works on snack on desktop but only when you choose android (or Web) - https://snack.expo.dev/#jave.web/expo-camera-from-expo-image-picker
Getting image from (native) gallery (not camera)
In case you're wondering how to do the same for gallery, the code is basically the same, you just need a different callback function for the button that uses requestMediaLibraryPermissionsAsync / launchImageLibraryAsync instead of the camera ones.
let openImagePickerAsync = async () => {
let permissionResult = await ImagePickerExpo.requestMediaLibraryPermissionsAsync();
if (permissionResult.granted === false) {
Alert.alert("For this to work app needs media library/gallery permissions...");
return;
}
let pickerResult = await ImagePickerExpo.launchImageLibraryAsync({
presentationStyle: 0, // without this iOS was crashing
});
console.log(pickerResult);
if (pickerResult.cancelled === true) {
return;
}
setSelectedImage({ localUri: pickerResult.uri });
}