Vidya
Vidya

Reputation: 153

How to open the camera and taking the picture in react native?

I want to open the device camera from my app when user click on the button and when user click on back button it should react to my application from device camera. I am able to open camera and take photo by running react native project. But I want to do it how camera works in what's app. That is clicking on button -> opening camera -> send button .

I am an beginner in react native .I tried many ways but I am not getting how it can be done.

Can anybody assist me to do this.

My App.js code is,

'use strict';
import React, { Component } from 'react';
import {
  AppRegistry,
  Dimensions,
  StyleSheet,
  Text,
  TouchableHighlight,
  View
} from 'react-native';
import Camera from 'react-native-camera';

class BadInstagramCloneApp extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Camera
          ref={(cam) => {
            this.camera = cam;
          }}
          style={styles.preview}
          aspect={Camera.constants.Aspect.fill}>
          <Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
        </Camera>
      </View>
    );
  }

  takePicture() {
    const options = {};
    //options.location = ...
    this.camera.capture({metadata: options})
      .then((data) => console.log(data))
      .catch(err => console.error(err));
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
  },
  preview: {
    flex: 1,
    justifyContent: 'flex-end',
    alignItems: 'center'
  },
  capture: {
    flex: 0,
    backgroundColor: '#fff',
    borderRadius: 5,
    color: '#000',
    padding: 10,
    margin: 40
  }
});

AppRegistry.registerComponent('BadInstagramCloneApp', () => BadInstagramCloneApp);

Upvotes: 2

Views: 20688

Answers (4)

user23833122
user23833122

Reputation: 1

In Android To open camera on TouchableOpacity onPress when permission is granted like it asks user while using this App or only this time or Deny

OUTPUT:

[ask for Permission Pop up] [1]: https://i.sstatic.net/vJcPz.png

enter image description here Follow this steps:

open react-native project go to Explorer

android -> app -> src -> main -> open file AndroidManifest.xml

In AndroidManifest.xml file put this permission

<uses-permission
      android:name="android.permission.CAMERA"
    /> 

the above permission allow for CAMERA access in adnroid

open Terminal and run this command to use device camera and access

npm install react-native-image-picker 
//or else you can do 
yarn add react-native-image-picker 

also run this command for permissions it will install permission

npm install react-native-permissions

now create file and import this below line in it

  import React, {useState} from 'react';
import {
  View,
  Image,
  Platform,
  TouchableOpacity,
  Text,
  PermissionsAndroid,
  StyleSheet,
} from 'react-native';
    import {launchCamera} from 'react-native-image-picker';
    import {check, PERMISSIONS, RESULTS, request} from 'react-native-permissions';

    const CameraPermission = () => {

    const [imgUrl, setImgUri] = useState('');

  
      const requestCameraPermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.CAMERA,
        {
          title: 'Camera Permission',
          message:
            'App needs access to your camera ' + 'so you can take pictures.',
          buttonNeutral: 'Ask Me Later',
          buttonNegative: 'Cancel',
          buttonPositive: 'OK',
        },
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log('You can use the camera');
        opencamera();
      } else {
        console.log('Camera permission denied');
      }
    } catch (err) {
      console.warn(err);
    }
  };

const opencamera = async () => {
    const result = await launchCamera();
    setImgUri(result?.assets[0]?.uri);
    console.log('RESULT>>>', result);
  };
return (
    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
      
//here you can see your clicked Image from camera
<Image
        source={{
          uri: imgUrl,
        }}
        style={{
          height: 100,
          width: 100,
          alignSelf: 'center',
          borderRadius: 100,
          marginBottom: 20,
        }}></Image>

      <TouchableOpacity
        onPress={requestCameraPermission}
        style={{
          backgroundColor: '#CE1C4F',
          paddingHorizontal: 20,
          marginHorizontal: 20,
          height: 40,
          borderRadius: 20,
          justifyContent: 'center',
        }}>
        <Text
          style={{
            justifyContent: 'center',
            textAlign: 'center',
            fontSize: 18,
            fontWeight: '500',
            color: 'white',
          }}>
          Request Camera Permission
        </Text>
      </TouchableOpacity>

    </View>
  );
};
export default CameraPermission;

Happy Coding... :-)

Upvotes: 0

Ahmedakhtar11
Ahmedakhtar11

Reputation: 1458

Correction of best answer because of deprecation of Camera to RNCamera plus missing closing bracket ")" right before the .catch and like a spelling mistake with the declaration of state:

But basically there's 2 routes, whether you're using expo or react native. You gotta have Pods/Ruby/Cocoapods or manually link and all that if you're using traditional React Native, but just go with expo-camera if you got an expo set up and don't listen to this.

This is a React-Native with Pods/Ruby/CocoaPods solution, whereas going with expo-camera might be much faster and better if you're not set up like this.

import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  Button,
  TouchableOpacity
} from 'react-native';
import { RNCamera } from 'react-native-camera';

export default class Camera2 extends Component {
    constructor(props) {
        super(props);
        this.state = {
          isCameraVisible: false
        }
      }

      showCameraView = () => {
        this.setState({ isCameraVisible: true });
      }


      takePicture = async () => {
        try {
          const data = await this.camera.takePictureAsync();
          console.log('Path to image: ' + data.uri);
        } catch (err) {
          // console.log('err: ', err);
        }
      };
  render() {
    const { isCameraVisible } = this.state;
    return (
      <View style={styles.container}>
        {!isCameraVisible &&<Button title="Show me Camera" onPress={this.showCameraView} />}
        {isCameraVisible &&
           <RNCamera
           ref={cam => {
             this.camera = cam;
           }}
           style={styles.preview}
         >
           <View style={styles.captureContainer}>
             <TouchableOpacity style={styles.capture} onPress={this.takePicture}>
             <Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
               <Text>Take Photo</Text>
             </TouchableOpacity>
           </View>
         </RNCamera>}
      </View>
    );
  }
}

const styles = StyleSheet.create({
    container: {
      flex: 1,
      flexDirection: 'row',
    },
    preview: {
      flex: 1,
      justifyContent: 'flex-end',
      alignItems: 'center'
    },
    capture: {
      flex: 0,
      backgroundColor: '#fff',
      borderRadius: 5,
      color: '#000',
      padding: 10,
      margin: 40
    }
  });

Upvotes: 0

Sai kiran
Sai kiran

Reputation: 366

You can use https://github.com/ivpusic/react-native-image-crop-picker for this. This component helps you to take photo and also the photo if required. Follow the documentation correctly and here is the code for camera selection option

    ImagePicker.openCamera({
        cropping: true,
        width: 500,
        height: 500,
        cropperCircleOverlay: true,
        compressImageMaxWidth: 640,
        compressImageMaxHeight: 480,
        freeStyleCropEnabled: true,
    }).then(image => {
        this.setState({imageModalVisible: false})
})
.catch(e => {
        console.log(e), this.setState({imageModalVisible: false})
});

Upvotes: 0

nika95
nika95

Reputation: 325

You can use the state to show/hide the camera view/component. Please check the following code:

...
class BadInstagramCloneApp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isCameraVisiable: false
    }
  }

  showCameraView = () => {
    this.setState({ isCameraVisible: true });
  }
  render() {
    const { isCameraVisible } = this.state;
    return (
      <View style={styles.container}>
        {!isCameraVisible &&<Button title="Show me Camera" onPress={this.showCameraView} />}
        {isCameraVisible &&
        <Camera
          ref={(cam) => {
            this.camera = cam;
          }}
          style={styles.preview}
          aspect={Camera.constants.Aspect.fill}>
          <Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
        </Camera>}
      </View>
    );
  }

  takePicture() {
    const options = {};
    //options.location = ...
    this.camera.capture({metadata: options})
      .then((data) => {
         console.log(data);
         this.setState({ isCameraVisible: false });
    }
    .catch(err => console.error(err));
  }
}
...

Upvotes: 3

Related Questions