How to open downloaded photo using gallery app in React Native Expo? - react-native

I am facing a problem, cannot figure out how to implement such action. I want to Download Photo from external source, and then I want to open it in gallery.
Checked this source: How to open iOS gallery app from React Native app
Here one developer suggest to use this code:
openPhotos = () =>{
switch(Platform.OS){
case "ios":
Linking.openURL("photos-redirect://");
break;
case "android":
Linking.openURL("content://media/internal/images/media");
break;
default:
console.log("Could not open gallery app");
}
}
This code does open gallery, but when I select default gallery app, it shows black screen, if I choose google photos app it opens the gallery without black screen.
My question would be how could I refactor my code, to be able to Download Photo, and open downloaded photo in gallery?
Component code:
import React from "react";
import {View,Text, StyleSheet,Platform,Image,Alert} from "react-native";
import PhotoComments from "./PhotoComments";
import moment from "moment";
import * as MediaLibrary from "expo-media-library";
import * as FileSystem from "expo-file-system";
import * as Permissions from "expo-permissions";
import { Button } from "react-native-elements";
import { Linking } from "expo";
function downloadFile(uri) {
let filename = uri.split("/");
filename = filename[filename.length - 1];
let fileUri = FileSystem.documentDirectory + filename;
FileSystem.downloadAsync(uri, fileUri)
.then(({ uri }) => {
saveFile(uri);
})
.catch(error => {
Alert.alert("Error", "Couldn't download photo");
console.error(error);
});
}
async function openPhotos(uri) {
switch (Platform.OS) {
case "ios":
Linking.openURL("photos-redirect://");
break;
case "android":
//Linking.openURL("content://media/internal/images/media/");
Linking.openURL("content://media/internal/images/media");
break;
default:
console.log("Could not open gallery app");
}
}
async function saveFile(fileUri) {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status === "granted") {
const asset = await MediaLibrary.createAssetAsync(fileUri);
const data = await MediaLibrary.createAlbumAsync("Download", asset, false);
console.log("deubeuger");
console.log(data);
console.log("buger");
Alert.alert("Success!", JSON.stringify(fileUri));
openPhotos(fileUri);
}
}
const PhotoRecord = ({ data }) => {
return (
<View style={styles.container}>
<View style={styles.infoContainer}>
<Text style={styles.usernameLabel}>#{data.username}</Text>
<Text style={styles.addedAtLabel}>
{moment(new Date(data.addedAt)).format("YYYY/MM/DD HH:mm")}
</Text>
</View>
<View style={styles.imageContainer}>
<Image source={{ uri: data.links.thumb }} style={styles.image} />
</View>
<PhotoComments comments={data.photoComments} />
<View style={styles.btnContainer}>
<Button
buttonStyle={{
backgroundColor: "white",
borderWidth: 1
}}
titleStyle={{ color: "dodgerblue" }}
containerStyle={{ backgroundColor: "yellow" }}
title="Add Comment"
/>
<Button
onPress={() => downloadFile(data.links.image)}
style={styles.btn}
title="Download"
/>
</View>
</View>
);
};
I managed to implement downloading from external source, but cannot find the working solutions on how to open downloaded photo through gallery app.
Maybe I am looking for solution which is not efficient, maybe there is a better way?

Couldn't find desirable solution for this problem. Decided to develop an app a little bit differently, if someone with similar problem will search for this thread. I made Download Button which will Download photo to the device
import React, { useState } from "react";
import {
View,
Text,
StyleSheet,
Image,
Alert,
TouchableOpacity
} from "react-native";
import PhotoComments from "./PhotoComments";
import moment from "moment";
import * as MediaLibrary from "expo-media-library";
import * as FileSystem from "expo-file-system";
import * as Permissions from "expo-permissions";
import { Button } from "react-native-elements";
import ZoomableImage from "./ZoomableImage";
function downloadFile(uri) {
let filename = uri.split("/");
filename = filename[filename.length - 1];
let fileUri = FileSystem.documentDirectory + filename;
FileSystem.downloadAsync(uri, fileUri)
.then(({ uri }) => {
saveFile(uri);
})
.catch(error => {
Alert.alert("Error", "Couldn't download photo");
console.error(error);
});
}
async function saveFile(fileUri) {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status === "granted") {
const asset = await MediaLibrary.createAssetAsync(fileUri);
await MediaLibrary.createAlbumAsync("Download", asset, false);
Alert.alert("Success", "Image was successfully downloaded!");
}
}
const PhotoRecord = ({ data }) => {
const [show, setShow] = useState(false);
return (
<View style={styles.container}>
<ZoomableImage
show={show}
setShow={setShow}
imageSource={data.links.image}
/>
<View style={styles.infoContainer}>
<Text style={styles.usernameLabel}>#{data.username}</Text>
<Text style={styles.addedAtLabel}>
{moment(new Date(data.addedAt)).format("YYYY/MM/DD HH:mm")}
</Text>
</View>
<TouchableOpacity
activeOpacity={1}
style={styles.imageContainer}
onLongPress={() => setShow(true)}
>
<Image source={{ uri: data.links.thumb }} style={styles.image} />
</TouchableOpacity>
<PhotoComments comments={data.photoComments} />
<View style={styles.btnContainer}>
<Button
buttonStyle={{
backgroundColor: "white",
borderWidth: 1
}}
titleStyle={{ color: "dodgerblue" }}
containerStyle={{ backgroundColor: "yellow" }}
title="Add Comment"
/>
<Button
onPress={() => downloadFile(data.links.image)}
style={styles.btn}
title="Download"
/>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
display: "flex",
flexDirection: "column"
},
infoContainer: {
borderBottomWidth: 1,
borderColor: "gainsboro",
display: "flex",
flexDirection: "row",
justifyContent: "space-between",
padding: 15
},
usernameLabel: {
fontSize: 18,
fontWeight: "bold"
},
addedAtLabel: {
paddingTop: 10,
color: "#404040"
},
imageContainer: {
width: "100%",
height: 380
},
image: {
width: "100%",
height: "100%",
resizeMode: "cover"
},
btnContainer: {
flex: 1,
flexDirection: "row",
marginBottom: 100,
justifyContent: "space-between"
}
});
export default PhotoRecord;
On my device it looks like this
If Download button clicked it will download the photo to the device
If user want to inspect the image, he can do long press on the photo and then the photo will be open in a web view modal
This is far from perfect, but I could figure out by myself.
The code for modal is here:
import React from "react";
import { Modal, Dimensions, StyleSheet, View } from "react-native";
import { WebView } from "react-native-webview";
const ZoomableImage = ({ show, setShow, imageSource }) => {
return (
<Modal
animationType={"fade"}
transparent={false}
visible={show}
onRequestClose={() => {
setShow(!show);
}}
>
<View style={styles.container}>
<WebView source={{ uri: imageSource }} style={styles.image} />
</View>
</Modal>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "space-between"
},
image: {
height: Math.round(Dimensions.get("window").height),
width: Math.round(Dimensions.get("window").width),
flex: 1
}
});
export default ZoomableImage;
Couldn't achieve what I wanted but came up with a slightly different solution, hopes this will help someone.

Related

React Native: Camera from "expo-camera" stop running when face is not ever detected

I am newer for using react-native, and wanna try to create a camera with filter. I'm blocked in step to recognize face. Have success to draw rectangle when face detected, but the problem is once it goes out of detection. The camera stop running as it fixes on the last real-time capture
Here is my code:
import { useState, useEffect, useRef } from 'react'
import { Camera } from 'expo-camera'
import * as MediaLibrary from 'expo-media-library'
import { Text, StyleSheet, View, TouchableOpacity } from 'react-native'
import Button from './Button'
import { Ionicons } from '#expo/vector-icons'
import * as FaceDetector from 'expo-face-detector'
export default function PCamera() {
const cameraRef = useRef(undefined)
const [faceDetected, setFaceDetected] = useState([])
const [lastImage, setImage] = useState(undefined)
const [hasUsePermssion, setUsePermission] = useState(false)
const [type, switchToType] = useState(Camera.Constants.Type.front)
const takePicture = async () => {
if (cameraRef) {
try {
const options = {
quality: 1,
base64: true,
exif: false,
}
const data = await cameraRef.current.takePictureAsync(options)
setImage(data.uri)
console.log(data)
} catch (err) {
console.error(err)
}
}
}
const swithMode = () => {
switchToType(
type === Camera.Constants.Type.front
? Camera.Constants.Type.back
: Camera.Constants.Type.front
)
}
const handleFacesDetected = ({ faces }) => {
setFaceDetected(faces)
}
useEffect(() => {
;(async () => {
const { status } = await Camera.requestCameraPermissionsAsync()
if (status === 'granted') {
setUsePermission(true)
}
})()
}, [])
if (hasUsePermssion === null) {
return <View />
}
if (hasUsePermssion === false) {
return <Text>No access to camera</Text>
}
return (
<View style={styles.cameraContainer}>
<View style={styles.overlay}>
<Camera
ref={cameraRef}
style={styles.camera}
type={type}
onFacesDetected={handleFacesDetected}
faceDetectorSettings={{
mode: FaceDetector.FaceDetectorMode.fast,
detectLandmarks: FaceDetector.FaceDetectorLandmarks.all,
runClassifications:
FaceDetector.FaceDetectorClassifications.none,
minDetectionInterval: 100,
tracking: true,
}}
>
{faceDetected.length > 0 &&
faceDetected.map((face) => (
<View
key={face.faceID}
style={{
position: 'absolute',
borderWidth: 2,
borderColor: 'red',
left: face.bounds.origin.x,
top: face.bounds.origin.y,
width: face.bounds.size.width,
height: face.bounds.size.height,
}}
/>
))}
</Camera>
</View>
<View style={styles.optionsContainer}>
<View>
<TouchableOpacity onPress={swithMode}>
<Text>
<Ionicons
name="camera-reverse-outline"
size={24}
color="black"
/>
</Text>
</TouchableOpacity>
</View>
<Button
icon="camera"
title="Take Photo"
onPress={takePicture}
style={styles.button}
/>
<View>
<Text>...</Text>
</View>
</View>
</View>
)}
const styles = StyleSheet.create({
cameraContainer: {flex: 1,
},
overlay: {
flex: 6,
borderBottomStartRadius: 75,
borderBottomEndRadius: 75,
overflow: 'hidden',
},
camera: {
flex: 1,
},
optionsContainer: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
},
})
N.B: Don't take care of the Button, it's a custom component and works well

Audio not playing when a random url path is passed from REST API

I have a util function defined in soundLoader.js that will play the audio. And I have a react-native component I called the util function and passed the url to play the audio. I get the url by the id from currently clicked button using rest api, and the plan is when the button is clicked I will pass the audio url path for the soundLoader function and I want it to play and also enable it to pause if another button is clicked I want the previous one to stop and play the current clicked audio or pause if the same button is clicked. Here is my code below, how I try to code the logic. After the code runs when I try to play the audio when button is clicked I get " LOG playback failed due to audio decoding errors " It is not playing the audio. How should I fix this issue and enable it to play and pause the audio?
`soundLoader.js`
var Sound = require('react-native-sound');
Sound.setCategory('Playback');
var duration =0
function mySoundLoader (url) {
let isPlaying = false;
setIsPlaying = (val) =>{
isPlaying = val;
return isPlaying;
}
var audio = new Sound(url, null, (e) => {
if (e) {
console.log('error loading track:', e);
return;
}
duration = Math.floor(audio.getDuration());
console.log(
'duration in seconds: ' +
audio.getDuration() +
'number of channels: ' +
audio.getNumberOfChannels(),
);
audio.setVolume(1);
audio.release();
if (audio.isPlaying()) {
audio.pause();
setIsPlaying(false);
} else {
setIsPlaying(true);
audio.play(success => {
if (success) {
setIsPlaying(false);
console.log('successfully finished playing');
} else {
setIsPlaying(false);
console.log('playback failed due to audio decoding errors');
}
});
}
})
}
setTimeout(() => mySoundLoader, duration)
export default mySoundLoader;
`player.js`
import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, TouchableWithoutFeedback, Button } from 'react-native';
import { FlatList, Image, TouchableOpacity } from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { getMovies, addFavorite, removeFavorite, getKefleInfo, getMezmurById } from '../redux/actions';
import dings from '../../src/audio/trimmed-harp-curved.mp3';
import Ionicons from 'react-native-vector-icons/Ionicons';
import mySoundLoader from './SoundLoader';
export default function Kefle() {
const { kefleInfo } = useSelector(state => state.kefleReducer);
const dispatch = useDispatch();
const fetchKefleInfo = () => dispatch(getKefleInfo());
const [activeId, setActiveId] = useState();
useEffect(() => {
fetchKefleInfo();
console.log(kefleInfo)
}, []);
actionOnRow = (item) => {
console.log("here actionOnRow called")
console.log('Selected Item :', item);
setActiveId(item.mezmur_id);
}
return (
<View style={{ flex: 1, marginTop: 44, paddingHorizontal: 20 }}>
<Text style={{ fontSize: 22 }}>Music Player</Text>
<View style={{ flex: 1, marginTop: 12 }}>
<FlatList
data={kefleInfo}
keyExtractor={item => item.mezmur_id}
renderItem={({ item }) => {
const IMAGE_URL = item.kefle_photo;
return (
<View style={{ marginVertical: 12 }}>
<TouchableWithoutFeedback onPress={() => actionOnRow(item)}>
<View style={{ flexDirection: 'row', flex: 1 }}>
<View style={{ flex: 1, marginLeft: 12 }}>
<View>
<Text style={{ fontSize: 22, paddingRight: 16, textAlign: "center" }}>
{item.title}
</Text>
<Button title="play me" onPress={(e) => {
mySoundLoader(item.audio)
}} />
</View>
<View
style={{
flexDirection: 'row',
marginTop: 10,
alignItems: 'center',
}}>
</View>
</View>
</View>
</TouchableWithoutFeedback>
</View>
);
}}
showsVerticalScrollIndicator={false}/>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#000',
},
playBtn: {
padding: 20,
},
});

How do you get 1 specific value from a prop in expo?

I've been trying to pass up this prop from CameraButton.js file that gives the UI of an image that was taken but whenever I activate the prop in the AddPost.js, it gives me all the values but when I try to get the singular value of the image like using console.log(props.route.params.image) and gives error undefined is not an object
enter image description here
but it works perfectly when export default function console.log(props.route.params) and shows
enter image description here
AddPost.JS
import { useNavigation } from "#react-navigation/core";
import React from 'react'
import {useState} from "react";
import { View, TextInput, Button } from 'react-native'
export default function AddPost(props) {
console.log(props);
const navigation = useNavigation();
const [caption, setCaption] = useState("")
const uploadImage = async () => {
const response = await fetch(uri)
}
return (
<View style={{flex: 1}}>
<TextInput
placeholder="Whats on your mind Edgers navars"
onChangeText={(caption) => setCaption(caption)}
/>
<Button title = "Take A Photo" onPress={() => navigation.navigate("CameraButton")}
/>
<Button title = "Save" onPress={() => uploadImage()}
/>
</View>
)
}
CameraButton.Js
import { Camera, CameraType } from 'expo-camera';
import { useNavigation } from "#react-navigation/core";
import { useState } from 'react';
import { Button, StyleSheet, Text, TouchableOpacity, View, Image } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
export default function App() {
const navigation = useNavigation();
const [type, setType] = useState(Camera.Constants.Type.back)
const [permission, requestPermission] = Camera.useCameraPermissions();
const [image, setImage] = useState(null);
const [camera, setCamera] = useState(null);
const takePicture = async () => {
if(camera){
const data = await camera.takePictureAsync(null);
setImage(data.uri);
}
}
if (!permission) {
// Camera permissions are still loading
return <View />;
}
if (!permission.granted) {
// Camera permissions are not granted yet
return (
<View style={styles.container}>
<Text style={{ textAlign: 'center' }}>
We need your permission to show the camera
</Text>
<Button onPress={requestPermission} title="grant permission" />
</View>
);
}
function toggleCameraType() {
setType((current) => (
current === Camera.Constants.Type.back ? Camera.Constants.Type.front : Camera.Constants.Type.back
));
}
// No permissions request is necessary for launching the image library
let openImagePickerAsync = async () => {
let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (permissionResult.granted === false) {
alert("Permission to access camera roll is required!");
return;
}
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.cancelled) {
setImage(result.uri);
}
}
return (
<View style={styles.container}>
<Camera ref={ref => setCamera(ref)} style={styles.camera} type={type}>
<View style={styles.buttonContainer}>
<TouchableOpacity
style={styles.button}
onPress={toggleCameraType}>
<Text style={styles.text}>Flip Camera</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => takePicture()}>
<Text style={styles.text}>Take Picture</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={openImagePickerAsync}>
<Text style={styles.text}>Choose Picture</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('AddPost', {image})}>
<Text style={styles.text}>Save Picture</Text>
</TouchableOpacity>
</View>
</Camera>
{image &&<Image source={{uri: image}}style={styles.camera}/>}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
camera: {
flex: 1,
},
buttonContainer: {
flex: 1,
flexDirection: 'row',
backgroundColor: 'transparent',
margin: 64,
},
button: {
flex: 1,
alignSelf: 'flex-end',
alignItems: 'center',
},
text: {
fontSize: 24,
fontWeight: 'bold',
color: 'white',
},
});
You have to get the uri from the route object.
const response = await fetch(props.route.params?.image)
In you file CameraButton.js set the navigation for this:
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('AddPost', {
image: image
})}>
<Text style={styles.text}>Save Picture</Text>
</TouchableOpacity>
Be sure that the state image contains only the uri and not and object
Try props[0].route.params.image.

How to open the camera and taking the picture in react native?

I want to open the device camera from my app when user click on the button and when user click on back button it should react to my application from device camera. I am able to open camera and take photo by running react native project. But I want to do it how camera works in what's app. That is clicking on button -> opening camera -> send button .
I am an beginner in react native .I tried many ways but I am not getting how it can be done.
Can anybody assist me to do this.
My App.js code is,
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
Dimensions,
StyleSheet,
Text,
TouchableHighlight,
View
} from 'react-native';
import Camera from 'react-native-camera';
class BadInstagramCloneApp extends Component {
render() {
return (
<View style={styles.container}>
<Camera
ref={(cam) => {
this.camera = cam;
}}
style={styles.preview}
aspect={Camera.constants.Aspect.fill}>
<Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
</Camera>
</View>
);
}
takePicture() {
const options = {};
//options.location = ...
this.camera.capture({metadata: options})
.then((data) => console.log(data))
.catch(err => console.error(err));
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center'
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: '#000',
padding: 10,
margin: 40
}
});
AppRegistry.registerComponent('BadInstagramCloneApp', () => BadInstagramCloneApp);
You can use the state to show/hide the camera view/component.
Please check the following code:
...
class BadInstagramCloneApp extends Component {
constructor(props) {
super(props);
this.state = {
isCameraVisiable: false
}
}
showCameraView = () => {
this.setState({ isCameraVisible: true });
}
render() {
const { isCameraVisible } = this.state;
return (
<View style={styles.container}>
{!isCameraVisible &&<Button title="Show me Camera" onPress={this.showCameraView} />}
{isCameraVisible &&
<Camera
ref={(cam) => {
this.camera = cam;
}}
style={styles.preview}
aspect={Camera.constants.Aspect.fill}>
<Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
</Camera>}
</View>
);
}
takePicture() {
const options = {};
//options.location = ...
this.camera.capture({metadata: options})
.then((data) => {
console.log(data);
this.setState({ isCameraVisible: false });
}
.catch(err => console.error(err));
}
}
...
You can use https://github.com/ivpusic/react-native-image-crop-picker for this. This component helps you to take photo and also the photo if required. Follow the documentation correctly and here is the code for camera selection option
ImagePicker.openCamera({
cropping: true,
width: 500,
height: 500,
cropperCircleOverlay: true,
compressImageMaxWidth: 640,
compressImageMaxHeight: 480,
freeStyleCropEnabled: true,
}).then(image => {
this.setState({imageModalVisible: false})
})
.catch(e => {
console.log(e), this.setState({imageModalVisible: false})
});
Correction of best answer because of deprecation of Camera to RNCamera plus missing closing bracket ")" right before the .catch and like a spelling mistake with the declaration of state:
But basically there's 2 routes, whether you're using expo or react native. You gotta have Pods/Ruby/Cocoapods or manually link and all that if you're using traditional React Native, but just go with expo-camera if you got an expo set up and don't listen to this.
This is a React-Native with Pods/Ruby/CocoaPods solution, whereas going with expo-camera might be much faster and better if you're not set up like this.
import React, { Component } from 'react';
import {
Text,
View,
StyleSheet,
Button,
TouchableOpacity
} from 'react-native';
import { RNCamera } from 'react-native-camera';
export default class Camera2 extends Component {
constructor(props) {
super(props);
this.state = {
isCameraVisible: false
}
}
showCameraView = () => {
this.setState({ isCameraVisible: true });
}
takePicture = async () => {
try {
const data = await this.camera.takePictureAsync();
console.log('Path to image: ' + data.uri);
} catch (err) {
// console.log('err: ', err);
}
};
render() {
const { isCameraVisible } = this.state;
return (
<View style={styles.container}>
{!isCameraVisible &&<Button title="Show me Camera" onPress={this.showCameraView} />}
{isCameraVisible &&
<RNCamera
ref={cam => {
this.camera = cam;
}}
style={styles.preview}
>
<View style={styles.captureContainer}>
<TouchableOpacity style={styles.capture} onPress={this.takePicture}>
<Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
<Text>Take Photo</Text>
</TouchableOpacity>
</View>
</RNCamera>}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center'
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: '#000',
padding: 10,
margin: 40
}
});

In React Native how can I access the native camera app?

I would like to add a link to my app that opens the phone's native camera app? Is this possible?
I'm aware that react-native-camera exists but from the docs it seems like it only supports accessing the camera for the purpose of creating your own camera interface inside your app. I would rather just use the camera app already on the phone.
Thank you
Use react-native-image-picker, you can access phone native's camera.
[EDIT]
An example Code
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Image,
Button
} from 'react-native';
import ImagePicker from "react-native-image-picker";
export default class App extends Component {
state = {
pickedImage: null
}
reset = () => {
this.setState({
pickedImage: null
});
}
pickImageHandler = () => {
ImagePicker.showImagePicker({title: "Pick an Image",
maxWidth: 800, maxHeight: 600}, res => {
if (res.didCancel) {
console.log("User cancelled!");
} else if (res.error) {
console.log("Error", res.error);
} else {
this.setState({
pickedImage: { uri: res.uri }
});
}
});
}
resetHandler = () =>{
this.reset();
}
render() {
return (
<View style={styles.container}>
<Text style={styles.textStyle}>Pick Image From Camera and Gallery</Text>
<View style={styles.placeholder}>
<Image source={this.state.pickedImage} style={styles.previewImage} />
</View>
<View style={styles.button}>
<Button title="Pick Image" onPress={this.pickImageHandler} />
<Button title="Reset" onPress={this.resetHandler} />
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
alignItems:"center"
},
textStyle: {
fontWeight:"bold",
fontSize:30,
textAlign:"center",
color:"red",
marginTop:10
},
placeholder: {
borderWidth: 1,
borderColor: "black",
backgroundColor: "#eee",
width: "70%",
height: 280,
marginTop:50,
},
button: {
width: "80%",
marginTop:20,
flexDirection:"row",
justifyContent: "space-around"
},
previewImage: {
width: "100%",
height: "100%"
}
});
}
Source: react-native-image-picker