rn 图片拍照、上传react-native-image-picker

多图像选择,对裁剪工具的更多控制,以及对横屏的支持等使用react-native-image-crop-picker

1、安装
	yarn add react-native-image-picker

2、配置权限
	(1)在android/app/src/main/AndroidManifest.xml中添加
	
	<uses-permission android:name="android.permission.CAMERA" />
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

在这里插入图片描述

(2)在android/settings.gradle文件中添加
			
	include ':react-native-image-picker'
	project(':react-native-image-picker').projectDir = new File(settingsDir, '../node_modules/react-native-image-picker/android')

在这里插入图片描述

(3)android/app/build.gradle文件的dependencies中

compile project(':react-native-image-picker')

在这里插入图片描述

3、使用
	import ImagePicker from 'react-native-image-picker';

	在回调中设置
	const options = {
	  title: 'Select Avatar',
	  customButtons: [{ name: 'fb', title: 'Choose Photo from Facebook' }],
	  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) {
	    console.log('User tapped custom button: ', response.customButton);
	  } else {
	    const source = { uri: response.uri };
	
	    // You can also display the image using data:
	    // const source = { uri: 'data:image/jpeg;base64,' + response.data };
		
		设置图片返回内容
	    this.setState({
	      avatarSource: source,
	    });
	  }
	});
	
	直接启动相机或相册库
	ImagePicker.launchCamera(options, (response) => {
	  	...
	});
	ImagePicker.launchImageLibrary(options, (response) => {
	 	...
	});

4、图片预览
	当点击确定图片或从相册库中选择,都这样设置
	<Image source={this.state.avatarSource} style={styles.uploadAvatar} />

5、参数配置
	title 		选择器名称
	cancelButtonTitle 	取消按钮文字
	takePhotoButtonTitle 		拍照按钮文字
	chooseFromLibraryButtonTitle 		从本地相册库导入的文字
	chooseWhichLibraryTitle 		其他库导入的文字
	customButtons 	自定义按钮,[{name:'x',title:'自定义按钮标题'},{...},...]
	tintColor	按钮文字颜色,ios
	cameraType 	'front' /'back',摄像头类型,ios
	mediaType	'photo', 'video', or 'mixed'
	maxWidth	只对照片有用
	maxHeight	只对照片有用
	quality 	照片质量,0到1,仅照片
	videoQuality	'low', 'medium', or 'high' on iOS, 'low' or 'high' on Android
	durationLimit	最高录影时间,毫秒
	rotation	 0 to 360 degrees of rotation,只对照片
	storageOptions	如果提供了此键,图像将保存在iOS应用程序的文档目录中(而不是临时目录)。在Android上,此键不影响图像位置(Android总是默认为公共图片目录)
		.skipBackup	如果是true,照片将不会备份到iCloud
		.path	设置后,iOS将保存在Documents/x/而不是根文档,Android将保存在Pictures/x/。
		.cameraRoll 	 	If true, the cropped photo will be saved to the iOS Camera Roll or Android DCIM folder.
		.waitUntilSaved 	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 AND cameraRoll are both true.
		.privateDirectory 	If true, the photo will be saved to the apps private files directory (Android/data/your_package/files/Pictures)
	permissionDenied.title 	Title of explaining permissions dialog. By default Permission denied.
	permissionDenied.text 	Message of explaining permissions dialog. By default To be able to take pictures with your camera and choose images from your library..
	permissionDenied.reTryTitle 	Title of re-try button. By default re-try
	permissionDenied.okTitle 	Title of ok button. By default I'm sure

6、回调response参数
	didCancel	是否点击取消
	error	包含错误消息(如果有的话)
	customButton	如果用户单击了一个自定义按钮,则包含该按钮的名称
	data	使用64编码的图像数据(仅限照片)
	uri		设备上本地文件资产的uri(照片或视频)
	origURL	图片库中原始资产的URL(如果存在的话)
	isVertical	如果图像是垂直方向的,是否为真
	width		(仅限照片)
	height		(仅限照片)
	fileSize	(仅限照片)
	type	文件类型(仅限照片)
	fileName	文件名(如果可用),ios (photos and videos) ,android (photos) 	
	path		文件路径
	latitude	纬度元数据(如果可用)
	longitude
	timestamp
	originalRotation	旋转角度(仅限照片)

代码示例:

import React,{Component} from 'react'
import {
  View,
  Text,
  StyleSheet,
  Button,
  TouchableOpacity,
  Image
} from 'react-native'

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

class Mine extends Component{
    state={
        avatarSource:''
    }
    photo()
    {
        const options = {
            title: '拍照选择器',
            customButtons: [{ name: 'fb', title: '自定义按钮标题' }],
            storageOptions: {
              skipBackup: true,
              path: 'images',
            },
            cancelButtonTitle:'取消',
            takePhotoButtonTitle:'点击拍照',
            chooseFromLibraryButtonTitle:'从本地库相册导入',
            chooseWhichLibraryTitle:'从其他库打开',
            tintColor:'#CB0000' 


          };

        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 {
              const source = { uri: response.uri };
          
              // You can also display the image using data:
              // const source = { uri: 'data:image/jpeg;base64,' + response.data };
          
              this.setState({
                avatarSource: source,
              });
            }
          });
    }
    render()
    {

        return(

            <View>
                <Button title='拍照' onPress={this.photo.bind(this)} />
                {this.state.avatarSource?<Image source={this.state.avatarSource} style={{width:60,height:60}}/>:<Text>图片加载中</Text> }
            </View>
        )
    }
}

const styles = StyleSheet.create({


})

export default Mine

效果图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43294560/article/details/108307836
RN