I'm trying to integrate react-native-image-picker and I was able to successfully install it. Now when I try to choose image from gallery in log it does shows that my imageSource has value but it doesn't display. I'm currently running it on iOS simulator. Below is my code
import ImagePicker from "react-native-image-picker";
const options = {
title: "Select a photo",
takePhotoButtonTitle: "Take a photo",
chooseFromLibraryButtonTitle: "Choose from gallery",
quality: 1
};
constructor(props) {
super(props);
this.state = { imageSource: null };
}
addImage = () => {
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 {
const source = { uri: response.uri };
this.setState({
imageSource: source,
});
console.log("Imagesource=" + JSON.stringify(source));
}
});
}
render() {
return (
<View style={styles.container}>
<Image source={this.state.imageSource} />
</View>
);
}
The console log does print the path to the image I picked from gallery but it just doesn't display. I'm running it on iPad with landscape orientation. Any help is appreciated.
Any Image shown should have fixed width and height.
You can use the Dimensionlike this var { width, height } = Dimensions.get("window"); to use height and width with respect to screen size(Don't forget to import from react-native).
Or you could just go ahead and give your own values to the respective parameters.
Related
I want users to be able to take photos from within my app and have the photos save to their gallery (so that I can later view them in a photo-picker).
I have the following code from react-native-camera, it's basically the bare-bones demo code.
takePicture() {
const options = { quality: 0.5, fixOrientation: false, width: 1920 };
if (this.camera) {
this.camera
.takePictureAsync(options)
.then(data => {
this.saveImage(data.uri);
})
.catch(err => {
console.error("capture picture error", err);
});
} else {
console.error("No camera found!");
}
}
}
To move the attachment, I am using react-native-fs, as follows (more basic demo-y code):
const dirHome = Platform.select({
ios: `${RNFS.DocumentDirectoryPath}/Pictures`,
android: `${RNFS.ExternalStorageDirectoryPath}/Pictures`
});
const dirPictures = `${dirHome}/MyAppName`;
saveImage = async filePath => {
try {
// set new image name and filepath
const newImageName = `${moment().format("DDMMYY_HHmmSSS")}.jpg`;
const newFilepath = `${dirPictures}/${newImageName}`;
// move and save image to new filepath
const imageMoved = await this.moveAttachment(filePath, newFilepath);
console.log("image moved: ", imageMoved);
} catch (error) {
console.log(error);
}
};
moveAttachment = async (filePath, newFilepath) => {
return new Promise((resolve, reject) => {
RNFS.mkdir(dirPictures)
.then(() => {
RNFS.moveFile(filePath, newFilepath)
.then(() => {
console.log("FILE MOVED", filePath, newFilepath);
resolve(true);
})
.catch(error => {
console.log("moveFile error", error);
reject(error);
});
})
.catch(err => {
console.log("mkdir error", err);
reject(err);
});
});
};
When taking a photo, this code executes and prints that the image has been moved within a couple of seconds. But, when I look into the built in Gallery App on the device, it often takes several minutes for the image to finally load. I've tried this across many different devices, both emulated and physical... am I doing something wrong? Thanks!
This was caused by Android's Media Scanner not immediately realizing new files existed.
From this Git issue and the subsequent PR: https://github.com/itinance/react-native-fs/issues/79
I modified my code as follows:
saveImage = async filePath => {
try {
// set new image name and filepath
const newImageName = `${moment().format("DDMMYY_HHmmSSS")}.jpg`;
const newFilepath = `${dirPicutures}/${newImageName}`;
// move and save image to new filepath
const imageMoved = await this.moveAttachment(filePath, newFilepath).then(
imageMoved => {
if (imageMoved) {
return RNFS.scanFile(newFilepath);
} else {
return false;
}
}
);
console.log("image moved", imageMoved);
} catch (error) {
console.log(error);
}
};
using RNFS's scanFile method to force the Media Scanner to realize the file exists. This is rough code I'll need to clean up, but it gets the job done.
As the title says, I'm trying to upload Image to firebase in react native. I'm using react-native-image-picker and firebase modules for that. My code goes as: (Only including the "main" parts for clarity)
import ImagePicker from 'react-native-image-picker';
...
//called on pressing a button
onChooseImagePress = async () => {
let result = await ImagePicker.open({ //error occurs here
takePhoto: true,
useLastPhoto: true,
chooseFromLibrary: true
});
if (!result.cancelled) {
this.uploadImage(result.uri, "test-image")
.then(() => {
Alert.alert("Success");
})
.catch((error) => {
Alert.alert(error);
});
}
}
uploadImage = async (uri, imageName) => {
const response = await fetch(uri);
const blob = await response.blob();
var ref = firebase.storage().ref('images').child("userName/" + imageName);
return ref.put(blob);
}
....
Issue:
I am getting this error: undefined is not a function. Here's a screenshot of the same:
I'm not sure what it even means, since ImagePicker has an open function. Please note that I have provided the desired permissions. So it is not an issue due to that. Please help me resolve this. Thanks...
Are you using React-native ImagePicker? There is no open in the API document.
API Reference of react-native-image-picker
This is the default example of getting the value of the selected image you want.
import ImagePicker from 'react-native-image-picker';
// More info on all the options is below in the API Reference... just some common use cases shown here
const 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 in the API Reference)
*/
ImagePicker.launchImageLibrary(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,
});
}
});
I am trying to upload image to server with progress by using the example provided by:
https://gist.github.com/Tamal/9231005f0c62e1a3f23f60dc2f46ae35
I checked some tutorials, the code should works. But the uri in Android show uri
uri: content://media/external/images/media/4985
The URI come from the component
https://github.com/jeanpan/react-native-camera-roll-picker
The URI should be
file://....
So, why the upload code not working.
How can I convert the
content://... to file://.... to make it possible to upload image to server in React-native? or does my assumed is correct?
I am using react-native-image-picker to get image from library. I have written following code in one method name as selectPhoto() to select image from library.
selectedPhoto = () => {
//Open Image Picker
const options = {
quality: 1.0,
maxWidth: 500,
maxHeight: 500,
};
ImagePicker.showImagePicker(options, (response) => {
//console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled photo 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};
console.log(source.uri);
this.setState({
profilePhoto: source
});
}
}); }
This will give me uri of selected image and I have set in state variable. then write following code to upload image.
var profiePicture = {
uri: this.state.profilePhoto.uri,
type: 'image/jpg', // or photo.type image/jpg
name: 'testPhotoName',
}
// API to upload image
fetch('http://www.example.com/api/uploadProfilePic/12345', {
method: 'post',
headers:{
'Accept': 'application/json',
'content-type': 'multipart/form-data',
},
body: JSON.stringify({
'profile_pic' : profiePicture
})
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
This code is working in one of the my project.
I need to render image tag in a loop based on array length,
My image tag looks similar to this
<Image
style={{width: 50, height: 50}}
source={{uri: 'https://facebook.github.io/react/img/logo_og1.png'}}
//if image fails to load from the uri then load from'./img/favicon.png'
onError={(error) => {console.log('loadinf',error)}}
/>
If error occurs while fetching from Uri i.e 404 error retry for sometime or show default local image.
How to do that in react native?
You put in a loading image in the place of real image using defaultSource property but it is only available to iOS as of this moment. We can achieve the other thing you wrote that it should display a local image in case it couldn't load the image from the internet by the following approach.
Store the original image URI in state.
Use this URI from state in source of the image.
When onError function is called change this state variable to your local image.
Example:
import React, {Component} from 'react';
import {
View,
Image
} from 'react-native';
export default class Demo extends Component {
constructor(props) {
super(props);
this.state = {
image: {
uri: 'something demo'
}
}
}
render() {
return <View>
<Image
source={ this.state.image }
onError={(a) => {
this.setState({
image: require('image.png')
});
}}
style={{ height: 100, width: 100 }}
/>
</View>
}
}
A dirty hack for retrying the image would be something like this:
let counter = 0;
export default class reactNativePange extends Component {
constructor(props) {
super(props);
this.state = {
image: {
uri: 'something demo'
},
failed: false
}
}
render() {
return (
<View style={styles.container}>
<Image
source={ this.state.failed ? require('./image.png') : { uri: 'something demo' } }
onError={(a) => {
if(counter >= 3) {
this.setState({
failed: true
});
} else {
counter++;
this.setState({
failed: true
});
setTimeout(() => {
this.setState({
failed: false
});
}, 1)
}
}}
style={{ height: 100, width: 100 }}
/>
</View>
);
}
}
As I mentioned that this is a dirty hack as the image might flicker during the retry.
I want to take an image using react-native image picker,
I am using npm run android command but as the application runs in expo it shows this error:
undefined is not an object(evaluating 'imagepickerManager.showimagepicker')
As I am using expo project index.android.js is not present in the project so react-native run-android command is not working.
Can someone please guide me how to recover this error?
import React, {Component} from 'react';
import {Text, View, TouchableOpacity, Image} from 'react-native';
// var ImagePicker = require('react-native-image-picker');
import * as ImagePicker from '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'
}
};
export default class App extends Component{
constructor(props){
super(props);
this.state={
avatarSource:null
}
}
render(){
let img=this.state.avatarSource == null?null:
<Image
source={this.state.avatarSource}
style={{height:200, width:300}}
/>
return(
<View>
<Text>Welcome to Image Picker</Text>
<TouchableOpacity onPress = {this.show.bind()} >
<Text>Load Images</Text>
</TouchableOpacity>
{img}
</View>
)
}
show(){
ImagePicker.showImagePicker(options, (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 please: ', 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
});
}
});
}
}
I was having the same issue. And solved it in following way -
react-native link react-native-image-picker
run the react-native-run-ios and react-native run-android command
More description here
I just fix this error by running react-native link then rebuild your app. It should work as expected. :)
import * as ImagePicker from "react-native-image-picker"