1.安装
yarn add react-native-image-picker
2. 安卓的拍照权限
<uses-permission android:name="android.permission.CAMERA" />
3. 代码示例:
import React, { Component } from 'react'
import { Text, View ,Image, Button} from 'react-native'
import ImagePicker from 'react-native-image-picker';
const options = {
title: '选择照片',
customButtons: [{ name: 'fb', title: '从网站选择' }],
storageOptions: {
skipBackup: true,
path: 'images',
},
};
export default class App6 extends Component {
constructor(props){
super(props)
this.state={avatarSource: ''}
}
_select=()=>{
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 };
console.log(response.uri)
// You can also display the image using data:
// const source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source,
});
}
});
}
_selectFromCamera=()=>{
ImagePicker.launchCamera(options, (response) => {
// Same code as in above section!
});
}
_selectFromLibrary=()=>{
ImagePicker.launchImageLibrary(options, (response) => {
// Same code as in above section!
});
}
render() {
return (
<View>
<Button title="从列表选择" onPress={this._select}/>
<Button title="用相机拍照" onPress={this._selectFromCamera}/>
<Button title="从相册选择" onPress={this._selectFromLibrary}/>
<Image style={{width:100,height:100}} source={this.state.avatarSource}/>
</View>
)
}
}
网友评论