ReactNative-拍照、相册选择【react-native-image-picker 2.x版本和3.x版本(最新版本)】的使用详解


 

react-native-image-picker 2.x版本和3.x版本(最新版本)的使用详解

 

一、react-native-image-picker 2.x版本的应用GitHub参考文档

  1. 安装依赖(cmd进入项目根目录执行命令)

yarn add react-native-image-picker

 #RN >= 0.60(如果你的react-native版本 > = 0.60执行以下命令)
 npx pod-install

 #RN < 0.60(如果你的react-native版本< 0.60执行以下命令)
 react-native link react-native-image-picker

  2. Android配置(如需设置IOS自行查看GitHub文档)

  • 打开项目根目录,然后进入该路径android\app\src\main找到AndroidManifest.xml,添加以下两行代码:

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

以上设置好后,可以测试是否可以使用,若不行接着做以下设置......

  • 进入项目根目录,打开android/settings.gradle文件,添加以下代码:
1 include ':react-native-image-picker'
2 project(':react-native-image-picker').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-image-picker/android')
  • 进入项目根目录,打开android/app/build.gradle文件,添加以下代码:
1 dependencies {
2     implementation project(':react-native-image-picker')
3 }
  • 进入项目根目录,打开android\app\src\main\java\com\你的项目名称1\MainApplication.java文件,添加以下代码:
 1 import com.imagepicker.ImagePickerPackage; // <-- add this import
 2 
 3 public class MainApplication extends Application implements ReactApplication {
 4     @Override
 5     protected List<ReactPackage> getPackages() {
 6         return Arrays.<ReactPackage>asList(
 7             new MainReactPackage(),
 8             new ImagePickerPackage(), // <-- add this line
 9             // OR if you want to customize dialog style
10             new ImagePickerPackage(R.style.my_dialog_style)
11         );
12     }
13 }
  • 进入项目根目录,打开android\app\src\main\java\com\你的项目名称1\MainActivity.java文件,添加以下代码:
 1 // 1. 添加以下两行:
 2     import com.imagepicker.permissions.OnImagePickerPermissionsCallback; // <- add this import
 3     import com.facebook.react.modules.core.PermissionListener; // <- add this import
 4 
 5     public class MainActivity extends ReactActivity {
 6         // 2. 添加如下一行:
 7         private PermissionListener listener; // <- add this attribute
 8 
 9         /**
10          * Returns the name of the main component registered from JavaScript.
11          * This is used to schedule rendering of the component.
12          */
13         @Override
14         protected String getMainComponentName() {
15             return "native_camera";
16         }
17     }

老铁以上设置好后即可正常使用 哦yes!!!

  1.3.使用

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

const options = {
    title: '请选择',
    cancelButtonTitle:'取消',
    takePhotoButtonTitle:'拍照',
    chooseFromLibraryButtonTitle:'从相册选择',
    storageOptions: {
      skipBackup: true,
      path: 'images',
    },
  };

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) {
        Alert.alert('自定义按钮:' + response.customButton)
      } else {
        const source = { uri: response.uri };
        Alert.alert(JSON.stringify(source))
        console.log("source:" + JSON.stringify(source))
      }
    });

以上代码是包含相机以及相册(ui+功能),如果你想要直接触发某项功能,可以调用以下方法:

 1 function openCamera(){
 2     ImagePicker.launchCamera(options , (response) =>{
 3       console.log("response:" + response.path)
 4     })
 5   }
 6 
 7   function openImageLibrary(){
 8     ImagePicker.launchImageLibrary(options , (response) =>{
 9       console.log("response:" + response.path)
10     })
11   }

二、react-native-image-picker 3.x版本的应用GitHub参考文档

【注意:3.x版本不需要设置权限】

  1.安装依赖

1 //@latest选择最新版本
2 yarn add react-native-image-picker@latest
3 
4 # RN >= 0.60
5 cd ios && pod install
6 
7 # RN < 0.60
8 react-native link react-native-image-picker

  2.使用

  1 import * as ImagePicker from 'react-native-image-picker';//--------> 切记注意导包格式
  2 import React from 'react';
  3 import {
  4   StyleSheet,
  5   Text,
  6   View,
  7   Image,
  8   ScrollView,
  9   Platform,
 10   SafeAreaView,
 11   Button,
 12 } from 'react-native';
 13 class App extends React.Component {
 14   const [response, setResponse] = React.useState(null);
 15 
 16   return (
 17     <SafeAreaView>
 18       <ScrollView>
 19         <Button
 20           title="Take image"
 21           onPress={() =>
 22             ImagePicker.launchCamera(
 23               {
 24                 mediaType: 'photo',
 25                 includeBase64: false,
 26                 maxHeight: 200,
 27                 maxWidth: 200,
 28               },
 29               (response) => {
 30                 setResponse(response);
 31               },
 32             )
 33           }
 34         />
 35 
 36         <Button
 37           title="Select image"
 38           onPress={() =>
 39             ImagePicker.launchImageLibrary(
 40               {
 41                 mediaType: 'photo',
 42                 includeBase64: false,
 43                 maxHeight: 200,
 44                 maxWidth: 200,
 45               },
 46               (response) => {
 47                 setResponse(response);
 48               },
 49             )
 50           }
 51         />
 52 
 53         <Button
 54           title="Take video"
 55           onPress={() =>
 56             ImagePicker.launchCamera({mediaType: 'video'}, (response) => {
 57               setResponse(response);
 58             })
 59           }
 60         />
 61 
 62         <Button
 63           title="Select video"
 64           onPress={() =>
 65             ImagePicker.launchImageLibrary({mediaType: 'video'}, (response) => {
 66               setResponse(response);
 67             })
 68           }
 69         />
 70 
 71         <View style={styles.response}>
 72           <Text>Res: {JSON.stringify(response)}</Text>
 73         </View>
 74 
 75         {response && (
 76           <View style={styles.image}>
 77             <Image
 78               style={{width: 200, height: 200}}
 79               source={{uri: response.uri}}
 80             />
 81           </View>
 82         )}
 83       </ScrollView>
 84     </SafeAreaView>
 85   );
 86 }
 87 
 88 const styles = StyleSheet.create({
 89   container: {
 90     flex: 1,
 91     alignItems: 'center',
 92     backgroundColor: '#F5FCFF',
 93   },
 94   button: {
 95     marginVertical: 24,
 96     marginHorizontal: 24,
 97   },
 98   image: {
 99     marginVertical: 24,
100     alignItems: 'center',
101   },
102   response: {
103     marginVertical: 16,
104     marginHorizontal: 8,
105   },
106 });

 

三、使用过程中可能会遇到的问题

1、报错 提示 image-picker 和 sdk 版本问题 ,可以打开你项目下android/app/src/main/AndroidManifest.xml文件添加以下两行代码:

 

 

1 xmlns:tools="http://schemas.android.com/tools"
1 <uses-sdk tools:overrideLibrary="com.imagepicker"/>

如果出现bug 建议重新初始项目来测试。。。。。

2、关于response的返回值在github的api里也有详细说明。

好了,介绍结束,其实还有个更高star的库react-native-camera,而且是有人脸识别功能的,但我觉得普通项目用本文这个已经够用了。

ps:如果跑项目报了一些莫名其妙的错误,可以试着删除node_modules,然后在项目命令行里执行

yarn install

//或者输入

npm instal

 

四、android 10.0 注意参考该博文【链接:https://www.cnblogs.com/freecolor/p/14006263.html 】添加相应的配置信息

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM