How to Capture Photos using Camera in React Native

Capturing photos is a common feature in many mobile apps. In this blog post, let’s explore how to capture photo using React Native and the various options available for customizing the camera experience for your users.

As the react native camera library is deprecated we are using react native vision camera in this tutorial. Remember that it requires iOS 11 or higher, and Android-SDK version 21 or higher.

Firstly, install the library using the following command.

npm i react-native-vision-camera

Navigate to the ios folder and run the following command.

pod install

Open the android/app/src/main/AndroidManifest.xml file and add the following permission inside the manifest tag.

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

For iOS, open Info.plist file and add the following inside the dict tag.

<key>NSCameraUsageDescription</key>
<string>$(PRODUCT_NAME) needs access to your Camera.</string>

That’s the installation part.

You should have camera permission to use camera to capture photos. You can get the permission status as given below.

const newCameraPermission = await Camera.requestCameraPermission()

A permission status for an app can have one of four possible values: authorized, not-determined, denied, and restricted (which is only applicable for iOS).

When the permission status is “authorized”, it means that the app is allowed to use the specified permission. In this case, the app can continue using the Camera view.

If the permission status is “not-determined”, it means that the app has not yet requested permission from the user. In this case, the app should continue by calling the request functions to request permission.

If the permission status is “denied”, it means that the app has already requested permission from the user but was explicitly denied. In this case, the app cannot use the request functions again, but it can use the Linking API to redirect the user to the Settings App where the user can manually grant the permission.

Finally, if the permission status is “restricted”, it means that the app cannot use the Camera because the functionality has been restricted, possibly due to active restrictions such as parental controls. This value is only applicable for iOS.

You can request the camera permission as given below.

const newCameraPermission = await Camera.requestCameraPermission()

After getting the permission you can set the camera view as given below.

function App() {
  const devices = useCameraDevices()
  const device = devices.back

   if (device == null) {
    return <Text>Camera not available</Text>;
  }
  return (
    <Camera
      style={StyleSheet.absoluteFill}
      device={device}
      isActive={true}
      photo={true}
    />
  )
}

Then you can capture the photo as given below.

const photo = await camera.current.takePhoto({
})

Following is the complete example where I launch the camera when the Button is pressed. When the photo is taken, the taken photo is shown as Image.

import React, {useEffect, useState, useRef} from 'react';
import {
  View,
  StyleSheet,
  Button,
  TouchableOpacity,
  Text,
  Image,
} from 'react-native';
import {Camera, useCameraDevices} from 'react-native-vision-camera';

function App() {
  const camera = useRef<Camera>(null);
  const devices = useCameraDevices();
  const device = devices.back;

  const [showCamera, setShowCamera] = useState(false);
  const [imageSource, setImageSource] = useState('');

  useEffect(() => {
    async function getPermission() {
      const newCameraPermission = await Camera.requestCameraPermission();
      console.log(newCameraPermission);
    }
    getPermission();
  }, []);

  async function capturePhoto() {
    if (camera.current !== null) {
      const photo = await camera.current.takePhoto({});
      setImageSource(photo.path);
      setShowCamera(false);
      console.log(photo.path);
    }
  }

  if (device == null) {
    return <Text>Camera not available</Text>;
  }

  return (
    <View style={styles.container}>
      {showCamera ? (
        <>
          <Camera
            ref={camera}
            style={StyleSheet.absoluteFill}
            device={device}
            isActive={showCamera}
            photo={true}
          />

          <View style={styles.buttonContainer}>
            <TouchableOpacity
              style={styles.camButton}
              onPress={() => capturePhoto()}
            />
          </View>
        </>
      ) : (
        <>
          <Button title="Launch Camera" onPress={() => setShowCamera(true)} />
          {imageSource !== '' ? (
            <Image
              style={styles.image}
              source={{
                uri: `file://'${imageSource}`,
              }}
            />
          ) : null}
        </>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    backgroundColor: 'gray',
  },
  buttonContainer: {
    position: 'absolute',
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
    bottom: 0,
    padding: 20,
  },
  camButton: {
    height: 80,
    width: 80,
    borderRadius: 40,
    backgroundColor: 'white',
    alignSelf: 'center',
  },
  image: {
    width: '100%',
    height: 'auto',
    aspectRatio: 9 / 16,
  },
});

export default App;

Following is the output.

I hope this react native tutorial to capture photo using react native vision camera is helpful for you.

Similar Posts

Leave a Reply