# 📸 React Native: Select and Save Media from Gallery or Camera

In mobile applications, users often need to select photos and videos from the gallery or capture new ones using the camera and save them. In **React Native** projects, we can use the **react-native-image-picker** and **react-native-camera-roll** libraries to accomplish this.

In this guide, we will cover:
✅ Selecting a photo or video from the gallery  
✅ Capturing a photo using the camera  
✅ Saving the captured photo to the gallery  

## 📌 1. Installing Required Libraries

First, let's install the necessary libraries:

```bash
npm install react-native-image-picker react-native-camera-roll
# or
yarn add react-native-image-picker react-native-camera-roll
```

📢 **For iOS:** Install CocoaPods dependencies:

```bash
cd ios && pod install && cd ..
```

## 📜 2. Configuring Permissions

We need to add permissions to access the camera and gallery.

### **Android Permissions**

Add the following lines to your `android/app/src/main/AndroidManifest.xml` file:

```xml
<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"/>
```

Additionally, for **Android 10 (API 29)** and above, add the following line for **scoped storage** access:

```xml
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION"/>
```

### **iOS Permissions**

Add the following permissions to your `Info.plist` file:

```xml
<key>NSPhotoLibraryUsageDescription</key>
<string>Permission is required to save photos to the gallery.</string>
<key>NSCameraUsageDescription</key>
<string>Permission is required to use the camera.</string>
<key>NSMicrophoneUsageDescription</key>
<string>Permission is required to record audio for videos.</string>
```

## 🎯 3. Selecting a Photo or Video from the Gallery

Use the following function to allow the user to select media from the gallery:

```javascript
import React, { useState } from 'react';
import { View, Button, Image, Text } from 'react-native';
import { launchImageLibrary } from 'react-native-image-picker';

const App = () => {
  const [media, setMedia] = useState(null);

  const selectMedia = () => {
    const options = {
      mediaType: 'mixed', // Change to 'photo' or 'video' as needed
      quality: 1,
      selectionLimit: 1,
    };

    launchImageLibrary(options, response => {
      if (response.didCancel) {
        console.log('User canceled selection');
      } else if (response.errorMessage) {
        console.log('Error:', response.errorMessage);
      } else {
        setMedia(response.assets[0]);
      }
    });
  };

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="Select from Gallery" onPress={selectMedia} />
      {media && (
        media.type.startsWith('image') ? (
          <Image source={{ uri: media.uri }} style={{ width: 200, height: 200, marginTop: 10 }} />
        ) : (
          <Text style={{ marginTop: 10 }}>Selected video: {media.fileName}</Text>
        )
      )}
    </View>
  );
};

export default App;
```

---

## 📷 4. Capturing a Photo and Saving It to the Gallery

Now, let's add steps to open the camera, take a photo, and save it to the gallery.

### **📸 Capturing a Photo**

Use **react-native-image-picker** to open the camera:

```javascript
import { launchCamera } from 'react-native-image-picker';
import { PermissionsAndroid, Platform } from 'react-native';
import CameraRoll from '@react-native-camera-roll/camera-roll';

const openCamera = async () => {
  const options = {
    mediaType: 'photo',
    quality: 1,
  };

  launchCamera(options, async response => {
    if (response.didCancel) {
      console.log('User canceled the camera');
    } else if (response.errorMessage) {
      console.log('Error:', response.errorMessage);
    } else {
      const photoUri = response.assets[0].uri;
      console.log('Captured photo:', photoUri);
      await savePhotoToGallery(photoUri);
    }
  });
};
```

### **💾 Saving the Captured Photo to the Gallery**

Use **react-native-camera-roll** to save the photo to the gallery:

```javascript
const savePhotoToGallery = async (uri) => {
  if (Platform.OS === 'android') {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
    );

    if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
      console.log('Permission to save to gallery was denied.');
      return;
    }
  }

  try {
    await CameraRoll.save(uri, { type: 'photo' });
    console.log('Photo saved successfully!');
  } catch (error) {
    console.log('Failed to save photo:', error);
  }
};
```

---

## 🎥 5. Complete App Code

Below is the full application code that includes both **selecting media from the gallery** and **capturing and saving a photo**:

```javascript
import React, { useState } from 'react';
import { View, Button, Image, Text, PermissionsAndroid, Platform } from 'react-native';
import { launchImageLibrary, launchCamera } from 'react-native-image-picker';
import CameraRoll from '@react-native-camera-roll/camera-roll';

const App = () => {
  const [media, setMedia] = useState(null);

  const selectMedia = () => {
    launchImageLibrary({ mediaType: 'mixed', quality: 1 }, response => {
      if (!response.didCancel && !response.errorMessage) {
        setMedia(response.assets[0]);
      }
    });
  };

  const takePhoto = async () => {
    launchCamera({ mediaType: 'photo', quality: 1 }, async response => {
      if (!response.didCancel && !response.errorMessage) {
        const photoUri = response.assets[0].uri;
        setMedia(response.assets[0]);
        await savePhotoToGallery(photoUri);
      }
    });
  };

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="Select from Gallery" onPress={selectMedia} />
      <Button title="Take Photo" onPress={takePhoto} />
      {media && <Image source={{ uri: media.uri }} style={{ width: 200, height: 200, marginTop: 10 }} />}
    </View>
  );
};

export default App;
```

🚀 Now, you can select media from the gallery and save captured photos to the phone's gallery!


