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)
})
}
Related
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';
I'm using react-native-firebase and react-native-document-picker and I'm trying to follow the face detection tutorial.
Currently getting the following error despite having read access through PermissionsAndroid:
Permission Denial: reading com.android.provides.media.MediaDocumentsProvider uri [uri] from pid=4746, uid=10135 requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
I am able to display the selected image by the user on the screen but the react-native-firebase functions seems to not be able to have permission. The error happens at this call: const faces = await vision().faceDetectorProcessImage(localPath);.
Any suggestions on how to give the face detection function access or what am I doing wrong?
My AndroidManifest.xml file contains the following:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is all the code in that component for reference:
import React, {useState} from 'react';
import { Button, Text, Image, PermissionsAndroid } from 'react-native';
import vision, { VisionFaceContourType } from '#react-native-firebase/ml-vision';
import DocumentPicker from 'react-native-document-picker';
async function processFaces(localPath) {
console.log(localPath)
const faces = await vision().faceDetectorProcessImage(localPath);
console.log("Got faces")
faces.forEach(face => {
console.log('Head rotation on Y axis: ', face.headEulerAngleY);
console.log('Head rotation on Z axis: ', face.headEulerAngleZ);
console.log('Left eye open probability: ', face.leftEyeOpenProbability);
console.log('Right eye open probability: ', face.rightEyeOpenProbability);
console.log('Smiling probability: ', face.smilingProbability);
face.faceContours.forEach(contour => {
if (contour.type === VisionFaceContourType.FACE) {
console.log('Face outline points: ', contour.points);
}
});
});
}
async function pickFile () {
// Pick a single file
try {
const res = await DocumentPicker.pick({
type: [DocumentPicker.types.images],
});
console.log(
res.uri,
res.type, // mime type
res.name,
res.size
);
return res
} catch (err) {
if (DocumentPicker.isCancel(err)) {
// User cancelled the picker, exit any dialogs or menus and move on
console.log("User cancelled")
} else {
console.log("Error picking file or processing faces")
throw err;
}
}
}
const requestPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
{
title: "Files Permission",
message:
"App needs access to your files " +
"so you can run face detection.",
buttonNeutral: "Ask Me Later",
buttonNegative: "Cancel",
buttonPositive: "OK"
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("We can now read files");
} else {
console.log("File read permission denied");
}
return granted
} catch (err) {
console.warn(err);
}
};
function FaceDetectionScreen ({navigation}) {
const [image, setImage] = useState("");
return (
<>
<Text>This is the Face detection screen.</Text>
<Button title="Select Image to detect faces" onPress={async () => {
const permission = await requestPermission();
if (permission === PermissionsAndroid.RESULTS.GRANTED) {
const pickedImage = await pickFile();
const pickedImageUri = pickedImage.uri
setImage(pickedImageUri);
processFaces(pickedImageUri).then(() => console.log('Finished processing file.'));
}
}}/>
<Image style={{flex: 1}} source={{ uri: image}}/>
</>
);
}
export default FaceDetectionScreen;
Thanks to this comment on a github issue I was able to update my code and get it to work by updating the first three lines of processFaces as:
async function processFaces(contentUri) {
const stat = await RNFetchBlob.fs.stat(contentUri)
const faces = await vision().faceDetectorProcessImage(stat.path);
after importing import RNFetchBlob from 'rn-fetch-blob'.
rn-fetch-blob
Im trying to pick a file (pdf-file) from a module called react-native-file-picker. This works ok, and gaves me name, type, path and uri.
After this, i display the name of the document that i picked in a flatlist.
Now, what i want is to "onPress" of the item in the flatlist, open the document with some pdf viewer or something like that.
I've already tried to use other modules like react-native-view-pdf and react-native-pdf and react-native-pdf-view but i cant access the state of my uri with either of them.
The last one that i used it was react-native-file-viewer and doesn't work very well because it doesn't open the item on press.
This is my actual code.
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Button, TextInput,
Dimensions, FlatList } from 'react-native';
import AsyncStorage from '#react-native-community/async-storage'
import FilePickerManager from 'react-native-file-picker';
import FileViewer from 'react-native-file-viewer';
global.myfunction = function myfunction() {
FilePickerManager.showFilePicker(null, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled file picker');
}
else if (response.error) {
console.log('FilePickerManager Error: ', response.error);
}
else {
this.storeItem(response)
}
});
};
export default class Docs extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
title: 'Docs',
header: null
}
};
state = {
arr: [],
local: '',
password: '',
obj: null,
count: 1,
image: {},
b64: '',
isModalVisible: false,
pdfuri: null,
};
pdf = () => {
FilePickerManager.showFilePicker(null, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled file picker');
}
else if (response.error) {
console.log('FilePickerManager Error: ', response.error);
}
else {
this.storeItem(response)
this.setState({
pdfuri: response.path
});
}
});
}
toggleModal = (item) => {
this.setState({ isModalVisible: !this.state.isModalVisible, obj: item });
};
storeItem(item) {
try {
//we want to wait for the Promise returned by AsyncStorage.setItem()
//to be resolved to the actual value before returning the value~
console.log(item)
var joined = this.state.arr.concat(item);
console.log('files ', joined)
this.setState({ arr: joined })
AsyncStorage.setItem('files', JSON.stringify(joined));
console.log(this.state.arr)
} catch (error) {
console.log(error.message);
}
}
componentDidMount() {
//Here is the Trick
const { navigation } = this.props;
}
componentWillMount() {
AsyncStorage.getItem('files').then(array => {
item = JSON.parse(array)
item ? this.setState({ arr: item }) : null;
console.log(this.state.arr)
})
}
verpdf() {
const path =
"content://com.android.providers.downloads.documents/document/4183"
FileViewer.open(path, { showOpenWithDialog: true })
.then(() => {
// success
})
.catch(error => {
// error
});
}
render() {
return (
<View style={[styles.container, { marginTop: 20 }]}>
<FlatList
data={this.state.arr}
renderItem={({ item }) => <TouchableOpacity onPress=
{this.verpdf(item)} style={{ marginBottom: 10, marginTop: 10, alignItems: 'center' }}>
<Text>{item.fileName}</Text></TouchableOpacity>}
/>
<Button title='ok' onPress={this.pdf}></Button>
</View>
);
}
}
How should i do this?
Try to change the event handler from
onPress=
{this.verpdf(item)}
to
onPress=
{()=>this.verpdf(item)}
Like #Oleg said, to open a certain item i needed to change the event handler to a arrow function.
onPress = {this.verpdf(item)}
to
onPress= {()=>this.verpdf(item)}
After that i wanted to open a certain item from my flatlist which i did:
verpdf(item) {
const path = item.path
FileViewer.open(path, { showOpenWithDialog: true })
.then(() => {
// success
})
.catch(error => {
// error
});
}
The RNImage Picker says: 'Then later, if you want to display this image in your render() method:' But it's a default function. How can I display the image on screen?
export default function Expenses(){
const [ imageSource, setImageSource ] = useState(null);
const [ data, setData ] = useState(null);
uploadImage = async () => {
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 };
setImageSource({
imageSource: source
});
}
})
};
I'm using Styled-components and Photo it's styled.Image.
return (
<Container>
<Photo source={imageSource} />
<ButtonTouch
onPress={uploadImage}>
<TextButton>Select Image</TextButton>
</ButtonTouch>
</Container>
);
}
And let me simplify for yall. I'm trying get this photo on my phone storage or take a photo, whatever and display this photo on screen. But I can't display that. Return nothing.
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);
});