在React Native中将远程图像保存到相机胶卷?

nic*_*las 5 react-native

我只得到了ReactNative CameraRoll saveImageWithTag功能的错误.使用以下内容保存本地图像:

CameraRoll.saveImageWithTag('./path/to/myimage.png');
      .then(res => console.log(res))
      .catch(err => console.log(err));
Run Code Online (Sandbox Code Playgroud)

给我错误:

Error: The file “myimage.png” couldn’t be opened because there is no such file.(…)
Run Code Online (Sandbox Code Playgroud)

./path/to/myimage.png在这种情况下是我require用于Image源图像的路径.本地图像的完整路径应该是什么?我是否需要以不同方式存储它们以使其可访问?

Jas*_*Lee 13

简短的回答

使用RNFS查找本地映像.

1.对于你的标题'在React Native中将远程图像保存到相机胶卷'

关键字是remote.

在使用CameraRoll之前,我们应该首先链接库.

在此输入图像描述

然后,我创建一个Image和一个Button:

  render: function() {
    return (
      <View style={styles.container}>
          <Image ref="logoImage"
            style={{ height:50, width: 50 }}
            source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}}
          />
          <TouchableHighlight style={styles.button} onPress={this._handlePressImage} underlayColor='#99d9f4'>
            <Text style={styles.buttonText}>Save Image</Text>
          </TouchableHighlight>
      </View>
    );
  },
Run Code Online (Sandbox Code Playgroud)

当我按下按钮时,程序会将图像保存到相机胶卷:

  _handlePressImage: function() {
    console.log('_handlePressImage.');

    var uri = this.refs.logoImage.props.source;
    console.log(uri);
    CameraRoll.saveImageWithTag(uri, function(result) {
      console.log(result);
    }, function(error) {
      console.log(error);
    });
  },
Run Code Online (Sandbox Code Playgroud)

React Native警告我不推荐使用API​​,只需使用promise:

var promise = CameraRoll.saveImageWithTag(uri);
promise.then(function(result) {
  console.log('save succeeded ' + result);
}).catch(function(error) {
  console.log('save failed ' + error);
});
Run Code Online (Sandbox Code Playgroud)

现在,我们可以在相机胶卷中看到徽标图像.

2.对于您内容中的真实问题

尽管你的标题说remote,你的代码使用local路径.

给出路径'./path/to/myimage.png',我假设图像路径是相对于.js文件.也就是说,您的图像与最终运行的应用程序无关,因此无法找到图像文件.

现在更改Image为使用本地文件:

<Image ref="logoImage"
  style={{ height:50, width: 50 }}
  source={require('./logo_og.png')}
/>
Run Code Online (Sandbox Code Playgroud)

并像这样保存图像:

var promise = CameraRoll.saveImageWithTag('./logo_og.png');
Run Code Online (Sandbox Code Playgroud)

这导致:

在此输入图像描述

因为CameraRoll API是对应的Native Component,属于最终运行的应用程序,而不是javascript.

3.使用RNFS保存本地图像

首先运行以下命令:

npm install react-native-fs --save
Run Code Online (Sandbox Code Playgroud)

然后链接库.

将图像放在Library/Caches:

在此输入图像描述

我们可以保存本地图像:

var cacheImagePath = RNFS.CachesDirectoryPath+"/logo_og.png";
console.log(cacheImagePath);
var promise = CameraRoll.saveImageWithTag(cacheImagePath);
promise.then(function(result) {
  console.log('save succeeded ' + result);
}).catch(function(error) {
  console.log('save failed ' + error);
});
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

谢谢.

  • @JasonLee如何在Android中从远程URL(例如“ http://facebook.github.io/react/img/logo_og.png”)保存图像? (3认同)