图像的 React-本机本地文件系统存储



作为学习练习,我正在编写一个基于 react-native-cli 的照片应用程序,该应用程序应该在离线模式下工作。我的意思是,应用程序提供了一种使用相机拍照或从内置图库中选择照片并将它们存储在目录路径存储在 realm 数据库中的本地文件系统中的方法。以下是我的堆栈,

System: Ubuntu Linux,
react-native-cli: 2.0.1
react-native: 0.61.4,
realm@3.4.2,
react-native-image-picker@1.1.0

使用 react-native-image-picker,我可以选择一张照片或拍摄一张照片,其详细信息存储在图像选择器的响应对象中, response.data(图像数据(和response.uri

 ImagePicker.showImagePicker(options, (response) => {
  if (response.didCancel) {
    alert('User cancelled image picker');
  } else if (response.error) {
    alert('ImagePicker Error: ', response.error);
  } else {
    const source = { uri: response.uri };
    const sourceData = response.data;
    this.setState({
      imageSourceData: source,
    });
  }
});
In Main.js I've a simple view,
import React, { Component } from 'react';
function Item({ item }) {
  return (
    <View style={{flexDirection: 'row'}}>
      <Text>{item.picureName}</Text>
    </View>
    <Image source={uri: ....????} />   <------------- How this would work?
  )
}
export default class Main extends Component {
  state = {
    size: 0,
    pictureName: null,
    picureLocation: null,
    picureDate: new Date(),
    imageSourceData: '',
    picures: []
  }
  componentDidMount() {
    Realm.open(databaseOptions)
      .then(realm => {
      const res = realm.objects(PICTURE_SCHEMA);
      this.setState({
        pictures: res
      })
    });
  }
  render() {
    return(
      <View>
        <Image source={uri: 'data:image/jpeg;base64,' + this.state.imageSourceData}
           style:{{width: 50, height:50}}/>
        <FlatList
         data={this.state.pictures}
         renderItem={({ item }) => <Item item={item} />}
         keyExtractor={item => item.pictureID}
      >
      </View>
    )
  }
}

我需要执行以下操作,一旦我从图像选择器获取图像,

1(将此数据存储在设备上的文件中并获取文件位置。

2( 将位置与其他元数据一起存储在 Realm 对象中

  saveButton() {
      // Store the imageSourceData into a file on a device,
      // Get the fileLocation
      // update state.picureLocation property 
      this.addOnePicture() 
  }
  addOnePicture() {
    var obj = new Object();
      obj = {
        PicureID: this.state.size + 1;
        PictureName: this.state.pictureName,
        PictureDate: this.state.pictureDate,
        PicureLocation: this.state.picureLocation
      };
    Realm.open(databaseOptions)
      .then(realm => {
        realm.write(() => {
        realm.create(PICTURE_SCHEMA, obj);
        this.setState({ size: realm.objects(PICTURE_SCHEMA).length });
      });
    })
  }

3( 可以读取领域对象列表以在 "componentDidMount(( hook" 中的平面列表中显示数据

这是一个代码片段,但我希望它是清楚的。我非常感谢任何帮助/建议,可能的代码块要做以下工作,

1(如何将数据(imageSourceData(存储到本地文件中,基本上填写saveButton(((我正在考虑使用react-native-fs包。这是个好主意吗?

2( 如何在视图中显示此图像?我是否需要读取在平面列表中呈现的内容?图像语法是什么样的(检查项目组件代码(。

react-native-fs 工作得很好。

最新更新