首页 > 解决方案 > 如何在 React Native 中显示 expo 相机的图像

问题描述

我正在应用程序中的相机上工作,我已经拍照并转换为 base64 现在我想显示图像但无法显示图像。有人可以帮助我如何实现这个目标。

谢谢

  takePicture = async () => {
    if (this.camera) {
        let photo = await this.camera.takePictureAsync({
            base64: true,
        });
        this.props.cameraToggle(false);
        this.props.image(photo)
        console.log('@@@ take picutre', photo)
    }
}

我要渲染的图像代码

<Image source={{uri:`data:image/png;base64,${cameraImage}`}} style={{width:100,height:100}}/>

标签: javascriptreactjsreact-nativeecmascript-6expo

解决方案


我假设您正在使用基于类的组件。您可以通过将响应设置为本地状态并有条件地渲染它来渲染image从中捕获的内容。cameraphoto

import React from "react";
import { Image } from "react-native";
import { Camera } from "expo-camera";
import Constants from "expo-constants";
import * as ImagePicker from "expo-image-picker";
import * as Permissions from "expo-permissions";

class Cameras extends React.Component(props) {
  state = {
    captures: "",
  };

  takePicture = async () => {
    if (this.camera) {
      let photo = await this.camera.takePictureAsync({
        base64: true,
      });
      this.props.cameraToggle(false);
      this.setState({ captures: photo.uri });
    }
  };

  render() {
    const { captures } = this.state;
    return (
      <View flex={1}>
        {this.state.captures ? (
          <Image source={{ uri: captures }} style={{width:50,height:50}} />
        ) : (
          <Camera {...pass in props} />
        )}
      </View>
    );
  }
}

export default Cameras;

注意: 更简洁的方法是captures通过导航不同的屏幕并在该屏幕上渲染图像来将状态作为路由参数传递。


推荐阅读