Selecting image from mobile phone gallery and capture image from camera is very typical for beginners in react native. But now we would do this type of functionality in our react native application using an external library called as React Native Image Picker library. This library supports all type of react native versions and also comes with both android and iOS full application support. So in this tutorial we would going to create a react native application that pick image from mobile phone gallery and select image from mobile phone camera and after selecting show that image inside Image component.
What we are doing in current project – Must Read 😛 :
- Selecting Image from both Android and iOS mobile phone gallery.
- Capturing image from both Android and iOS device camera.
- Show captured image inside Image component.
- Show selected image from gallery inside Image component.
Important Note : You must follow all the steps exactly as i did in this tutorial, So don’t skip any step and read the full tutorial. Happy Reading 🙂 .
Contents in this project React Native Pick Image From Camera and Gallery Tutorial :
1. Start a fresh React Native project. If you don’t know how then read my this tutorial.
2. After creating project Start Command Prompt in your system using Run As Administrator .
3. Now using command prompt locate your project’s folder .
4. Type npm install react-native-image-picker@latest --save inside your project like i did in below screenshot.
5. After successfully installed the React Native Image Picker library you would see message like below screenshot.
6. After installing the library type
react-native link command inside your project’s folder. This command would refresh the complete project folder. This command is very important .
7. Screenshot after running react-native link command.
8. Configure Project for Android Devices :
1. Open build.gradle file present in your folder located in YourProject/android .
2. Replace classpath ‘com.android.tools.build:gradle:2.2.+’ on previous line.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.2.+' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { mavenLocal() jcenter() maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url "$rootDir/../node_modules/react-native/android" } } } |
3. Now open YourProjectName/android/gradle/wrapper/gradle-wrapper.properties file and replace previous distributionUrl line to this distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip .Below is the complete source code of gradle-wrapper.properties file.
1 2 3 4 5 |
distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip |
4. Open AndroidManifest.xml file present inside YourProjectName\android\app\src\main and Add CAMERA permission and WRITE_EXTERNAL_STORAGE permission.
1 2 |
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> |
5. Complete source code of AndroidManifest.xml file after adding both permissions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.imagepickerproject" android:versionCode="1" android:versionName="1.0"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="22" /> <application android:name=".MainApplication" android:allowBackup="true" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenSize" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" /> </application> </manifest> |
9. Configure Project for iOS device :
1. Open ImagePickerProject.xcodeproj file in Xcode in MAC.
2. Open Info.plist file in Xcode.
3. Click on small plus icon present just above the Information Property List .
4. Select Privacy – Camera Usages Description permission like i did in below screenshot.
6. Again Select Privacy – Photo Library Usages permission .
7. Now front of both permissions double click and Add some text like i did, So you remember why this permisson is added.
Here you go now your application is successfully configured for iOS devices. Now its time to start coding .
10. Start Coding :
1. Import AppRegistry, StyleSheet, Text, View, PixelRatio, TouchableOpacity, Image component.
1 2 3 4 5 6 7 8 9 10 |
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, PixelRatio, TouchableOpacity, Image, } from 'react-native'; |
2. Import ImagePicker library.
1 |
import ImagePicker from 'react-native-image-picker'; |
3. Create State inside your mail class and inside that state create variable named as ImageSource = null .
The ImageSource variable is used to store the selected image URI path.
1 2 3 4 5 6 7 8 9 |
class ImagePickerProject extends React.Component { state = { ImageSource: null, }; } |
4. Create function selectPhotoTapped() . This is a inbuilt function of this library.
1 2 3 4 5 6 7 8 9 |
selectPhotoTapped() { const options = { quality: 1.0, maxWidth: 500, maxHeight: 500, storageOptions: { skipBackup: true } }; |
5. Now before ending selectPhotoTapped() function create another function inside its scope named as ImagePicker.showImagePicker() . This is also inbuilt function of React Native Image Picker Library.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
selectPhotoTapped() { const options = { quality: 1.0, maxWidth: 500, maxHeight: 500, storageOptions: { skipBackup: true } }; ImagePicker.showImagePicker(options, (response) => { console.log('Response = ', response); if (response.didCancel) { console.log('User cancelled photo picker'); } else if (response.error) { console.log('ImagePicker Error: ', response.error); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); } else { let source = { uri: response.uri }; // You can also display the image using data: // let source = { uri: 'data:image/jpeg;base64,' + response.data }; this.setState({ ImageSource: source }); } }); } |
6. Create a Parent View inside the render’s return block.
1 2 3 4 5 6 7 8 9 |
render() { return ( <View style={styles.container}> </View> ); } |
7. Now inside the Parent View component create TouchableOpacity and call the selectPhotoTapped() function on its onPress.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
render() { return ( <View style={styles.container}> <TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}> </TouchableOpacity> </View> ); } |
8. Now Create a Sub View inside TouchableOpacity now using ? ( Ternary Operator ) Set condition that If ImageSource variable === null then it will show a Text component inside the TouchableOpacity or if There is Image Selected( ImageSource variable is full) then it will show the selected image inside the Image component.
1 2 3 4 5 6 7 8 9 10 11 |
<TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}> <View style={styles.ImageContainer}> { this.state.ImageSource === null ? <Text>Select a Photo</Text> : <Image style={styles.ImageContainer} source={this.state.ImageSource} /> } </View> </TouchableOpacity> |
9. Create Custom CSS Style sheet.
container : for Parent View.
ImageContainer : for Image Component ( In which the Selected or Captured Image will be displayed. ).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#FFF8E1' }, ImageContainer: { borderRadius: 10, width: 250, height: 250, borderColor: '#9B9B9B', borderWidth: 1 / PixelRatio.get(), justifyContent: 'center', alignItems: 'center', backgroundColor: '#CDDC39', }, }); |
10. Complete source code for index.android.js / index.ios.js file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, PixelRatio, TouchableOpacity, Image, } from 'react-native'; import ImagePicker from 'react-native-image-picker'; class ImagePickerProject extends React.Component { state = { ImageSource: null, }; selectPhotoTapped() { const options = { quality: 1.0, maxWidth: 500, maxHeight: 500, storageOptions: { skipBackup: true } }; ImagePicker.showImagePicker(options, (response) => { console.log('Response = ', response); if (response.didCancel) { console.log('User cancelled photo picker'); } else if (response.error) { console.log('ImagePicker Error: ', response.error); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); } else { let source = { uri: response.uri }; // You can also display the image using data: // let source = { uri: 'data:image/jpeg;base64,' + response.data }; this.setState({ ImageSource: source }); } }); } render() { return ( <View style={styles.container}> <TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}> <View style={styles.ImageContainer}> { this.state.ImageSource === null ? <Text>Select a Photo</Text> : <Image style={styles.ImageContainer} source={this.state.ImageSource} /> } </View> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#FFF8E1' }, ImageContainer: { borderRadius: 10, width: 250, height: 250, borderColor: '#9B9B9B', borderWidth: 1 / PixelRatio.get(), justifyContent: 'center', alignItems: 'center', backgroundColor: '#CDDC39', }, }); AppRegistry.registerComponent('ImagePickerProject', () => ImagePickerProject); |
Screenshots in iOS device :
Screenshots in Android Device :
Important Note : In iOS simulator camera will not be worked, because iOS simulator dose not support camera so you need a real iOS mobile phone device to Test camera.
Fantastic tutorial. Good job.
Thanks Dave 🙂
undefined is not an object (evaluating ‘ImagePickerManager.showImagePicker’)
Getting this error
Lakshya please install the library again .
Dear Lakshya, I think you missed this command ‘react-native link’ to run from terminal . After installing : ‘npm install [email protected] –save’, you must have to run the command ‘react-native link’.
undefined is not an object (evaluating ‘ImagePickerManager.showImagePicker’)
Getting this error . ….. got same isuue me as well …. what you did exactly to solve this
Try to reinstall the library .
I have to do Manual Installation to solve this.
https://github.com/react-community/react-native-image-picker
I’ve same problem any solution ??
I’ve android emulator
Nice tutorial. Wonderful explanation. Thanks….
Welcome Anup 🙂 .
Nice tutorial. Thanks
Welcome Shivam 🙂 .
Love it! 😀
Welcome Rishabh 🙂 .
how to save the image taken with camera in different location?
Ramesh currently i have not tried yet this type of functionality .
Thank you
It works pretty well with the Android Emulator and also on the device.
Welcome bro 🙂 .
Great tutorial ! Helped me a lot !! Thanks!!! 🙂
Welcome Saravanan 🙂 .
i Got like
error: cannot find symbol
new ImagePickerPackage(),
^
symbol: class ImagePickerPackage
2 errors
Incremental compilation of 1 classes completed in 5.908 secs.
:app:compileDebugJavaWithJavac FAILED
George try to install the library again .
thanks … i missed compile project(‘:react-native-image-picker’) in android/App/build.gradle
Welcome George 🙂 .
A great, simple document, thank you very much. I could run camera functionality with your explanations after struggling two whole days.
One more question, how can I enable to retrieve only last n images instead of whole images from a phone?
Thanks & regards,
Huseyin
Welcome Huseyin 🙂 , what do you mean by ‘how can I enable to retrieve only last n images instead of whole images from a phone?’ please explain your question more briefly .
Thank you.
I want to show only latest 3-4 images from the library after taking a photo.
Thanks & regards
Sorry bro, i don’t know .
undefined is not an object (evaluating ‘ImagePickerManager.showImagePicker’)
Vishal try to re-install the library again and make sure you have execute the link command after done installation.
Sir this tutorial is for ios only??????????
No, Sanjeep this tutorial works on both Android and iOS devices.
alert show but take photo and choose from library not working
Trying to re-install the library Himanshu and make sure after install you’ll run react-native link command.
Without pressing any button can image capture with 3 sec countdown timer and after that move to next page??
Without pressing any button can image capture with 3 sec countdown timer and after that move to next page????
Sorry swati we haven’t tried that yet .
how can i captured multiple picture and add into list or in pager
Sorry dharma i have not tried yet this .
Helo Sir
Can you help me,
how to use realm database to store employee first name ,last name ,id and image through react native
and also fetch and show the data of employee in screen
Swati currently we do not how how to save image locally in mobile phone but you can store image URL if your image is online. read our this tutorial this would help you https://reactnativecode.com/insert-data-into-realm-local-database/
How can I save the address in the database?
Address of selected image ?
I want to save the photo taken in php my admin
Saying I have to save the photo’s address
How can i do this
Bahar this.state.ImageSource contain the image URL you can use it to save but if you want to download image or upload image to server than sorry bro.
I am getting 500 (internal server error) Sir.
Johncy please follow all the steps , it will work .
Great Sir..Really Thank you very much.I want to follow all your articles..Please tell me where can i find related topics for React Native.
Sorry problem was in my system environment..It does not tracked my changes.
Ok Johncy 🙂 .
Hi there,
on IOS devices when I try to take a photo the response.uri and response.fileName is undefined. although everything is fine on Android and when getting image from Gallery on IOS. my question is how could I get the uri when taking photo on IOS?
ImagePicker.showImagePicker(options, (data) => {console.log(data.fileName})
Great Tutorial Admin Bro…
Works pretty well on Android Emulator…
Thanks.
Welcome bro 🙂 .
Once again very well explained tutorial….
Thanks Admin.
Please make Some tutorials on GEOLOCATION.
( How to get user current location & direct them to one point to another point using google maps)
Usmaan i will soon publish a new tutorial regarding to your query but there is a problem in react native’s runtime permissions.
ok admin…..I will be waiting for it…..
Please Help….
What components in react native i need to use to achieve the following:
I have Two user “X” & “Y”
1. how to set a user call it (‘X’) location as default , while user sign-in (in their User account/profile)
2. Then how to show that user “X” location on google maps for any other user call it ( “Y”) and also
detect user “Y” current location and direct user “Y” to user “X” location by using google maps (Typical google maps with Driving directions in Android Phones)
Usmaan currently we do not work on GPS .
Hello
I used the project before this tutorial, but I can not open the gallery or Durin in this project
Click on the select a photo nothing happens
Project version before me: 0.56.0
Version is 0.55.4
Whether it’s a change of version or another reason???
Bahar try to create a new project again and install all the libraries again , this should work .
Thank you! Helped so much!
Welcome bro 🙂 .
Thanks,
This post is useful to me.
Best regards.
for your camera and gallery permission, how to set if not have mac laptop ?
Ralry you can setup android permissions using windows pc but to set iOS permissions you need MAC, but you can use MAC in your windows system with VMware with virtual windows system .
admin, android is ok for me, coz i’m android dev, i dunno ios thing.
but for ios, this one cannot add code inside info.plist ?
must use vmware/Mac ?
how to customize the default dialog in image picker???
Default image dialog means the box where images shows after selecting or the dialog box which opens after clicking on selecting button ?
Wat about camera run time permission, is it prompt to user to give access to camera and external storage permission??
Mujeeb this library would automatically calls the camera runtime permission all you have to do is tap the Yes button present on permission dialog screen.
i am getting issue undefined is not an object (evaluating ‘ImagePickerManager.showImagePicker’)
Harsh try to install the library again with administrative privileges.
when i’m install react-native image-picker library, then my project build become fail.
Waseem read my this tutorial this would help you: https://reactnativecode.com/execution-failed-for-task-processdebugresources/ .