Convert Figma logo to code with AI

react-native-image-picker logoreact-native-image-picker

:sunrise_over_mountains: A React Native module that allows you to use native UI to select media from the device library or directly from the camera.

8,564
2,095
8,564
322

Top Related Projects

iOS/Android image picker with support for camera, video, configurable compression, multiple images and cropping

CameraRoll is a react-native native module that provides access to the local camera roll or photo library.

An unified permissions API for React Native on iOS, Android and Windows.

📸 A powerful, high-performance React Native Camera library.

Quick Overview

React Native Image Picker is a popular library that provides a simple and customizable interface for selecting images and videos from the device's library or capturing them using the camera. It supports both iOS and Android platforms, offering a seamless cross-platform solution for handling media selection in React Native applications.

Pros

  • Easy integration with React Native projects
  • Supports both image and video selection/capture
  • Customizable options for media quality, size, and type
  • Actively maintained with regular updates and bug fixes

Cons

  • Some users report occasional issues with Android permissions
  • Limited advanced features compared to platform-specific solutions
  • May require additional configuration for certain edge cases
  • Documentation could be more comprehensive for complex use cases

Code Examples

  1. Basic image selection:
import {launchImageLibrary} from 'react-native-image-picker';

const selectImage = () => {
  launchImageLibrary({mediaType: 'photo'}, (response) => {
    if (response.assets) {
      console.log(response.assets[0].uri);
    }
  });
};
  1. Capturing a photo with the camera:
import {launchCamera} from 'react-native-image-picker';

const takePhoto = () => {
  launchCamera({mediaType: 'photo', saveToPhotos: true}, (response) => {
    if (response.assets) {
      console.log(response.assets[0].uri);
    }
  });
};
  1. Customizing options for video selection:
import {launchImageLibrary} from 'react-native-image-picker';

const selectVideo = () => {
  launchImageLibrary({
    mediaType: 'video',
    durationLimit: 30,
    quality: 0.7,
  }, (response) => {
    if (response.assets) {
      console.log(response.assets[0].uri);
    }
  });
};

Getting Started

  1. Install the library:

    npm install react-native-image-picker
    
  2. For iOS, add the following to your Info.plist:

    <key>NSPhotoLibraryUsageDescription</key>
    <string>$(PRODUCT_NAME) would like access to your photo library</string>
    <key>NSCameraUsageDescription</key>
    <string>$(PRODUCT_NAME) would like to use your camera</string>
    
  3. For Android, add the following permissions to your AndroidManifest.xml:

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
  4. Import and use the library in your React Native component:

    import {launchImageLibrary} from 'react-native-image-picker';
    
    // Use the library as shown in the code examples above
    

Competitor Comparisons

iOS/Android image picker with support for camera, video, configurable compression, multiple images and cropping

Pros of react-native-image-crop-picker

  • Built-in image cropping and rotation functionality
  • Supports multiple image selection
  • Allows video selection and compression

Cons of react-native-image-crop-picker

  • More complex setup process
  • Larger package size due to additional features
  • May have compatibility issues with certain React Native versions

Code Comparison

react-native-image-picker:

ImagePicker.launchCamera(options, response => {
  if (response.uri) {
    console.log('Image URI:', response.uri);
  }
});

react-native-image-crop-picker:

ImagePicker.openCamera({
  width: 300,
  height: 400,
  cropping: true,
}).then(image => {
  console.log('Image path:', image.path);
});

Both libraries provide similar functionality for capturing images, but react-native-image-crop-picker offers more options out of the box, such as cropping and specifying dimensions. However, this comes at the cost of a slightly more complex API and larger package size.

react-native-image-picker is simpler to use and has a smaller footprint, making it a good choice for basic image selection needs. On the other hand, react-native-image-crop-picker is more suitable for applications requiring advanced image manipulation features without additional libraries.

Consider your project requirements and the trade-offs between simplicity and feature set when choosing between these two libraries.

CameraRoll is a react-native native module that provides access to the local camera roll or photo library.

Pros of react-native-cameraroll

  • Focused specifically on accessing and managing the device's photo library
  • Provides more comprehensive album management features
  • Lighter weight and more specialized for photo library tasks

Cons of react-native-cameraroll

  • Limited to photo library access, doesn't include camera functionality
  • May require additional libraries for image picking or camera integration
  • Less frequently updated compared to react-native-image-picker

Code Comparison

react-native-cameraroll:

import CameraRoll from "@react-native-community/cameraroll";

CameraRoll.getPhotos({
  first: 1000,
  assetType: 'Photos',
})
.then(r => {
  this.setState({ photos: r.edges });
});

react-native-image-picker:

import ImagePicker from 'react-native-image-picker';

ImagePicker.launchImageLibrary({
  mediaType: 'photo',
  includeBase64: false,
  maxHeight: 200,
  maxWidth: 200,
}, (response) => {
  console.log(response);
});

The code examples demonstrate the primary use cases for each library. react-native-cameraroll focuses on retrieving photos from the device's library, while react-native-image-picker provides a more comprehensive solution for selecting or capturing images, including camera functionality.

An unified permissions API for React Native on iOS, Android and Windows.

Pros of react-native-permissions

  • Comprehensive permission handling for various types (camera, location, etc.)
  • Supports both iOS and Android platforms
  • Provides a unified API for checking and requesting permissions

Cons of react-native-permissions

  • Requires more setup and configuration compared to react-native-image-picker
  • May include unnecessary permissions for projects only needing image picking
  • Steeper learning curve due to its broader scope

Code Comparison

react-native-permissions:

import { check, request, PERMISSIONS, RESULTS } from 'react-native-permissions';

const checkCameraPermission = async () => {
  const result = await check(PERMISSIONS.IOS.CAMERA);
  if (result === RESULTS.GRANTED) {
    // Camera permission is granted
  }
};

react-native-image-picker:

import ImagePicker from 'react-native-image-picker';

const options = {
  title: 'Select Image',
  storageOptions: {
    skipBackup: true,
    path: 'images',
  },
};

ImagePicker.showImagePicker(options, (response) => {
  if (response.uri) {
    // Image selected
  }
});

react-native-permissions offers a more granular approach to handling various permissions, while react-native-image-picker provides a simpler, more focused solution for image selection. The choice between the two depends on the specific requirements of your project and the range of permissions needed.

📸 A powerful, high-performance React Native Camera library.

Pros of Vision Camera

  • Advanced camera features: Offers more sophisticated camera controls, including frame processors and QR code scanning
  • Performance: Utilizes native APIs for better performance and smoother camera experience
  • Extensibility: Provides a plugin system for adding custom functionalities

Cons of Vision Camera

  • Complexity: Steeper learning curve due to more advanced features and API
  • Setup: Requires more configuration and setup compared to Image Picker
  • Limited to camera: Focused solely on camera functionality, not general image picking

Code Comparison

Vision Camera:

const devices = useCameraDevices()
const device = devices.back

return (
  <Camera
    style={StyleSheet.absoluteFill}
    device={device}
    isActive={true}
  />
)

Image Picker:

ImagePicker.launchCamera(options, response => {
  if (response.didCancel) {
    console.log('User cancelled image picker');
  } else if (response.error) {
    console.log('ImagePicker Error: ', response.error);
  } else {
    const source = { uri: response.uri };
    // Use the image
  }
});

Vision Camera offers more control over the camera interface, while Image Picker provides a simpler API for quick image selection. Vision Camera is better suited for applications requiring advanced camera features, while Image Picker is ideal for basic image selection tasks.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

react-native-image-picker 🎆

A React Native module that allows you to select a photo/video from the device library or camera.

npm downloads npm package License

Installation

yarn add react-native-image-picker

New Architecture

To take advantage of the new architecture run-

iOS

RCT_NEW_ARCH_ENABLED=1 npx pod-install ios

Android

Set newArchEnabled to true inside android/gradle.properties

Pre-Fabric (AKA not using the new architecture)

npx pod-install ios

Post-install Steps

iOS

Add the appropriate keys to your Info.plist depending on your requirement:

RequirementKey
Select image/video from photosNSPhotoLibraryUsageDescription
Capture ImageNSCameraUsageDescription
Capture VideoNSCameraUsageDescription & NSMicrophoneUsageDescription

Android

No permissions required (saveToPhotos requires permission check).

Note: This library does not require Manifest.permission.CAMERA, if your app declares as using this permission in manifest then you have to obtain the permission before using launchCamera.

Targeting Android API Levels Below 30

If your app's minSdkVersion is set to below 30 and it does not already include or depend on androidx.activity:activity:1.9.+ or a newer version, you'll need to add the following line to the dependencies section of your app/build.gradle file to ensure support for the backported AndroidX Photo Picker:

dependencies {
    ...
    implementation("androidx.activity:activity:1.9.+")
    ...
}

Additionally, you may need to update your AndroidManifest.xml to trigger the installation of the backported Photo Picker. For reference, you can check the example app's configuration in example/android/app/src/main/AndroidManifest.xml and example/android/app/build.gradle.

For more details, consult the Android documentation on AndroidX Photo Picker: https://developer.android.com/training/data-storage/shared/photopicker

API Reference

Methods

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

launchCamera()

Launch camera to take photo or video.

launchCamera(options?, callback);

// You can also use as a promise without 'callback':
const result = await launchCamera(options?);

See Options for further information on options.

The callback will be called with a response object, refer to The Response Object.

launchImageLibrary

Launch gallery to pick image or video.

launchImageLibrary(options?, callback)

// You can also use as a promise without 'callback':
const result = await launchImageLibrary(options?);

See Options for further information on options.

The callback will be called with a response object, refer to The Response Object.

Options

OptioniOSAndroidWebDescription
mediaTypeOKOKOKphoto or video or mixed(launchCamera on Android does not support 'mixed'). Web only supports 'photo' for now.
restrictMimeTypesNOOKNOArray containing the mime-types allowed to be picked. Default is empty (everything).
maxWidthOKOKNOTo resize the image.
maxHeightOKOKNOTo resize the image.
videoQualityOKOKNOlow, medium, or high on iOS, low or high on Android.
durationLimitOKOKNOVideo max duration (in seconds).
qualityOKOKNO0 to 1, photos.
conversionQualityNOOKNOFor conversion from HEIC/HEIF to JPEG, 0 to 1. Default is 0.92
cameraTypeOKOKNO'back' or 'front' (May not be supported in few android devices).
includeBase64OKOKOKIf true, creates base64 string of the image (Avoid using on large image files due to performance).
includeExtraOKOKNOIf true, will include extra data which requires library permissions to be requested (i.e. exif data).
saveToPhotosOKOKNO(Boolean) Only for launchCamera, saves the image/video file captured to public photo.
selectionLimitOKOKOKSupports providing any integer value. Use 0 to allow any number of files on iOS version >= 14 & Android version >= 13. Default is 1.
presentationStyleOKNONOControls how the picker is presented. currentContext, pageSheet, fullScreen, formSheet, popover, overFullScreen, overCurrentContext. Default is currentContext.
formatAsMp4OKNONOConverts the selected video to MP4 (iOS Only).
assetRepresentationModeOKOKNOA mode that determines which representation to use if an asset contains more than one on iOS or disables HEIC/HEIF to JPEG conversion on Android if set to 'current'. Possible values: 'auto', 'current', 'compatible'. Default is 'auto'.

|

The Response Object

keyiOSAndroidWebDescription
didCancelOKOKOKtrue if the user cancelled the process
errorCodeOKOKOKCheck ErrorCode for all error codes
errorMessageOKOKOKDescription of the error, use it for debug purpose only
assetsOKOKOKArray of the selected media, refer to Asset Object

Asset Object

keyiOSAndroidWebPhoto/VideoRequires PermissionsDescription
base64OKOKOKPHOTO ONLYNOThe base64 string of the image (photos only)
uriOKOKOKBOTHNOThe file uri in app specific cache storage. Except when picking video from Android gallery where you will get read only content uri, to get file uri in this case copy the file to app specific storage using any react-native library. For web it uses the base64 as uri.
originalPathNOOKNOBOTHNOThe original file path.
widthOKOKOKBOTHNOAsset dimensions
heightOKOKOKBOTHNOAsset dimensions
fileSizeOKOKNOBOTHNOThe file size
typeOKOKNOBOTHNOThe file type
fileNameOKOKNOBOTHNOThe file name
durationOKOKNOVIDEO ONLYNOThe selected video duration in seconds
bitrate---OKNOVIDEO ONLYNOThe average bitrate (in bits/sec) of the selected video, if available. (Android only)
timestampOKOKNOBOTHYESTimestamp of the asset. Only included if 'includeExtra' is true
idOKOKNOBOTHYESlocal identifier of the photo or video. On Android, this is the same as fileName

Note on file storage

Image/video captured via camera will be stored in temporary folder allowing it to be deleted any time, so don't expect it to persist. Use saveToPhotos: true (default is false) to save the file in the public photos. saveToPhotos requires WRITE_EXTERNAL_STORAGE permission on Android 28 and below (The permission has to obtained by the App manually as the library does not handle that).

For web, this doesn't work.

ErrorCode

CodeDescription
camera_unavailableCamera not available on device
permissionPermission not satisfied
othersOther errors (check errorMessage for description)

License

MIT

NPM DownloadsLast 30 Days