How to Take and Save Photos in React Native

Capturing photos from the camera and saving them to the internal memory is a feature of many mobile apps. In this react native tutorial, let’s learn how to take photos and save them using react native vision camera.

The react native vision camera is a library that enables us to do many things with the camera. One among them is to capture a photo using the camera.

I already have a tutorial on taking photos using react native camera vision. I recommend you to go through it and set up the library in your project using the instructions given there.

Here, we use another library react native fs to save the captured photos. You can install the library using the instructions given there.

The react native camera vision already saves the captured photos in a temporary path. What we do is to use react native fs to move the photo from the temporary path to the picture directory.

See the code snippet given below.

 async function savePhoto(data: string) {
    const filename = 'test.jpeg';
    await RNFS.moveFile(data, `${RNFS.PicturesDirectoryPath}/${filename}`);
  }

Here the data is the temporary path. The photo will be saved in the pictures directory of your phone

Following is the complete code where we capture a photo and then save them in the pictures directory.

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';
import RNFS from 'react-native-fs';

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);
      savePhoto(photo.path);
      console.log(photo.path);
    }
  }
  async function savePhoto(data: string) {
    const filename = 'test.jpeg';
    await RNFS.moveFile(data, `${RNFS.PicturesDirectoryPath}/${filename}`);
  }

  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;

I hope this blog post on how to take and save photos is useful for you.

Similar Posts

Leave a Reply