React Native - 相机和图像库 - 无工作

问题描述 投票:0回答:1

我在使用任何类型的相机和图片库选择器时遇到问题?我正在运行最新版本的 expo CLI。

当我创建一个新项目时,它不会自动包含任何 IOS 或 ANDROID 文件夹,因此我没有地方放置任何权限(如果必须这样做?)

我几乎尝试了所有教程,但没有一个起作用。

我需要知道的是实现这一目标的最简单方法是什么以及使用什么方法。另外,如果我必须添加权限,该怎么做。

我见过很多人遇到这个问题,但没有真正的解决方案。

谢谢

react-native camera react-native-image-picker expo-camera
1个回答
0
投票

感谢迈克尔的帮助和几个小时的研究,我已经成功地让它工作了,而且比我想象的要容易,而且代码比我尝试过的少得多!仅在 IOS 上进行了测试,但现在可以轻松合并到个人资料页面等内容中。如果其他人也遇到同样的问题,希望它能有所帮助。

完整代码:

import React, { useState, useEffect } from 'react';
import { Button, Image, View, Platform } from 'react-native';
import * as ImagePicker from 'expo-image-picker';

export default function ImagePickerExample() {
  const [image, setImage] = useState(null);


  const pickImage = async () => {
    
    // No permissions request is necessary for launching the image library
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    console.log(result);

    if (!result.canceled) {
      setImage(result.assets[0].uri);
    }
  };

const openCamera = async () => {
// Ask the user for the permission to access the camera
const permissionResult = await ImagePicker.requestCameraPermissionsAsync();

if (permissionResult.granted === false) {
  alert("You've refused to allow this appp to access your camera!");
  return;
}

    let result = await ImagePicker.launchCameraAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

console.log(result);
setImage(result.assets[0].uri);

if (!result.cancelled) {
  setPickedImagePath(result.uri);
  console.log(result.uri);
}
}

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="Pick an image from camera roll" onPress={pickImage} />

      <Button title="Camera" onPress={openCamera} />
       {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
    </View>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.