React-Native Camera did not open in android - react-native

I'm using expo for React-Native. React-Native camera works fine in iPhone but in android device it's not opening. In Android device it open when i open it with expo but when i generate apk file it's not opening. I checked the log it says camera don't has the permission. Please help me to solve this here is an example of my code:
import React from 'react';
import { Text, View, TouchableOpacity } from 'react-native';
import { Camera, Permissions } from 'expo';
export default class CameraExample extends React.Component {
state = {
hasCameraPermission: null,
type: Camera.Constants.Type.back,
};
async componentWillMount() {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ hasCameraPermission: status === 'granted' });
}
render() {
const { hasCameraPermission } = this.state;
if (hasCameraPermission === null) {
return <View />;
} else if (hasCameraPermission === false) {
return <Text>No access to camera</Text>;
} else {
return (
<View style={{ flex: 1 }}>
<Camera style={{ flex: 1 }} type={this.state.type}>
<View
style={{
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
}}>
<TouchableOpacity
style={{
flex: 0.1,
alignSelf: 'flex-end',
alignItems: 'center',
}}
onPress={() => {
this.setState({
type: this.state.type === Camera.Constants.Type.back
? Camera.Constants.Type.front
: Camera.Constants.Type.back,
});
}}>
<Text
style={{ fontSize: 18, marginBottom: 10, color: 'white' }}>
{' '}Flip{' '}
</Text>
</TouchableOpacity>
</View>
</Camera>
</View>
);
}
}
}
Any help is highly appreciated.
Thanks

Do you include camera permissions in app.json?
https://docs.expo.io/versions/latest/guides/configuration.html#permissions
It should look something along the lines of:
{
"expo": {
...
"android": {
"permissions": ["CAMERA"]
}
}
}

Related

How to save image in a Phone on clicking in React Native Expo Camera?

This is what so far I have done. Here I am able to switch ON the camera and also get access to images using ImagePicker. But while clicking image, I am getting anything like where the image is saved and also I am unable to select the image properly.
When I click pic on camera, I get this in console:
"Object {
"height": 4000,
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540himanshu717171%252FMyProject/Camera/373e905c-2ef8-4f0f-b4a4-78ac8a64732c.jpg",
"width": 3000,
}"
And while selecting any image from Phone, I am getting this response in a console:
"Object {
"cancelled": false,
"height": 721,
"type": "image",
"uri": "file:/data/user/0/host.exp.exponent/cache/ExperienceData/%2540himanshu717171%252FMyProject/ImagePicker/937bed14-dc51-4786-8836-09965b17d327.jpg",
"width": 1280,
}"
This is my code. Please suggest me any changes required.
import React from 'react';
import { StyleSheet, Text, View ,TouchableOpacity,Platform, } from 'react-native';
import { Camera } from 'expo-camera';
import * as Permissions from 'expo-permissions';
import { FontAwesome, Ionicons,MaterialCommunityIcons } from '#expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
export default class App extends React.Component {
state = {
hasPermission: null,
cameraType: Camera.Constants.Type.back,
}
async componentDidMount() {
this.getPermissionAsync()
}
getPermissionAsync = async () => {
// Camera roll Permission
if (Platform.OS === 'ios') {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status !== 'granted') {
alert('Sorry, we need camera roll permissions to make this work!');
}
}
// Camera Permission
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ hasPermission: status === 'granted' });
}
handleCameraType=()=>{
const { cameraType } = this.state
this.setState({cameraType:
cameraType === Camera.Constants.Type.back
? Camera.Constants.Type.front
: Camera.Constants.Type.back
})
}
takePicture = async () => {
if (this.camera) {
let photo = await this.camera.takePictureAsync();
console.log(photo);
}
}
pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images
});
console.log(result);
}
render(){
const { hasPermission } = this.state
if (hasPermission === null) {
return <View />;
} else if (hasPermission === false) {
return <Text>No access to camera</Text>;
} else {
return (
<View style={{ flex: 1 }}>
<Camera style={{ flex: 1 }} type={this.state.cameraType} ref={ref => {this.camera = ref}}>
<View style={{flex:1, flexDirection:"row",justifyContent:"space-between",margin:30}}>
<TouchableOpacity
style={{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: 'transparent'
}}
onPress={()=>this.pickImage()}>
<Ionicons
name="ios-photos"
style={{ color: "#fff", fontSize: 40}}
/>
</TouchableOpacity>
<TouchableOpacity
style={{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: 'transparent',
}}
onPress={()=>this.takePicture()}
>
<FontAwesome
name="camera"
style={{ color: "#fff", fontSize: 40}}
/>
</TouchableOpacity>
<TouchableOpacity
style={{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: 'transparent',
}}
onPress={()=>this.handleCameraType()}
>
<MaterialCommunityIcons
name="camera-switch"
style={{ color: "#fff", fontSize: 40}}
/>
</TouchableOpacity>
</View>
</Camera>
</View>
);
}
}
}
App.navigationOptions = {
title: 'Camera',
headerStyle: {
backgroundColor: '#ff6666',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
fontSize:20
},
};

react native bar code reader is not working correctly?

Problem:
I have created a react native application. There I am using expo-barcode-scanner. This is how my code is organized.
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
TouchableOpacity,
Image,
TextInput,
ScrollView,
KeyboardAvoidingView,
} from "react-native";
import Dimensions from "Dimensions";
import * as Permissions from "expo-permissions";
import { BarCodeScanner } from "expo-barcode-scanner";
class Home extends Component {
constructor(props) {
super(props);
this.state = {
QrPress: false,
hasCameraPermission: null,
};
}
componentDidMount() {
this.getPermissionsAsync();
}
getPermissionsAsync = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ hasCameraPermission: status === "granted" });
};
_onPress_QrScan() {
this.setState({
QrPress: true
});
}
handleBarCodeScanned = ({ type, data }) => {
this.setState({ QrPress: false, scanned: true, lastScannedUrl: data });
};
renderBarcodeReader() {
const { hasCameraPermission, scanned } = this.state;
if (hasCameraPermission === null) {
return <Text>Requesting for camera permission</Text>;
}
if (hasCameraPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View
style={{
flex: 1,
flexDirection: "column",
justifyContent: "flex-end"
}}
>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : this.handleBarCodeScanned}
style={StyleSheet.absoluteFillObject}
/>
{scanned && (
<Button
title={"Tap to Scan Again"}
onPress={() => this.setState({ scanned: false })}
/>
)}
</View>
);
}
render() {
const { hasCameraPermission, scanned, QrPress } = this.state;
let marker = null;
if (this.state.locationChosen) {
marker = <MapView.Marker coordinate={this.state.focusedLocation} />;
}
return (
<View style={{}}>
<KeyboardAvoidingView behavior="padding" enabled>
<ScrollView>
<TouchableOpacity
onPress={() => {
this._onPress_QrScan();
}}
activeOpacity={3}
>
<Text style={styles.viewDetails}>Scan QR</Text>
</TouchableOpacity>
{QrPress ? (
<React.Fragment>{this.renderBarcodeReader()}</React.Fragment>
) : (
null
)}
</ScrollView>
</KeyboardAvoidingView>
</View>
);
}
}
const DEVICE_WIDTH = Dimensions.get("window").width;
const DEVICE_HEIGHT = Dimensions.get("window").height;
const styles = StyleSheet.create({
container: {
top: 0,
flex: 3
},
map: {
flex: 1,
height: 130
},
homeHeader: {
flexDirection: "column",
flex: 1
},
homeHeaderImage: {
flexDirection: "row"
},
homeHederText: {
fontSize: 18,
fontWeight: "bold",
fontStyle: "normal",
fontFamily: "sans-serif",
letterSpacing: 0.81,
color: "#000104",
marginTop: "2%",
marginLeft: "40%",
marginRight: "3%"
},
hederContentContainer: {
flexDirection: "row",
marginTop: "30%",
marginBottom: "10%"
},
qrCodeGeneraterContainer: {
alignItems: "center",
justifyContent: "center"
},
});
export default Home;
But when I open the app with expo client on my android mobile. It is not rendering the barcode reader. It means It is not opening the camera to scan the QR. It just only shows a blank white background. I tried a lot to find out the solution to this problem. Unfortunately, I could not do anything with this issue. Can someone help me with this problem? Thank you.
There are a lot's of issue in your component. Please use the below code and update the style etc depend on your requirements.
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
TouchableOpacity,
Image,
TextInput,
ScrollView,
KeyboardAvoidingView,
Dimensions,
Button,
} from "react-native";
import MapView from 'react-native-maps';
import * as Permissions from "expo-permissions";
import { BarCodeScanner } from "expo-barcode-scanner";
class Home extends Component {
constructor(props) {
super(props);
this.state = {
QrPress: false,
hasCameraPermission: null,
};
}
componentDidMount() {
this.getPermissionsAsync();
}
getPermissionsAsync = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ hasCameraPermission: status === "granted" });
};
_onPress_QrScan = () => {
this.setState({
QrPress: true
});
}
handleBarCodeScanned = ({ type, data }) => {
this.setState({ QrPress: false, scanned: true, lastScannedUrl: data });
};
renderBarcodeReader = () => {
const { hasCameraPermission, scanned } = this.state;
if (hasCameraPermission === null) {
return <Text>Requesting for camera permission</Text>;
}
if (hasCameraPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View
style={{
flex: 1,
flexDirection: "column",
justifyContent: "flex-end",
}}
>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : this.handleBarCodeScanned}
style={{ flex:1, ...StyleSheet.absoluteFillObject}}
/>
{scanned && (
<Button
title={"Tap to Scan Again"}
onPress={() => this.setState({ scanned: false })}
/>
)}
</View>
);
}
render() {
const { hasCameraPermission, scanned, QrPress } = this.state;
let marker = null;
if (this.state.locationChosen) {
marker = <MapView.Marker coordinate={this.state.focusedLocation} />;
}
return (
<View style={{flex:1}}>
<KeyboardAvoidingView behavior="padding" enabled style={{flex:1}}>
<ScrollView contentContainerStyle={{flexGrow: 1}} >
{QrPress ? (
<View style={{flex:1}}>
{this.renderBarcodeReader()}
</View>
) : (
<View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
<TouchableOpacity
onPress={this._onPress_QrScan}
activeOpacity={3}
>
<Text style={styles.viewDetails}>Scan QR</Text>
</TouchableOpacity>
</View>
)}
</ScrollView>
</KeyboardAvoidingView>
</View>
);
}
}
const DEVICE_WIDTH = Dimensions.get("window").width;
const DEVICE_HEIGHT = Dimensions.get("window").height;
const styles = StyleSheet.create({
container: {
top: 0,
flex: 3
},
map: {
flex: 1,
height: 130
},
homeHeader: {
flexDirection: "column",
flex: 1
},
homeHeaderImage: {
flexDirection: "row"
},
homeHederText: {
fontSize: 18,
fontWeight: "bold",
fontStyle: "normal",
fontFamily: "sans-serif",
letterSpacing: 0.81,
color: "#000104",
marginTop: "2%",
marginLeft: "40%",
marginRight: "3%"
},
hederContentContainer: {
flexDirection: "row",
marginTop: "30%",
marginBottom: "10%"
},
qrCodeGeneraterContainer: {
alignItems: "center",
justifyContent: "center"
},
});
export default Home;

take a picture with expo camera

I am trying to take a picture for a react-native expo application, but I can't figure it out and the following answer on stack overflow isn't helping: How to snap pictures using expo react native camera?.
I got my code mostly from the expo demo on their site (https://docs.expo.io/versions/latest/sdk/camera/#takepictureasync) with the exception of I added a picture button I want to use to take a picture. Can someone please help me out?
I have already tried working with the above-mentioned stack overflow help, and it isn't working.
import React from 'react';
import { Text, View, TouchableOpacity, Image } from 'react-native';
import * as Permissions from 'expo-permissions';
import { Camera } from 'expo-camera';
export default class CameraExample extends React.Component {
state = {
hasCameraPermission: null,
type: Camera.Constants.Type.back,
};
async componentDidMount() {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ hasCameraPermission: status === 'granted' });
}
render() {
const { hasCameraPermission } = this.state;
if (hasCameraPermission === null) {
return <View />;
} else if (hasCameraPermission === false) {
return <Text>No access to camera</Text>;
} else {
return (
<View style={{ flex: 1 }}>
<Camera style={{ flex: 1 }} type={this.state.type}>
<View
style={{
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
}}>
<TouchableOpacity
style={{
flex: 0.1,
alignSelf: 'flex-end',
alignItems: 'center',
}}
onPress={() => {
this.setState({
type:
this.state.type === Camera.Constants.Type.back
? Camera.Constants.Type.front
: Camera.Constants.Type.back,
});
}}>
<Text style={{ fontSize: 18, marginBottom: 10, color: 'white' }}> Flip </Text>
</TouchableOpacity>
<TouchableOpacity>
<Image source={require("./images/camera.jpeg")}
style={{width: 100,
height: 100}} /> /* this is my button for taking the picture*/
</TouchableOpacity>
</View>
</Camera>
</View>
);
}
}
}
I just want to snap a picture and display to the console for now.
in this part of your code, you need set a onPress action to "snap" a picture.
My suggestion is simple as to add a
<TouchableOpacity onPress={() => takePicture()}>
<Image source={require("./images/camera.jpeg")} style={{width: 100, height: 100}} />
</TouchableOpacity>
And add the Async function to receive the actual picture:
const takePicture = async () => {
if (this.camera) {
const options = {quality: 1, base64: true};
const data = await this.camera.takePictureAsync(options);
console.log(data);
}
};
Go to your terminal and you have there your log with Image BASE64 Image.
I hope this helped you :)

wants to capture image in by using expo camera

i'm trying to capture image from expo camera but when i alert my photo nothing shown up here is complete code of my component
import React from 'react';
import { Text, View, TouchableOpacity } from 'react-native';
import { Camera, Permissions } from 'expo';
import {
Container,
Title,
Content,
Header,
Button,
Switch,
Left,
Body,
Right,
List,ListItem,Thumbnail,Footer,FooterTab
} from "native-base";
import {Icon} from 'react-native-elements';
export default class CameraEx extends React.Component {
static navigationOptions = {
header: null
}
state = {
hasCameraPermission: null,
type: Camera.Constants.Type.back,
};
async componentDidMount() {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ hasCameraPermission: status === 'granted' });
}
takePicture = async function() {
if (this.camera) {
let photo = await this.camera.takePictureAsync();
alert(photo);
}
}
render() {
const { hasCameraPermission } = this.state;
if (hasCameraPermission === null) {
return <View />;
} else if (hasCameraPermission === false) {
return <Text>No access to camera</Text>;
} else {
return (
<Container style={{ flex: 1 }}>
<Header transparent>
<Left>
<Button transparent onPress={() =>this.props.navigation.navigate('Home') }>
<Icon name='arrow-back' />
</Button>
</Left>
</Header>
<Camera style={{ flex: 1 }} type={this.state.type}>
<View
style={{
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
justifyContent:'space-between',
width:"50%"
}}>
<TouchableOpacity
style={{
//flex: 0.1,
alignSelf: 'flex-end',
alignItems: 'center',
}}
onPress={() => {
this.setState({
type: this.state.type === Camera.Constants.Type.back
? Camera.Constants.Type.front
: Camera.Constants.Type.back,
});
}}>
<Text
style={{ fontSize: 18, marginBottom: 10, color: 'white' }}>
{' '}Flip{' '}
</Text>
</TouchableOpacity>
<TouchableOpacity
style={{
// flex: 0.1,
alignSelf: 'flex-end',
alignItems: 'center',
}}
onPress={()=>this.takePicture()}
>
<Text
style={{ fontSize: 18, marginBottom: 10, color: 'white' }}>
{' '}Take Picture{' '}
</Text>
</TouchableOpacity>
</View>
</Camera>
</Container>
);
}
}
}
here is a complete code my component please let me know how i can capture image and stored into state i'm beginner ............................................................................................................................................. ....
you cannot show a picture in alert box. you need to pass the source or base64 of image to react native Image component.
import {ImagePicker} from 'expo';
const options = {
base64: true,
allowsEditing: true
};
const data = await ImagePicker.launchCameraAsync(options);
if (data.cancelled !== true) {
this.setState({imageBase64: data.base64});
}
and then you can use like this:
<Image source={`data:image/png;base64, ${this.state.imageBase64}`} />

Black image captured from expo takeSnapshotAsync

I have a react native component in which I am trying to capture an image.
The problem is when I capture the image, it is returning a black image.
My component is as follows:
import React from 'react';
var inspect = require('util-inspect');
import { Text, View, TouchableOpacity, Button, Image } from 'react-native';
import { Camera, Permissions, takeSnapshotAsync } from 'expo';
export default class CameraScreen extends React.Component {
state = {
hasCameraPermission: null,
type: Camera.Constants.Type.back,
imageUrI: ''
};
async componentWillMount() {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ hasCameraPermission: status === 'granted' });
}
async capture(e){
console.log('e', takeSnapshotAsync)
try{
let result = await takeSnapshotAsync(this.refs.camera, {
format: 'png',
result: 'file',
});
this.setState({imageUrI: result})
this.upload(result)
console.log("result", result)
}catch(err){
console.log('err', err)
}
}
upload(photo_uri){
const data = new FormData();
data.append('name', 'testName'); // you can append anyone.
data.append('webcam', {
uri: photo_uri,
type: 'image/png', // or photo.type
name: 'testPhotoName'
});
fetch('http://0647ad02.ngrok.io/upload', {
method: 'post',
body: data
}).then(res => {
console.log('res', res)
}).catch(err => {
console.log("err", err)
})
}
render() {
const { hasCameraPermission } = this.state;
if (hasCameraPermission === null) {
return <View />;
} else if (hasCameraPermission === false) {
return <Text>No access to camera</Text>;
} else if (this.state.imageUrI) {
return (<Image
style={{flex: 1}}
source={{uri: this.state.imageUrI}}
/>);
} else {
return (
<View
style={{
flex: 1,
flexDirection: 'column',
}}
>
<Camera
style={{ flex: 3 }}
type={this.state.type}
ref="camera"
>
</Camera>
<View
style={{
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
}}>
<TouchableOpacity
style={{
flex: 0.5,
alignSelf: 'flex-end',
alignItems: 'center',
}}
onPress={() => {
this.setState({
type: this.state.type === Camera.Constants.Type.back
? Camera.Constants.Type.front
: Camera.Constants.Type.back,
});
}}>
<Text
style={{ fontSize: 18, marginBottom: 10, color: 'white' }}>
{' '}Flip{' '}
</Text>
</TouchableOpacity>
<TouchableOpacity
style={{
flex: 0.5,
alignSelf: 'flex-end',
alignItems: 'center',
}}
onPress={() => this.capture()}>
<Text
style={{ borderColor: 'white', borderWidth: 1, borderRadius: 100, width: 100, height: 100, fontSize: 18, marginBottom: 10, color: 'white' }}>
{' '}
</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
}
As you can see, I have a <Camera> component imported from expo. This then has a touch component to handle the capture() action.
My capture function is using this.refs.camera to target the view and then passes the options to return a file and png as a result.
I am guessing it is one of these two options that are wrong? Either I am targeting the wrong element (I have tried others to no avail) or the file returned doesn't actually exist? I have tried returning a binary file but having trouble posting that in the upload function.
Am I on the right track?
I am testing on an Android One Plus 2 phone running android 6.0.1
Thanks
Camera from Expo is currently unsupported by .takeSnapshotAsync, unfortunately. See https://github.com/expo/expo/issues/1003 for more details