React Native Image Picker Example

React Native Image Picker

A React Native Image Picker library allows you select a photo/video from the device library or directly from the camera.

So in this tutorial I have create react native ImagePickerApp that picks selected image from mobile phone gallery and clicked image from mobile phone camera and displayed in Image component.

Get GITHUB code from HERE.

  • Start a new React Native project. If you don’t know how then read my this tutorial.
  • After creating project Open Command Prompt in your system .
  • Now using command prompt locate your project’s  root folder .
  • Type npm install reactnativeimagepicker@latest save  inside your project.
  • After successfully installed the React Native Image Picker library you would see message like below screenshot.

Configure Project for Android Devices :

  • Add the following lines to android/settings.gradle:
include ':react-native-image-picker'
project(':react-native-image-picker').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-image-picker/android')

 

  • Update the android build tools version to 2.2.+ in android/build.gradle:
buildscript {
    ...
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.+' // <- USE 2.2.+ version
    }
    ...
}
  • Update the gradle version to 2.14.1 in android/gradle/wrapper/gradle-wrapper.properties:
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip

 

  • Add the compile line to the dependencies in android/app/build.gradle:
dependencies {
    compile project(':react-native-image-picker')
}

 

  • Add the required permissions in AndroidManifest.xml:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 

  • Add the import and link the package in MainApplication.java:
import com.imagepicker.ImagePickerPackage; // <-- add this import

public class MainApplication extends Application implements ReactApplication {
    @Override
    protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
            new MainReactPackage(),
            new ImagePickerPackage() // <-- add this line
            // OR if you want to customize dialog style
            new ImagePickerPackage(R.style.my_dialog_style)
        );
    }
}

 

Start Coding :

  •  Import  StyleSheet, Text, View, Button,Image component.
  • Import ImagePicker library.
import ImagePicker from "react-native-image-picker";
  • Open App.Js and inside render() write the below JSX code:
render() {
  return (
    <View style={styles.container}>
    <Text style={styles.textStyle}>Pick Image From Camera and Gallery </Text>
      <View style={styles.placeholder}>
        <Image source={this.state.pickedImage} style={styles.previewImage} />
      </View>
      <View style={styles.button}>

        <Button title="Pick Image" onPress={this.pickImageHandler} />

        <Button title="Reset" onPress={this.resetHandler} />

      </View>
    </View>
  );
}
  • Create State inside your main class and inside that state create variable named as pickedImage = null .

The pickedImage variable is used to store the selected image URI path.

state = {
pickedImage : null
}
  • Inside render() I have created two buttons Pick ImageReset.

When I press Pick Image button pickImageHandler function will called and Inside pickImageHandler() I have used one built_in function

showImagePicker() .
/**
* The first arg is the options object for customization (it can also be null or omitted for default options),
* The second arg is the callback which sends object: response (more info below in README)
*/

 pickImageHandler = () => {
   ImagePicker.showImagePicker({title: "Pick an Image", maxWidth: 800, maxHeight: 600}, res => {
     if (res.didCancel) {
       console.log("User cancelled!");
     } else if (res.error) {
       console.log("Error", res.error);
     } else {
       this.setState({
         pickedImage: { uri: res.uri }
       });

     }
   });
 }

When I press Reset button resetHandler function will called and Inside resetHandler() again I set pickedImage variable defined in state

to null by calling reset().

reset = () => {
  this.setState({
    pickedImage: null
  });
}

Complete source code :

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Image,
  Button
} from 'react-native';
import ImagePicker from "react-native-image-picker";


export default class App extends Component {

  state = {
    pickedImage: null
  }

  reset = () => {
    this.setState({
      pickedImage: null
    });
  }

  /**
 * The first arg is the options object for customization (it can also be null or omitted for default options),
 * The second arg is the callback which sends object: response (more info below in README)
 */

  pickImageHandler = () => {
    ImagePicker.showImagePicker({title: "Pick an Image", maxWidth: 800, maxHeight: 600}, res => {
      if (res.didCancel) {
        console.log("User cancelled!");
      } else if (res.error) {
        console.log("Error", res.error);
      } else {
        this.setState({
          pickedImage: { uri: res.uri }
        });

      }
    });
  }

  resetHandler = () =>{
    this.reset();
  }

  render() {
    return (
      <View style={styles.container}>
      <Text style={styles.textStyle}>Pick Image From Camera and Gallery </Text>
        <View style={styles.placeholder}>
          <Image source={this.state.pickedImage} style={styles.previewImage} />
        </View>
        <View style={styles.button}>

          <Button title="Pick Image" onPress={this.pickImageHandler} />

          <Button title="Reset" onPress={this.resetHandler} />

        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    alignItems:"center"
  },
  textStyle: {
    fontWeight:"bold",
    fontSize:30,
    textAlign:"center",
    color:"red",
    marginTop:10
  },
  placeholder: {
    borderWidth: 1,
    borderColor: "black",
    backgroundColor: "#eee",
    width: "70%",
    height: 280,
    marginTop:50,
  },
  button: {
    width: "80%",
    marginTop:20,
    flexDirection:"row",
    justifyContent: "space-around"
  },
  previewImage: {
      width: "100%",
      height: "100%"
  }
});
  • Run your application:

7 thoughts on “React Native Image Picker Example”

  1. undefined is not an object(‘evaluating ‘ImagePickerManager.showImagePicker’) ->I have this problem,can you help me ?

    1. Arun Chandravanshi

      there is no option available for cropping by using library react-native-image-picker.
      To crop an image we can use library react-native-image-crop-picker like this:

      import ImagePicker from “react-native-image-crop-picker”;
      ImagePicker.openCamera({
      width: 300,
      height: 400,
      cropping: true
      }).then(image => {
      console.log(image);
      });
      For more info go to https://github.com/ivpusic/react-native-image-crop-picker.

  2. I have an issue when I setState image source to display image in view and re-render the component, my app become hangs and crashed. Do you have any solution?

Leave a Reply