How to use React Native image picker

React Native image picker simplifies the process of integrating image selection functionality into React Native applications. By using React Native image picker, we can enable users to choose and utilize images from their gallery or directly capture them using the camera.

Here are the steps to implement an image picker in React Native:

Step 1: Install react-native-image-picker

Open the terminal and navigate to your project directory. Then, run the following command to install react-native-image-picker:

npm install react-native-image-picker //using npm
//OR
yarn add react-native-image-picker //using yarn

For iOS, you also need to install pods in the iOS directory and then return to the root project directory. You can do this using the following commands:

cd ios
pod install
cd ..

Step 2: Configure permissions

To access the device's camera and photo library, we need to configure the required permissions. Add permissions for each platform:

Android

Open the AndroidManifest.xml file from the android/app/src/main directory of your project. Add the following line inside the <manifest> tag:

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

iOS

Open the Info.plist from the ios/yourProjectName directory and add the following lines in dict tag:

<key>NSPhotoLibraryUsageDescription</key>
<string>Allow access to the photo library for selecting images</string>

Step 4: Implement gallery image picker

To implement a gallery image picker, we need to import the required function. Open the JavaScript file in which you want to implement the image picker and add the following import statement:

import {launchImageLibrary} from 'react-native-image-picker';

Next, create a function that will handle image selection. We will use the launchImageLibrary function that we just imported. The launchImageLibrary takes two parameters:

  • options: An object that specifies the options for the image picker. Some commonly used options include:

    • mediaType (string): Specifies the media type to pick. Use 'photo' for images.

    • includeBase64 (boolean): Determines whether to include the base64 representation of the selected image in the response. Set it to false if you do not need the base64 data.

    • maxHeight (number): Specifies the maximum height of the selected image.

    • maxWidth (number): Specifies the maximum width of the selected image.

  • callback: A callback function that will be invoked with the response from the image picker. It takes a single parameter, response, which contains information about the selected image. The response object may have the following properties:

    • didCancel (boolean): Indicates whether the user canceled the image picker.

    • error (string): If an error occurs during the image picking process, this property will contain the error message.

    • uri (string): The URIUniform Resource Identifier of the selected image.

    • assets (array): An array of assets representing the selected images. Each asset may contain additional properties such as uri, width, height, etc.

Here’s an example:

const openImagePicker = () => {
const options = {
mediaType: 'photo',
includeBase64: false,
maxHeight: 2000,
maxWidth: 2000,
};
launchImageLibrary(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('Image picker error: ', response.error);
} else {
let imageUri = response.uri || response.assets?.[0]?.uri;
setSelectedImage(imageUri);
}
});
};

In the code above, we define a function openImagePicker that opens the gallery image picker when called.

We set some options for the image picker, such as mediaType for photos, includeBase64 set to false, and maximum height and width set to 2000 pixels.

We call the launchImageLibrary function with the provided options and a callback function. Inside the callback, we handle different scenarios:

  • if the user cancels the image picker

  • if there's an error

  • if an image is successfully selected

If an image is selected, we extract the image URI and update the selectedImage state variable.

Step 5: Implement camera image picker

To implement a camera image picker, we need to import the required function. Open the JavaScript file in which you want to implement the image picker and add the following import statement:

import {launchCamera} from 'react-native-image-picker';

Next, create a function that will handle image selection using the launchCamera. The launchCamera function is used to open the camera on a device, allowing users to capture photos or videos.

It is similar to the launchImageLibrary function, which opens the image gallery instead. It also uses the same two parameters:

  • options: Configuration settings

  • callback: Response handling function

Here’s an example:

handleCameraLaunch = () => {
const options = {
mediaType: 'photo',
includeBase64: false,
maxHeight: 2000,
maxWidth: 2000,
};
launchCamera(options, response => {
if (response.didCancel) {
console.log('User cancelled camera');
} else if (response.error) {
console.log('Camera Error: ', response.error);
} else {
let imageUri = response.uri || response.assets?.[0]?.uri;
setSelectedImage(imageUri);
console.log(imageUri);
}
});
}

The function above starts by declaring an object called options, which contains various configuration settings for launching the camera. These settings include:

  • mediaType: Specifies that the camera should capture a photo.

  • includeBase64: Indicates whether the resulting image should be encoded in base64 format or not. In this case, it is set to false, so the image will not be encoded as base64.

  • maxHeight and maxWidth: Specify the maximum height and width of the captured image, respectively. The values are set to 2000 pixels each.

The function then calls the launchCamera() function with the provided options and a callback function. Inside the callback, we handle different scenarios:

  • if the user cancels the image picker

  • if there's an error

  • if an image is successfully selected

If an image is selected, we extract the image URI and update the selectedImage state variable.

Step 6: Trigger the image picker

To trigger the image picker, we need to call the handler functions just created. We can do this by attaching it to a button's onPress event or any other user interaction in your app’s UI. Here’s an example using a button:

<Button title="Choose from Device" onPress={openImagePicker} />
<Button title="Open Camera" onPress={handleCameraLaunch} />

When the user taps the button, the respective image picker will open, allowing them to choose an image from the photo library or take a new photo with the camera.

Example app

Here is an example React Native app that allows users to pick an image from the gallery or directly capture using a camera:

const { getDefaultConfig } = require('metro-config');

module.exports = (async () => {
  const defaultConfig = await getDefaultConfig();
  return {
    ...defaultConfig,
    resolver: {
      ...defaultConfig.resolver,
      sourceExts: [...defaultConfig.resolver.sourceExts, 'web.js', 'web.ts', 'web.tsx'],
    },
  };
})();
Complete App

Here is what the app looks like:

Note: If you want to also crop the image, you can use image crop picker.

Copyright ©2024 Educative, Inc. All rights reserved