5 Simple Steps to Add Awesome Camera Feature to Your React Native App Using Image Picker – with Code Snippets

Table of content

  1. Introduction
  2. Step 1: Install Required Libraries
  3. Step 2: Create Camera Component
  4. Step 3: Implement Image Picker
  5. Step 4: Save Image to Device
  6. Step 5: Preview Image
  7. Conclusion
  8. Code Snippets

Introduction

React Native is a popular JavaScript framework that allows developers to build mobile apps for both Android and iOS platforms using a single codebase. One of the key features that users expect in mobile apps is the ability to take photos or videos using their device's camera. In this article, we will show you how to add the camera feature to your React Native app using the Image Picker library. We will also provide you with a few code snippets that you can easily integrate into your project. By the end of this article, you will be able to implement a fully functional camera feature that works seamlessly with your app. Let's get started!

Step 1: Install Required Libraries


In order to add camera functionality to your React Native app using Image Picker, you will need to install two libraries: react-native-image-picker and react-native-permissions.

The react-native-image-picker library provides a simple and customizable way to access the device's camera and photo gallery. The react-native-permissions library, on the other hand, is used to request permission from the user to access the camera and photo gallery.

To install these libraries, you will need to run the following command in your terminal:

npm install react-native-image-picker react-native-permissions --save

Once the installation is complete, you will need to link these libraries to your project. To do so, run the following command:

react-native link react-native-image-picker
react-native link react-native-permissions

This will link the libraries to your project and make them available for use in your code. After completing these steps, you can move on to Step 2 to learn how to configure the Image Picker library.

Step 2: Create Camera Component


Now that we have installed the required modules for our image picker, it's time to create a camera component in our React Native app. The camera component will be responsible for taking pictures using the device's camera and returning the captured image to our app.

To create the camera component, we'll start by importing the necessary components from the react-native module:

import React, { useState } from 'react';
import { View, TouchableOpacity, Text, Image } from 'react-native';
import ImagePicker from 'react-native-image-picker';

Next, we'll create a functional component called Camera and define a state variable called image. We'll set the initial value of image to null.

const Camera = () => {
  const [image, setImage] = useState(null);
  
  ...
}

We'll use the TouchableOpacity component to create a button that triggers the camera. Inside the TouchableOpacity, we'll add an onPress event that calls the launchCamera method from the ImagePicker module. This method will open the device's camera and allow the user to take a picture.

<TouchableOpacity onPress={() => {
    ImagePicker.launchCamera({}, (response) => {
        console.log(response);
    });
}}>
    <Text>Take Picture</Text>
</TouchableOpacity>

When the user takes a picture, the launchCamera method will return an object with information about the captured image. We can access this information by passing a callback function as the second argument to the launchCamera method. In the example above, we're simply logging the response to the console.

Finally, we'll create an Image component that displays the captured image. We'll only display the image if image is not null.

{image && <Image source={{ uri: image.uri }} style={{ width: 200, height: 200 }} />}

With these steps, we have created a camera component that allows the user to take a picture and display the captured image in our React Native app. We can now move on to the next step and add more features to our image picker.

Step 3: Implement Image Picker

To implement Image Picker in your React Native app, the first thing you need to do is install the Image Picker library. Use the following command to install it:

npm install react-native-image-picker --save

Next, you need to import the library into your code. Add the following line at the top of your file:

import ImagePicker from 'react-native-image-picker';

Now you can call the Image Picker function in your code. Here's an example of how you can use it:

ImagePicker.showImagePicker(options, (response) => {
  console.log('Response = ', response);

  if (response.didCancel) {
    console.log('User cancelled image picker');
  } else if (response.error) {
    console.log('ImagePicker Error: ', response.error);
  } else if (response.customButton) {
    console.log('User tapped custom button: ', response.customButton);
  } else {
    const source = { uri: response.uri };

    // You can also display the image using data:
    // const source = { uri: 'data:image/jpeg;base64,' + response.data };

    this.setState({
      avatarSource: source,
    });
  }
});

The showImagePicker function takes two parameters: options and a callback function. The options parameter is an object that allows you to customize the Image Picker. You can set options such as the title and message to display, the type of images to show (camera or photo library), and more. The callback function is called when the user selects an image or cancels the selection. The response object contains information about the selected image, such as its URI and data.

In the example above, the if statements check for different responses from the user. If the user cancels the selection, an error occurs, or the user taps a custom button (if you included one in the options), the appropriate response is logged to the console. Otherwise, the source of the selected image is set as the state of the component, which can then be displayed in your app.

Step 4: Save Image to Device

After capturing or selecting an image, the next step is to save it to the device. To accomplish this, we first need to generate a unique filename for the image. We can use the uuid package to generate a unique ID for each image, which we can append to the file path to create a unique filename.

import uuid from 'react-native-uuid';
import { Platform } from 'react-native';

const saveImage = async (imageURI) => {
  const extension = Platform.OS === 'android' ? 'file://' : '';
  const filename = `${extension}${FileSystem.documentDirectory}${uuid.v4()}.jpg`;

  // code to save image to device using the filename
}

Next, we need to write the image file to the device. We can use the FileSystem.writeAsStringAsync() method provided by the expo-file-system package to accomplish this.

import { FileSystem } from 'expo';

const saveImage = async (imageURI) => {
  // generate filename
  // ...

  try {
    await FileSystem.writeAsStringAsync(filename, imageURI, {
      encoding: FileSystem.EncodingType.Base64,
    });
    console.log(`Image saved to ${filename}`);
  } catch (error) {
    console.error(`Error saving image: ${error}`);
  }
}

The writeAsStringAsync() method takes three arguments:

  1. The filename to write the data to.
  2. The data to write, which in our case is the base64-encoded image data.
  3. An options object that specifies the encoding type. We use FileSystem.EncodingType.Base64 since we are passing base64-encoded data.

Finally, we log a message to the console indicating that the image was successfully saved, or log an error message if there was an issue.

That's it! With these few lines of code, we can easily save images to the device in our React Native app.

Step 5: Preview Image

To preview the selected image before it is uploaded, we can make use of the Image component provided by React Native. In the ImagePicker component, we have access to the uri property of the selected image. We can use this property to set the source of the Image component, which will then display the selected image.

Here's how we can modify our code to add the preview feature:

import React, { useState } from 'react';
import { Button, Image, View } from 'react-native';
import ImagePicker from 'react-native-image-picker';

const App = () => {
  const [imageURI, setImageURI] = useState('');

  const handleChooseImage = () => {
    ImagePicker.showImagePicker({}, response => {
      if (response.uri) {
        setImageURI(response.uri);
      }
    });
  };

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="Choose Image" onPress={handleChooseImage} />
      {imageURI ? (
        <Image source={{ uri: imageURI }} style={{ width: 200, height: 200 }} />
      ) : null}
    </View>
  );
};

export default App;

Here, we've added a new state variable imageURI, which will contain the URI of the selected image. In the handleChooseImage function, we set the imageURI state variable to the uri property of the selected image if it exists.

Next, we've added a conditional statement to render the Image component only if imageURI is not an empty string. If imageURI contains a URI, the Image component is rendered with the source property set to the uri of the selected image.

With this modification, users can preview the selected image before uploading it to the server.

Conclusion

In , adding camera functionality to your React Native app using Image Picker can be a simple yet powerful way to enhance the user experience. By following the five steps outlined in this guide, you can easily integrate features like taking photos or selecting images from the camera roll into your app. With the help of code snippets provided, you can customize the camera feature to fit the specific needs and design of your app.

Remember to test your app thoroughly after implementing any new features, and to keep in mind the potential impact on device storage and performance. With careful planning and attention to detail, you can create an app that combines powerful functionality with a seamless and user-friendly interface. Happy coding!

Code Snippets

When adding camera functionality to your React Native app using Image Picker, having access to can make the process much smoother. Here are some to get you started:

First, you'll need to import the necessary libraries:

import React from 'react';
import { View, Button, Image, StyleSheet } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import Constants from 'expo-constants';
import * as Permissions from 'expo-permissions';

Next, you'll need to create a function that requests permission to access the user's camera and photo library:

async function getPermissionAsync() {
  if (Constants.platform.ios) {
    const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
    if (status !== 'granted') {
      alert('Sorry, we need camera roll permissions to make this work!');
    }
  }
  if (Constants.platform.android) {
    const { status } = await Permissions.askAsync(Permissions.CAMERA);
    if (status !== 'granted') {
      alert('Sorry, we need camera permissions to make this work!');
    }
  }
}

Then, you can create a function that allows the user to select an image from their camera roll or take a photo using their camera:

async function pickImage() {
  await getPermissionAsync();
  let result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.All,
    allowsEditing: true,
    aspect: [4, 3],
    quality: 1,
  });

  if (!result.cancelled) {
    setSelectedImage({ localUri: result.uri });
  }
}

async function takePhoto() {
  await getPermissionAsync();
  let result = await ImagePicker.launchCameraAsync({
    allowsEditing: true,
    aspect: [4, 3],
    quality: 1,
  });

  if (!result.cancelled) {
    setSelectedImage({ localUri: result.uri });
  }
}

And finally, you can render the button for the user to take a photo and select an image:

<View style={styles.container}>
  <Button title="Pick an image from camera roll" onPress={pickImage} />
  <Button title="Take a photo" onPress={takePhoto} />
  {selectedImage && (
    <Image
      source={{ uri: selectedImage.localUri }}
      style={styles.thumbnail}
    />
  )}
</View>

These should give you a good starting point to add camera functionality to your React Native app using Image Picker.

Throughout my career, I have held positions ranging from Associate Software Engineer to Principal Engineer and have excelled in high-pressure environments. My passion and enthusiasm for my work drive me to get things done efficiently and effectively. I have a balanced mindset towards software development and testing, with a focus on design and underlying technologies. My experience in software development spans all aspects, including requirements gathering, design, coding, testing, and infrastructure. I specialize in developing distributed systems, web services, high-volume web applications, and ensuring scalability and availability using Amazon Web Services (EC2, ELBs, autoscaling, SimpleDB, SNS, SQS). Currently, I am focused on honing my skills in algorithms, data structures, and fast prototyping to develop and implement proof of concepts. Additionally, I possess good knowledge of analytics and have experience in implementing SiteCatalyst. As an open-source contributor, I am dedicated to contributing to the community and staying up-to-date with the latest technologies and industry trends.
Posts created 2111

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top