Implementing a Camera in a React Native App using react-native-vision-camera

 Recently, react-native-vision-camera emerged as a powerful alternative to react-native-camera, which has been deprecated due to a lack of maintainers and increased code complexity. Let's explore setting up a camera in a React Native application using react-native-vision-camera.

Installation:

First, install the react-native-vision-camera package:

npm i react-native-vision-camera

Android Permissions:

Open android\app\src\main\AndroidManifest.xml and ensure you've added necessary permissions:

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

If you refere the documentaion they have metioned that to use useCameraDevices.

const devices = useCameraDevices();
const device = devices.back;

But Truthfully it was not working, devices giving a array of object response. So devices.back is undefined.

Using the Camera:

Here’s an example of how to use the camera:

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

const App = () => {
const [cameraPermission, setCameraPermission] = useState(null);
const device = useCameraDevice('back'); // Set the initial camera device
const camera = useRef<Camera>(null);
const [capturedPhoto, setCapturedPhoto] = useState(null);
const [showPreview, setShowPreview] = useState(false);

const checkCameraPermission = async () => {
const status = await Camera.getCameraPermissionStatus();
console.log('status',status);

if (status === 'granted') {
setCameraPermission(true);
} else if (status === 'notDetermined') {
const permission = await Camera.requestCameraPermission();
setCameraPermission(permission === 'authorized');
} else {
setCameraPermission(false);
}
};

useEffect(() => {
checkCameraPermission();
}, []);

if (cameraPermission === null) {
return <Text>Checking camera permission...</Text>;
} else if (!cameraPermission) {
return <Text>Camera permission not granted</Text>;
}

if (!device) {
return <Text>No camera device available</Text>;
}

// const camera = useRef<Camera>(null);
// const camera = useRef(null);

const takePhoto = async () => {
try {
if (!camera.current) {
console.error('Camera reference not available.', camera);
return;
}

const photo = await camera.current.takePhoto();
console.log(photo);

if (photo) {
setCapturedPhoto(`file://${photo.path}`);
setShowPreview(true);
} else {
console.error('Photo captured is undefined or empty.');
}
} catch (error) {
console.error('Error capturing photo:', error);
}
};

const confirmPhoto = () => {
// User confirmed, further actions with the captured photo
// For example, save the photo to storage, etc.
console.log('Photo confirmed:', capturedPhoto);
setShowPreview(false); // Hide the preview after confirmation
};

const retakePhoto = () => {
// User wants to retake the photo
setCapturedPhoto(null); // Clear the captured photo
setShowPreview(false); // Hide the preview
};

const onCameraReady = (ref) => {
// Camera component is ready, set the camera reference
camera.current = ref;// Reference to the Camera component (e.g., obtained from ref prop)
};

return (
<View style={{ flex: 1 }}>
<Camera
style={{ flex: 1 }}
device={device}
isActive={true}
ref={(ref) => onCameraReady(ref)}
photo={true}
video={true}
/>
{showPreview && capturedPhoto ? (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Image
source={{ uri: capturedPhoto }} // Assuming the photo is a valid URI
style={{ width: 300, height: 300, marginBottom: 20 }}
/>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<Button title="Retake" onPress={retakePhoto} />
<Button title="Confirm" onPress={confirmPhoto} />
</View>
</View>
) : (
<View style={{ flexDirection: 'row', justifyContent: 'space-evenly' }}>
<Button title="Take Photo" onPress={takePhoto} />
</View>

)}

</View>
);
};

export default App;

This example demonstrates basic functionalities like checking camera permissions, capturing a photo, and displaying a preview.

The react-native-vision-camera library offers various features such as video recording, snapshots, and more. However, handling the UI for these functionalities requires custom implementation.

You can customize and expand upon this content as needed, delving into more features or customizations provided by the react-native-vision-camera library.

Feel free to explore and design according to your application’s needs!

Happy coding!

Comments

Popular posts from this blog

Creating a Circular File Download Progress Bar using SVG in React Native

Best Practices for React Native Development Don’t and Do’s Prem Yathvik

Check the React native application is connected to the Internet.