26

This should be included in the react-native APIs but I cannot seem to find any API included out of the box.

I want to open up the camera on the click of a button. I can see some APIs just for iOS but react-native should make things cross-platform.

Does anyone know how to access the camera (not the gallery) using react-native?

Trishant Pahwa
  • 2,559
  • 2
  • 14
  • 31
Virk Bilal
  • 640
  • 1
  • 5
  • 10

4 Answers4

15

You might like to use react-native-camera module for this.

Here's an example usage of the library:

'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);
Trishant Pahwa
  • 2,559
  • 2
  • 14
  • 31
  • 5
    That module still is not react-native official. – Virk Bilal Jul 23 '17 at 21:13
  • react-native version? – Trishant Pahwa Jul 23 '17 at 21:14
  • Javascript is a large community. You can check whether the build of that module is passing or not. And decide if you wish to use it. – Trishant Pahwa Jul 23 '17 at 21:15
  • 2
    @VirkBilal There is no "official" react-native camera library. `react-native-camera` is the closest thing to that at the moment, with nearly 6K stars on Github. You can also check out `react-native-camera-kit`: https://github.com/wix/react-native-camera-kit – Joshua Pinter Jul 02 '18 at 21:10
  • 2
    I am having lots of issues with react native camera and I would have saved around 1 month of time if I just wrote an intent to use the default camera application https://github.com/react-native-community/react-native-camera/issues/2478 – Fabrizio Bertoglio Oct 15 '19 at 01:22
  • react-native-camera is deprecated and failing builds. Use react-native-vision-camera instead. Here's its Github: https://github.com/mrousavy/react-native-vision-camera – Tim Strawbridge Apr 17 '22 at 17:34
1

Currently react-native-camera is deprecated and if you want to achieve native performance and reach feature support good choice is https://github.com/mrousavy/react-native-vision-camera

Features:

  • Photo, Video and Snapshot capture
  • Customizable devices and multi-cameras (smoothly zoom out to "fish-eye" camera)
  • Customizable FPS
  • Frame Processors (JS worklets to run QR-Code scanning, facial recognition, AI object detection, realtime video chats, ...)
  • Smooth zooming (Reanimated)
  • Fast pause and resume
  • HDR & Night modes

Example:

function App() {
  const devices = useCameraDevices('wide-angle-camera')
  const device = devices.back

  if (device == null) return <LoadingView />
  return (
    <Camera
      style={StyleSheet.absoluteFill}
      device={device}
      isActive={true}
    />
  )
}

Documentation:

https://mrousavy.com/react-native-vision-camera/docs/guides

enter image description here

Kirill Novikov
  • 2,576
  • 4
  • 20
  • 33
0

In React Native you can access the camera by first installing it using NPM: npm install react-native-camera --save react-native link react-native-camera

Then use this in your Component:

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

See this github repo for full example: https://github.com/lwansbrough/react-native-camera

Zain Merchant
  • 104
  • 1
  • 10
0

I found react-native-picker image picker handier for my needs, it can be useable for both camera and gallery. for the bellow example you need to install version: "react-native-image-picker": "^3.3.2",

https://www.npmjs.com/package/react-native-image-picker

import React, {useState, useEffect} from 'react';
import {StyleSheet, Text, View, Image} from 'react-native';
import cameraImage from '../../../../assets/icons/camera.png';
import galleryImage from '../../../../assets/icons//gallery.png';
import {TouchableWithoutFeedback} from 'react-native-gesture-handler';
import * as ImagePicker from 'react-native-image-picker';
import {PermissionsAndroid} from 'react-native';
const ImagePicker = () => {
  const [responseCamera, setResponseCamera] = React.useState(null);
  const [responseGallery, setResponseGallery] = React.useState(null);

  const openCameraWithPermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.CAMERA,
        {
          title: 'App Camera Permission',
          message: 'App needs access to your camera ',
          buttonNeutral: 'Ask Me Later',
          buttonNegative: 'Cancel',
          buttonPositive: 'OK',
        },
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        ImagePicker.launchCamera(
          {
            mediaType: 'photo',
            includeBase64: false,
            maxHeight: 200,
            maxWidth: 200,
          },
          (response) => {
            console.log(response);
            setResponseCamera(response);
            setResponseGallery(null);
          },
        );
      } else {
        console.log('Camera permission denied');
      }
    } catch (err) {
      console.warn(err);
    }
  };

  return (
    <View
      style={{
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-around',
        margin: 4,
      }}>
      <TouchableOpacity onPress={() => openCameraWithPermission()}>
        {responseCamera === null ? (
          <Image style={styles.icon} source={cameraImage} />
        ) : (
          <Image style={styles.icon} source={{uri: responseCamera.uri}} />
        )}
      </TouchableOpacity>
      <TouchableOpacity
        onPress={() =>
          ImagePicker.launchImageLibrary(
            {
              mediaType: 'photo',
              includeBase64: false,
              maxHeight: 200,
              maxWidth: 200,
            },
            (response) => {
              setResponseGallery(response);
              setResponseCamera(null);
            },
          )
        }>
        {responseGallery === null ? (
          <Image style={styles.icon} source={galleryImage} />
        ) : (
          <Image style={styles.icon} source={{uri: responseGallery.uri}} />
        )}
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  icon: {
    height: 50,
    width: 50,
  },
});

export default ImagePicker;

permissions for android:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera" />

enter image description here

Rafiq
  • 8,987
  • 4
  • 35
  • 35