3

I am new to react-native. I have created an app. but now I want to Capture Image from this app. I have got the code from expo website But the problem is This code only open camera. I want to capture An Image Through That camera. So if it is possible please help me..

here is my code

import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import { Camera } from 'expo-camera';
import { Ionicons } from '@expo/vector-icons';

export default function App({navigation}) {
  const [hasPermission, setHasPermission] = useState(null);
  const [type, setType] = useState(Camera.Constants.Type.back);

  useEffect(() => {
    (async () => {
      const { status } = await Camera.requestPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);

  if (hasPermission === null) {
    return <View />;
  }
  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }
  return (
    <View style={styles.container}>
        
      <View style={styles.header}>
        <Ionicons style={{paddingLeft:20}} name="arrow-back" size={40} 
        color="black"  onPress={() => navigation.navigate("OtherInfo")} />
        <Text style={{fontSize:20, paddingLeft: 70, paddingTop: 10}}>Get Image</Text>
      </View>

      <Camera style={styles.camera} type={type}>
        <View style={styles.buttonContainer}>
          <TouchableOpacity
            style={styles.button}
            onPress={() => {
              setType(
                type === Camera.Constants.Type.back
                  ? Camera.Constants.Type.front
                  : Camera.Constants.Type.back
              );
            }}>
            <Text style={styles.text}> Flip </Text>
          </TouchableOpacity>
        </View>
      </Camera>
    </View>
  );
}


const styles = StyleSheet.create({
    camera:{
        height:500
    },
    header:{
      flexDirection: 'row'
    }
    });

1 Answers1

8

Here is the working Example of the small app which takes the picture from Camera as well as Gallary and shows it to after it is clicked or selected

Working App: Expo Snack

enter image description here

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.requestCameraPermissionsAsync();

    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.All,
      allowsEditing: true,
      aspect: [1, 1],
      quality: 1,
      presentationStyle: 0
    });

    console.log(result);
    if (!result.canceled) {
      setImageUri(result.assets[0].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',
  },
});
Anthony phillips
  • 152
  • 3
  • 13
Ketan Ramteke
  • 10,183
  • 2
  • 21
  • 41
  • One more question. Can I remove that cropping image option from gallery images I mean can I select full image from gallery without croping it –  Feb 02 '21 at 10:18
  • 1
    You can, Just remove the aspect ratio option from ```pickImage``` function. – Ketan Ramteke Feb 02 '21 at 10:21
  • Ok Thanku Its Worked. One More I want to save 3 images in my app. So how could I do that . I have created a separate page for that. and now I want that when user click on Take picture button Then Images will be saved in that screen in small small ration. please. if you dont mind –  Feb 02 '21 at 10:25
  • 1
    just make a state which stores an array of images, and when the pickImage is ran, add the newly selected image in that array(state). Simple. – Ketan Ramteke Feb 02 '21 at 10:27
  • Ok I will try Thanks>> –  Feb 02 '21 at 10:29
  • If You Are free Now Can You Edit Above Code For that Please if You dont mind –  Feb 02 '21 at 10:34
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/228146/discussion-between-ketan-ramteke-and-sohil-shaikh). – Ketan Ramteke Feb 02 '21 at 10:36
  • please check it => https://stackoverflow.com/questions/66009837/how-to-captured-and-then-save-those-images-in-react-native-app-it-self –  Feb 02 '21 at 12:36
  • 1
    posted the answer with upadated code. do check out. – Ketan Ramteke Feb 03 '21 at 07:12