@2hats/react-native-image-picker 中文文档教程

发布于 7年前 浏览 27 项目主页 更新于 3年前

React Native Image Picker npm versionnpmMIT Platform - Android and iOS Gitter chat

一个 React Native 模块,允许您使用本机 UI 从设备库或直接从相机中选择照片/视频,如下所示:

iOSAndroid

Before you open an issue

这个库开始是本机 iOS 图像选择器的基本桥梁,我想保留它那样。 因此,此处将不支持超出本机 UIImagePickerController 支持的功能。 多图像选择、对裁剪工具的更多控制以及横向支持是原生 iOS 功能中缺少的东西 - 不是我的库的问题。 如果你需要这些东西,react-native-image-crop-picker 可能是更好的选择为你。

Table of contents

Install

NOTE: THIS PACKAGE IS NOW BUILT FOR REACT NATIVE 0.40 OR GREATER! IF YOU NEED TO SUPPORT REACT NATIVE < 0.40, YOU SHOULD INSTALL THIS PACKAGE @0.24

npm install react-native-image-picker@latest --save

Automatic Installation

react-native link

重要说明:对于 iOS,您仍然需要执行第 4 步和第 2 步, 3、5 for Android 的手册说明如下。

Manual Installation

iOS

  1. In the XCode's "Project navigator", right click on your project's Libraries folder ➜ Add Files to <...>
  2. Go to node_modulesreact-native-image-pickerios ➜ select RNImagePicker.xcodeproj
  3. Add RNImagePicker.a to Build Phases -> Link Binary With Libraries
  4. For iOS 10+, Add the NSPhotoLibraryUsageDescription, NSCameraUsageDescription, and NSMicrophoneUsageDescription (if allowing video) keys to your Info.plist with strings describing why your app needs these permissions. Note: You will get a SIGABRT crash if you don't complete this step
  5. Compile and have fun

Android

  1. 将以下行添加到 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')
    
  2. android/build.gradle 中将 android 构建工具版本更新为 2.2.+

    buildscript {
        ...
        dependencies {
            classpath 'com.android.tools.build:gradle:2.2.+' // <- USE 2.2.+ version
        }
        ...
    }
    ...
    
  3. 更新android/gradle/wrapper/gradle-wrapper.properties 中的 gradle 版本为 2.14.1

    ...
    distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
    
  4. 将编译行添加到 android/app/build 中的依赖 项.gradle

    dependencies {
        compile project(':react-native-image-picker')
    }
    
  5. AndroidManifest.xml中添加需要的权限:

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
  6. 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)
            );
        }
    }
    
Android (Optional)

对话框的自定义设置android /app/res/values/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="DefaultExplainingPermissionsTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
        <!-- Used for the buttons -->
        <item name="colorAccent">@color/your_color</item>

        <!-- Used for the title and text -->
        <item name="android:textColorPrimary">@color/your_color</item>

        <!-- Used for the background -->
        <item name="android:background">@color/your_color</item>
    </style>
<resources>

如果 MainActivity 不是 ReactActivity 的实例,则需要实现 OnImagePickerPermissionsCallback to MainActivity

import com.imagepicker.permissions.OnImagePickerPermissionsCallback; // <- add this import
import com.facebook.react.modules.core.PermissionListener; // <- add this import

public class MainActivity extends YourActivity implements OnImagePickerPermissionsCallback {
  private PermissionListener listener; // <- add this attribute

  // Your methods here

  // Copy from here

  @Override
  public void setPermissionListener(PermissionListener listener)
  {
    this.listener = listener;
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
  {
    if (listener != null)
    {
      listener.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  }

  // To here
}

此代码允许将请求权限的结果传递给本机部分。

Usage

var ImagePicker = require('react-native-image-picker');

// More info on all the options is below in the README...just some common use cases shown here
var options = {
  title: 'Select Avatar',
  customButtons: [
    {name: 'fb', title: 'Choose Photo from Facebook'},
  ],
  storageOptions: {
    skipBackup: true,
    path: 'images'
  }
};

/**
 * 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)
 */
ImagePicker.showImagePicker(options, (response) => {
  console.log('Response = ', response);

  if (response.didCancel) {
    console.log('User cancelled image 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({
      avatarSource: source
    });
  }
});

稍后,如果您想在 render() 方法中显示此图像:

<Image source={this.state.avatarSource} style={styles.uploadAvatar} />

Directly Launching the Camera or Image Library

要直接启动相机或图像库(跳过警报对话框),您可以 执行以下操作:

// Launch Camera:
ImagePicker.launchCamera(options, (response)  => {
  // Same code as in above section!
});

// Open Image Library:
ImagePicker.launchImageLibrary(options, (response)  => {
  // Same code as in above section!
});

Note

在 iOS 上,不要假设返回的绝对 uri 会持续存在。 参见#107

Options

optioniOSAndroidInfo
titleOKOKSpecify null or empty string to remove the title
cancelButtonTitleOKOKSpecify null or empty string to remove this button (Android only)
takePhotoButtonTitleOKOKSpecify null or empty string to remove this button
chooseFromLibraryButtonTitleOKOKSpecify null or empty string to remove this button
customButtonsOKOKAn array containing objects with the name and title of buttons
cameraTypeOK-'front' or 'back'
mediaTypeOKOK'photo', 'video', or 'mixed' on iOS, 'photo' or 'video' on Android
maxWidthOKOKPhotos only
maxHeightOKOKPhotos only
qualityOKOK0 to 1, photos only
videoQualityOKOK'low', 'medium', or 'high' on iOS, 'low' or 'high' on Android
durationLimitOKOKMax video recording time, in seconds
rotation-OKPhotos only, 0 to 360 degrees of rotation
allowsEditingOK-bool - enables built in iOS functionality to resize the image after selection
noDataOKOKIf true, disables the base64 data field from being generated (greatly improves performance on large photos)
storageOptionsOKOKIf this key is provided, the image will be saved in your app's Documents directory on iOS, or your app's Pictures directory on Android (rather than a temporary directory)
storageOptions.skipBackupOK-If true, the photo will NOT be backed up to iCloud
storageOptions.pathOK-If set, will save the image at Documents/[path]/ rather than the root Documents
storageOptions.cameraRollOKOKIf true, the cropped photo will be saved to the iOS Camera Roll or Android DCIM folder.
storageOptions.waitUntilSavedOK-If true, will delay the response callback until after the photo/video was saved to the Camera Roll. If the photo or video was just taken, then the file name and timestamp fields are only provided in the response object when this is true.
permissionDenied.title-OKTitle of explaining permissions dialog. By default Permission denied.
permissionDenied.text-OKMessage of explaining permissions dialog. By default To be able to take pictures with your camera and choose images from your library..
permissionDenied.reTryTitle-OKTitle of re-try button. By default re-try
permissionDenied.okTitle-OKTitle of ok button. By default I'm sure

The Response Object

keyiOSAndroidDescription
didCancelOKOKInforms you if the user cancelled the process
errorOKOKContains an error message, if there is one
customButtonOKOKIf the user tapped one of your custom buttons, contains the name of it
dataOKOKThe base64 encoded image data (photos only)
uriOKOKThe uri to the local file asset on the device (photo or video)
origURLOK-The URL of the original asset in photo library, if it exists
isVerticalOKOKWill be true if the image is vertically oriented
widthOKOKImage dimensions
heightOKOKImage dimensions
fileSizeOKOKThe file size (photos only)
type-OKThe file type (photos only)
fileNameOK (photos and videos)OK (photos)The file name
path-OKThe file path
latitudeOKOKLatitude metadata, if available
longitudeOKOKLongitude metadata, if available
timestampOKOKTimestamp metadata, if available, in ISO8601 UTC format
originalRotation-OKRotation degrees (photos only) See #109

React Native Image Picker npm versionnpmMIT Platform - Android and iOS Gitter chat

A React Native module that allows you to use native UI to select a photo/video from the device library or directly from the camera, like so:

iOSAndroid

Before you open an issue

This library started as a basic bridge of the native iOS image picker, and I want to keep it that way. As such, functionality beyond what the native UIImagePickerController supports will not be supported here. Multiple image selection, more control over the crop tool, and landscape support are things missing from the native iOS functionality - not issues with my library. If you need these things, react-native-image-crop-picker might be a better choice for you.

Table of contents

Install

NOTE: THIS PACKAGE IS NOW BUILT FOR REACT NATIVE 0.40 OR GREATER! IF YOU NEED TO SUPPORT REACT NATIVE < 0.40, YOU SHOULD INSTALL THIS PACKAGE @0.24

npm install react-native-image-picker@latest --save

Automatic Installation

react-native link

IMPORTANT NOTE: You'll still need to perform step 4 for iOS and steps 2, 3, and 5 for Android of the manual instructions below.

Manual Installation

iOS

  1. In the XCode's "Project navigator", right click on your project's Libraries folder ➜ Add Files to <...>
  2. Go to node_modulesreact-native-image-pickerios ➜ select RNImagePicker.xcodeproj
  3. Add RNImagePicker.a to Build Phases -> Link Binary With Libraries
  4. For iOS 10+, Add the NSPhotoLibraryUsageDescription, NSCameraUsageDescription, and NSMicrophoneUsageDescription (if allowing video) keys to your Info.plist with strings describing why your app needs these permissions. Note: You will get a SIGABRT crash if you don't complete this step
  5. Compile and have fun

Android

  1. 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')
    
  2. 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
        }
        ...
    }
    ...
    
  3. 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
    
  4. Add the compile line to the dependencies in android/app/build.gradle:

    dependencies {
        compile project(':react-native-image-picker')
    }
    
  5. Add the required permissions in AndroidManifest.xml:

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
  6. 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)
            );
        }
    }
    
Android (Optional)

Customization settings of dialog android/app/res/values/themes.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="DefaultExplainingPermissionsTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
        <!-- Used for the buttons -->
        <item name="colorAccent">@color/your_color</item>

        <!-- Used for the title and text -->
        <item name="android:textColorPrimary">@color/your_color</item>

        <!-- Used for the background -->
        <item name="android:background">@color/your_color</item>
    </style>
<resources>

If MainActivity is not instance of ReactActivity, you will need to implement OnImagePickerPermissionsCallback to MainActivity:

import com.imagepicker.permissions.OnImagePickerPermissionsCallback; // <- add this import
import com.facebook.react.modules.core.PermissionListener; // <- add this import

public class MainActivity extends YourActivity implements OnImagePickerPermissionsCallback {
  private PermissionListener listener; // <- add this attribute

  // Your methods here

  // Copy from here

  @Override
  public void setPermissionListener(PermissionListener listener)
  {
    this.listener = listener;
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
  {
    if (listener != null)
    {
      listener.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  }

  // To here
}

This code allows to pass result of request permissions to native part.

Usage

var ImagePicker = require('react-native-image-picker');

// More info on all the options is below in the README...just some common use cases shown here
var options = {
  title: 'Select Avatar',
  customButtons: [
    {name: 'fb', title: 'Choose Photo from Facebook'},
  ],
  storageOptions: {
    skipBackup: true,
    path: 'images'
  }
};

/**
 * 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)
 */
ImagePicker.showImagePicker(options, (response) => {
  console.log('Response = ', response);

  if (response.didCancel) {
    console.log('User cancelled image 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({
      avatarSource: source
    });
  }
});

Then later, if you want to display this image in your render() method:

<Image source={this.state.avatarSource} style={styles.uploadAvatar} />

Directly Launching the Camera or Image Library

To Launch the Camera or Image Library directly (skipping the alert dialog) you can do the following:

// Launch Camera:
ImagePicker.launchCamera(options, (response)  => {
  // Same code as in above section!
});

// Open Image Library:
ImagePicker.launchImageLibrary(options, (response)  => {
  // Same code as in above section!
});

Note

On iOS, don't assume that the absolute uri returned will persist. See #107

Options

optioniOSAndroidInfo
titleOKOKSpecify null or empty string to remove the title
cancelButtonTitleOKOKSpecify null or empty string to remove this button (Android only)
takePhotoButtonTitleOKOKSpecify null or empty string to remove this button
chooseFromLibraryButtonTitleOKOKSpecify null or empty string to remove this button
customButtonsOKOKAn array containing objects with the name and title of buttons
cameraTypeOK-'front' or 'back'
mediaTypeOKOK'photo', 'video', or 'mixed' on iOS, 'photo' or 'video' on Android
maxWidthOKOKPhotos only
maxHeightOKOKPhotos only
qualityOKOK0 to 1, photos only
videoQualityOKOK'low', 'medium', or 'high' on iOS, 'low' or 'high' on Android
durationLimitOKOKMax video recording time, in seconds
rotation-OKPhotos only, 0 to 360 degrees of rotation
allowsEditingOK-bool - enables built in iOS functionality to resize the image after selection
noDataOKOKIf true, disables the base64 data field from being generated (greatly improves performance on large photos)
storageOptionsOKOKIf this key is provided, the image will be saved in your app's Documents directory on iOS, or your app's Pictures directory on Android (rather than a temporary directory)
storageOptions.skipBackupOK-If true, the photo will NOT be backed up to iCloud
storageOptions.pathOK-If set, will save the image at Documents/[path]/ rather than the root Documents
storageOptions.cameraRollOKOKIf true, the cropped photo will be saved to the iOS Camera Roll or Android DCIM folder.
storageOptions.waitUntilSavedOK-If true, will delay the response callback until after the photo/video was saved to the Camera Roll. If the photo or video was just taken, then the file name and timestamp fields are only provided in the response object when this is true.
permissionDenied.title-OKTitle of explaining permissions dialog. By default Permission denied.
permissionDenied.text-OKMessage of explaining permissions dialog. By default To be able to take pictures with your camera and choose images from your library..
permissionDenied.reTryTitle-OKTitle of re-try button. By default re-try
permissionDenied.okTitle-OKTitle of ok button. By default I'm sure

The Response Object

keyiOSAndroidDescription
didCancelOKOKInforms you if the user cancelled the process
errorOKOKContains an error message, if there is one
customButtonOKOKIf the user tapped one of your custom buttons, contains the name of it
dataOKOKThe base64 encoded image data (photos only)
uriOKOKThe uri to the local file asset on the device (photo or video)
origURLOK-The URL of the original asset in photo library, if it exists
isVerticalOKOKWill be true if the image is vertically oriented
widthOKOKImage dimensions
heightOKOKImage dimensions
fileSizeOKOKThe file size (photos only)
type-OKThe file type (photos only)
fileNameOK (photos and videos)OK (photos)The file name
path-OKThe file path
latitudeOKOKLatitude metadata, if available
longitudeOKOKLongitude metadata, if available
timestampOKOKTimestamp metadata, if available, in ISO8601 UTC format
originalRotation-OKRotation degrees (photos only) See #109
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文