Access Image from storage using React Native


 Access Images from storage or camera using

React Native


  In this blog, we are going to learn about image reading.

  Let's create a new React Native project called "AwesomeProject":


npx react-native init AwesomeProject




  To start the Metro server, run the below command inside your React Native project folder:


npx react-native start



  Step 1: For image read from storage of android phone or using the camera you need to install
              the following library.


npm install react-native-image-picker

 



  Step 2: Write the below code in the android manifest.xml file. These permission are required to 
              access the Camera and Storage.


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

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

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



Step 3: Open app.js and write the below code.



import React, {useState} from 'react';


import {

 StyleSheet,

 View,

 TouchableOpacity,

 Image,

 Platform,

 PermissionsAndroid,

} from 'react-native';

 

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

 

const App = () => {

 const [filePath, setFilePath] = useState({});

 

 const requestCameraPermission = async () => {

   if (Platform.OS === 'android') {

     try {

       const granted = await PermissionsAndroid.request(

         PermissionsAndroid.PERMISSIONS.CAMERA,

         {

           title: 'Camera Permission',

           message: 'App needs camera permission',

         },

       );

       // If CAMERA Permission is granted

       return granted === PermissionsAndroid.RESULTS.GRANTED;

     } catch (err) {

       console.warn(err);

       return false;

     }

   } else return true;

 };

 

 const requestExternalWritePermission = async () => {

   if (Platform.OS === 'android') {

     try {

       const granted = await PermissionsAndroid.request(

         PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,

         {

           title: 'External Storage Write Permission',

           message: 'App needs write permission',

         },

       );


       return granted === PermissionsAndroid.RESULTS.GRANTED;

     } catch (err) {

       console.warn(err);

       alert('Write permission err', err);

     }

     return false;

   } else return true;

 };

 

 const captureImage = async (type) => {

   let options = {

     mediaType: type,

     maxWidth: 300,

     maxHeight: 550,

     quality: 1,

     videoQuality: 'low',

     durationLimit: 30, //Video max duration in seconds

     saveToPhotos: true,

   };

   let isCameraPermitted = await requestCameraPermission();

   let isStoragePermitted = await requestExternalWritePermission();

   if (isCameraPermitted && isStoragePermitted) {

     launchCamera(options, (response) => {

       console.log('Response = ', response);

 

       if (response.didCancel) {

         alert('User cancelled camera picker');

         return;

       } else if (response.errorCode == 'camera_unavailable') {

         alert('Camera not available on device');

         return;

       } else if (response.errorCode == 'permission') {

         alert('Permission not satisfied');

         return;

       } else if (response.errorCode == 'others') {

         alert(response.errorMessage);

         return;

       }


       setFilePath(response);

     });

   }

 };

 

 

 return (

   <View style={styles.container}>

     {filePath.uri ? (

       <Image style={styles.avatar} source={{uri: filePath.uri}} />

     ) : (

       <TouchableOpacity

         activeOpacity={0.5}

         onPress={() => captureImage('photo')}>

         <Image

           style={styles.avatar}

           source={{

             uri: 'https://bootdey.com/img/Content/avatar/avatar6.png',

           }}

         />

       </TouchableOpacity>

     )}

   </View>

 );

};

 

export default App;

 

const styles = StyleSheet.create({

 container: {

   flex: 1,

   padding: 10,

   backgroundColor: '#fff',

   alignItems: 'center',

 },

 titleText: {

   fontSize: 22,

   fontWeight: 'bold',

   textAlign: 'center',

   paddingVertical: 10,

 },

 textStyle: {

   padding: 10,

   color: 'black',

   textAlign: 'center',

 },

 buttonStyle: {

   alignItems: 'center',

   backgroundColor: '#DDDDDD',

   padding: 5,

   marginVertical: 10,

   width: 250,

 },

 imageStyle: {

   width: 200,

   height: 200,

   margin: 5,

 },

 avatar: {

   width: 130,

   height: 130,

   borderRadius: 63,

   borderWidth: 4,

   borderColor: 'white',

   marginBottom: 10,

 },

});

 


Step 4: Output for image read file.


First Output Screen                                                        Second Screen Output
                                       



Third Screen Output

In this way, we can read images in React Native. Keep Learning. 
All the Best :)











Comments