I am using the expo-image-picker to get the image uri of a locally stored image. I want to use the expo-image-manipulator to resize the image prior to sending it to the backend but the expo imageManipulator will not take the uri from the expo image picker. These errors are happening while running in expo on an android emulator.
Here is the basic code getting the uri:
import * as ImagePicker from "expo-image-picker";
const selectImage = async () => {
try {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
quality: 0.5,
});
if (!result.cancelled) onChangeImage(result.uri);
} catch (error) {
console.log("Error reading an image", error);
}
};
I can send this image directly to the backend and save it to my S3 just fine. When I console.log(uri), here is what I get:
file:/data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FThredFit-59f4d533-f203-4efb-bcb0-6a5786d44584/ImagePicker/0ea74111-8677-4074-81af-5fbc1f0758d5.jpg
Now I try to enter this into the image resizer below (as imageUri):
import * as ImageManipulator from 'expo-image-manipulator';
const setSize = async (imageUri, width, height) => {
try {
const manipResult = await ImageManipulator.manipulateAsync(
imageUri,
[{ resize: { width: width, height: height } }],
{ format: 'jpeg' }
);
console.log(manipResult);
} catch (error) {
console.log("Error manipulating image: ", error);
}
};
and I get the following error on the android emulator:
abi38_0_0.com.facebook.react.bridge.ReadableNativeMap cannot be cast to java.lang.String
if I stringify the imageUrl first, then I get past this error but the resizer throws an error saying it can't decode the image:
[Error: Could not get decoded bitmap of "file:/data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FThredFit-59f4d533-f203-4efb-bcb0-6a5786d44584/ImagePicker/0ea74111-8677-4074-81af-5fbc1f0758d5.jpg": java.lang.Exception: Loading bitmap failed]
Image of the emulator error
image of the logged error
It's hard to see exactly what is going on here because you didn't provide all of the relevant code. I suspect that the issue you encountered is around stringifying an object rather than getting the appropriate value off of it. Here's an example of ImagePicker and ImageManipulator integration: https://snack.expo.io/#brents/image-picker-and-manipulator
import React, { useState, useEffect } from 'react';
import { Button, Image, View, Platform } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import * as ImageManipulator from 'expo-image-manipulator';
import Constants from 'expo-constants';
export default function ImagePickerExample() {
const [image, setImage] = useState(null);
useEffect(() => {
(async () => {
if (Platform.OS !== 'web') {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
alert('Sorry, we need camera roll permissions to make this work!');
}
}
})();
}, []);
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(result);
if (result.cancelled) {
return;
}
const manipResult = await ImageManipulator.manipulateAsync(
result.localUri || result.uri,
[{ rotate: 90 }, { flip: ImageManipulator.FlipType.Vertical }],
{ compress: 1, format: ImageManipulator.SaveFormat.PNG }
);
setImage(manipResult.uri);
};
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button title="Pick an image from camera roll" onPress={pickImage} />
{image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
</View>
);
}
Related
I use React Native and Expo to develop an application on mobile and tablet. I need to be able to take a photo and save it to my local SQLite database. I manage to take my photo and save it, then display it on a page. I use expo-camera.
Everything is fine in IOS. However, the image is corrupted on Android. My images are saved in base64. I add two links leading to the result on android and on IOS.
IOS version
Android version
The conversion to base64 takes place at the end of this extract in __takePicture :
const [startCamera, setStartCamera] = useState(false);
const [photo, setPhoto] = useState(null);
const [zoom, setZoom] = useState(0);
const [hasPermission, setHasPermission] = useState(null);
const [type, setType] = useState(CameraType.back);
const [camera, setCamera] = useState(null);
useEffect(() => {
(async () => {
const { status } = await Camera.requestCameraPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
useEffect(() => {
__startCamera(props.startCamera);
}), [startCamera, props.startCamera];
const __startCamera = async (props) => {
const { status } = await Camera.requestCameraPermissionsAsync();
if (status === "granted") {
setStartCamera(props);
} else {
Alert.alert("Action impossible", "Demande d'accès");
}
};
const __takePicture = async () => {
if (!camera) return;
const photo = await camera.takePictureAsync({ base64: true });
setPhoto(photo);
const manipResult = await manipulateAsync(photo.uri, [], {
compress: 0,
format: SaveFormat.JPEG,
base64: true,
});
setPhoto(manipResult);
};
Picture display :
<Image
source={{ uri: photo.uri }}
resizeMode="cover"
style={{
width: "80%",
height: "80%",
backgroundColor: "black",
borderWidth: 5,
borderRadius: 10,
}}
/>
Do you know where the problem comes from? Thank you for your time.
Answer provided by Timotius from the Discord Reactiflux server which worked for me: change compress: 0 to compress: 1
Another element that he brings back from their documentation which may prove useful :
"SaveFormat.PNG compression is lossless but slower, SaveFormat.JPEG is faster but the image has visible artifacts. Defaults to SaveFormat.JPEG"
My code is :
import React, { useEffect } from "react";
import * as ImagePicker from "expo-image-picker";
import Screen from "./app/components/Screen";
export default function App() {
async function permisionFunction() {
const result = await ImagePicker.getCameraPermissionsAsync();
if (!result.granted) {
console.log(result);
alert("need access to gallery for this app to work");
}
}
useEffect(() => {
permisionFunction();
}, []);
return <Screen></Screen>;
}
I denied the permissions for camera when it was promted for the first time.
Now whenever I opens the app always need access to gallery for this app to work this message is shown up. for android.
I tried by giving all the permissions to the expo app in settings but still same msg appears.
How can I solve this.
Use expo-cameramodule to access device camera.
I have curated the working example of small app with which you can access pictures from gallery as well as device camera.
Working App: Expo Snack
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Button, Image } from 'react-native';
import { Camera } from 'expo-camera';
import * as ImagePicker from 'expo-image-picker';
export default function Add({ navigation }) {
const [cameraPermission, setCameraPermission] = useState(null);
const [galleryPermission, setGalleryPermission] = useState(null);
const [camera, setCamera] = useState(null);
const [imageUri, setImageUri] = useState(null);
const [type, setType] = useState(Camera.Constants.Type.back);
const permisionFunction = async () => {
// here is how you can get the camera permission
const cameraPermission = await Camera.requestPermissionsAsync();
setCameraPermission(cameraPermission.status === 'granted');
const imagePermission = await ImagePicker.getMediaLibraryPermissionsAsync();
console.log(imagePermission.status);
setGalleryPermission(imagePermission.status === 'granted');
if (
imagePermission.status !== 'granted' &&
cameraPermission.status !== 'granted'
) {
alert('Permission for media access needed.');
}
};
useEffect(() => {
permisionFunction();
}, []);
const takePicture = async () => {
if (camera) {
const data = await camera.takePictureAsync(null);
console.log(data.uri);
setImageUri(data.uri);
}
};
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [1, 1],
quality: 1,
});
console.log(result);
if (!result.cancelled) {
setImageUri(result.uri);
}
};
return (
<View style={styles.container}>
<View style={styles.cameraContainer}>
<Camera
ref={(ref) => setCamera(ref)}
style={styles.fixedRatio}
type={type}
ratio={'1:1'}
/>
</View>
<Button title={'Take Picture'} onPress={takePicture} />
<Button title={'Gallery'} onPress={pickImage} />
{imageUri && <Image source={{ uri: imageUri }} style={{ flex: 1 }} />}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
cameraContainer: {
flex: 1,
flexDirection: 'row',
},
fixedRatio: {
flex: 1,
aspectRatio: 1,
},
button: {
flex: 0.1,
padding: 10,
alignSelf: 'flex-end',
alignItems: 'center',
},
});
It's mention in doc Configuration.
In managed apps, Camera requires Permissions.CAMERA. Video recording requires Permissions.AUDIO_RECORDING.
I have the same problem... I'm using expo SDK 42 and after a denied answer the permissions request does not trigger again anymore.
Anyway, You have some mistakes in your code, you have to watch the status property of the permissions response.
this is how to check the response status
const requestPermissions = async () => {
try {
const {
status,
} = await ImagePicker.requestMediaLibraryPermissionsAsync();
console.log('status lib', status);
setHasPickerPermission(status === 'granted');
} catch (error) {
console.log('error', error);
}
try {
const { status } = await ImagePicker.requestCameraPermissionsAsync();
console.log('status camera', status);
setHasCameraPermission(status === 'granted');
} catch (error) {
console.log('error', error);
}
};
useEffect(() => {
requestPermissions();
}, []);
If the user has denied the camera permission the first time, the second time you request permission with requestCameraPermissionsAsync() the answer will always be "denied" unless the user manually changes the permission in the app settings.
import { Linking } from "react-native";
import { useCameraPermissions } from "expo-image-picker";
export default function App() {
const [status, requestPermissions] = useCameraPermissions();
const requestPermissionAgain = () => {
Linking.openSettings();
}
useEffect(() => {
if (!status?.granted) requestPermissions();
}, []);
}
I’m trying to make a prototype application that over and over
1- record a video with the camera for x seconds
2- displays this video
For this I use the components Camera from expo-camera and Video from expo-av
For this I have two views :
I use in my code the stateSequence property and the sequencer() function which displays alternately the view with the Camera component which films for x seconds , and the video view which allows me to display the video.
Sequencer() is triggered with setInterval( this.sequencer , 10000) found in the componentWillMount()
I can switch alternately from a View with the Camera component to a View with the Video component.
To record a video with the Camera component I use recordAsync(), but I get the following error:
Unhandled promise rejection: Error: Camera is not running
I’m using an android phone for my tests.
Can’t you help me
this is my code
import { StyleSheet, Text, View ,TouchableOpacity} from 'react-native';
import * as Permissions from 'expo-permissions';
import { Camera } from 'expo-camera';
import { Video } from 'expo-av';
import { Logs } from 'expo';
export default class SequenceViewer extends Component {
constructor(props) {
super(props);
this.state = {
stateSequence: "SHOOT ",
hasCameraPermission: null,
type: Camera.Constants.Type.front,
}
this.recordVideo = this.recordVideo.bind(this)
}
sequencer = () => {
if(this.state.stateSequence==="WATCH"){
this.setState({ stateSequence: "SHOOT",})
this.recordVideo(); // Error message Camera is not running
} else {
this.setState({stateSequence: "WATCH"})
}
}
async componentWillMount() {
let rollStatus = await Permissions.askAsync(Permissions.CAMERA_ROLL);
let cameraResponse = await Permissions.askAsync(Permissions.CAMERA)
if (rollStatus.status=='granted'){
if (cameraResponse.status == 'granted' ){
let audioResponse = await Permissions.askAsync(Permissions.AUDIO_RECORDING);
if (audioResponse.status == 'granted'){
this.setState({ permissionsGranted: true });
setInterval( this.sequencer , 10000);
}
}
}
}
recordVideo = async () => {
if(this.state.cameraIsRecording){
this.setState({cameraIsRecording:false})
this.camera.stopRecording();
}
else {
this.setState({cameraIsRecording:true})
if (this.camera) {
let record = await this.camera.recordAsync(quality='480p',maxDuration=5,mute=true).then( data =>{
this.setState( {recVideoUri :data.uri})
})
}
}
};
render() {
const { hasCameraPermission } = this.state
if(this.state.stateSequence=="WATCH")
{
return(
<View style={styles.container}>
<Video
source={{ uri:this.state.recVideoUri }}
rate={1.0}
volume={1.0}
isMuted={false}
resizeMode="cover"
shouldPlay
isLooping
style={{ width: 300, height: 300 }}
ref={(ref) => { this.player = ref }}
/>
</View>
)
} else
{
return(
<View style={{ flex: 1 }}>
<Camera style={{ flex: 1 }} type={this.state.type} ref={ref => {this.camera = ref; }}></Camera>
</View>
)
}
}
}
const styles = StyleSheet.create({
viewerText: {
fontSize: 20,
fontWeight: 'bold',
},
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Thank you
I had the same problem, my solution was by default camera type have to be "back" and you could change to "front" by:
componentDidMount = () => {
this.props.navigation.addListener('didFocus', async () => {
await setTimeout(() => {
this.setState({ cameraType: Camera.Constants.Type.front })
}, 100)
});
}
I was getting the "Camera is not running" error when i changed screens. So for functional components instead of withNavigationFocus(Camera) use this method:
import { useIsFocused } from '#react-navigation/native';
function MyComponent() {
const isFocused = useIsFocused()
return (
<View>
{ isFocused && <RNCamera /> }
</View>
)
}
I am currently working on react-native photo sharing app for Android. Used native share method but it only share message and title. No options to share an image.
Looking after so many questions here couldn't find any straight forward way.
Please provide help.
This is the message I am getting Share awesome status on whatsapp using Khela #imageurl. Download #urltoplaystore
To share any image in React Native you are right you need to use the Share from react-native library itself, and you were wondering what is needed for an image, the answer it's really simple, you just need to use a Base64 image.
Check it out a working snack: snack.expo.io/#abrahamcalf/share-image
Wrap the code:
import * as React from 'react';
import {
Text,
View,
StyleSheet,
Image,
Share,
TouchableOpacity,
} from 'react-native';
export default class App extends React.Component {
state = {
cat: 'data:image/jpeg;base64,some-encoded-stuff;
};
handleSharePress = () => {
Share.share({
title: 'Share',
message: 'My amazing cat 😻',
url: this.state.cat,
});
};
render() {
return (
<View style={styles.container}>
<Image source={{ uri: this.state.cat }} style={styles.img} />
<TouchableOpacity onPress={this.handleSharePress}>
<Text>Share Image</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'space-around',
alignItems: 'center',
},
img: {
width: 200,
height: 300,
},
});
If you want to try something else, probably complex, I recommend to check out the react-native-share library from the React Native Community.
import Icon from 'react-native-vector-icons/Feather';
import Share from 'react-native-share';
import RNFetchBlob from 'rn-fetch-blob';
import React, {Component} from 'react';
const fs = RNFetchBlob.fs;
class ProductDetail extends Component {
constructor(props) {
super(props);
this.state = {};
}
shareTheProductDetails(imagesPath) {
let {productDetails} = this.state;
let imagePath = null;
RNFetchBlob.config({
fileCache: true,
})
.fetch('GET', imagesPath.image)
// the image is now dowloaded to device's storage
.then((resp) => {
// the image path you can use it directly with Image component
imagePath = resp.path();
return resp.readFile('base64');
})
.then((base64Data) => {
// here's base64 encoded image
var imageUrl = 'data:image/png;base64,' + base64Data;
let shareImage = {
title: productDetails.product_name, //string
message:
'Description ' +
productDetails.product_description +
' http://beparr.com/', //string
url: imageUrl,
// urls: [imageUrl, imageUrl], // eg.'http://img.gemejo.com/product/8c/099/cf53b3a6008136ef0882197d5f5.jpg',
};
Share.open(shareImage)
.then((res) => {
console.log(res);
})
.catch((err) => {
err && console.log(err);
});
// remove the file from storage
return fs.unlink(imagePath);
});
}
render() {
return (
<TouchableOpacity
style={{
borderWidth: 0,
left:(5),
top:(2),
}}
onPress={() =>
this.shareTheProductDetails(images)
}>
<Icon
style={{
left: moderateScale(10),
}}
name="share-2"
color={colors.colorBlack}
size={(20)}
/>
</TouchableOpacity>
)}
}
I have requirement where i need to get a random image every time when i click an button. I don't want picker to come up for the camera-roll with images, instead random image should selected from the camera folder and display in the image view.
I have followed the official FB tutorial of camera roll. Please find the code as below
_handleButtonPress = () => {
CameraRoll.getPhotos({
first: 20,
assetType: 'Photos',
})
.then(r => {
this.setState({ photos: r.edges });
})
.catch((err) => {
});
};
But this code will select the recently clicked images and display in the picker. Instead of to randomly select the uri of the image and display in the imageview. Any help is appreciated.
Regards,
Sharath
You essentially have the photos and all the necessary metadata once you set the state: this.setState({ photos: r.edges })
All you have to do is pick a random image from there. Here's how I did it:
import React, { Component } from 'react';
import {
StyleSheet,
View,
Image,
CameraRoll,
Button
} from 'react-native';
export default class App extends Component {
constructor(props) {
super(props)
this.state = {
img: null
}
}
getRandomImage = () => {
const fetchParams = {
first: 25,
}
CameraRoll.getPhotos(fetchParams)
.then(data => {
const assets = data.edges
const images = assets.map((asset) => asset.node.image)
const random = Math.floor(Math.random() * images.length)
this.setState({
img: images[random]
})
})
.catch(err => console.log)
}
render() {
return (
<View style={styles.container}>
{ this.state.img ?
<Image
style={styles.image}
source={{ uri: this.state.img.uri }}
/>
: null
}
<Button title="Get Random Image from CameraRoll" onPress={this.getRandomImage}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
image: {
width: '100%',
height: '75%',
margin: 10,
}
});