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

2024-02-10

我很困惑,但 React Native CameraRoll 出现错误saveImageWithTag功能。使用以下内容保存本地图像:

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

给我错误:

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

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


0.简答

Use RNFS https://github.com/johanneslumpe/react-native-fs定位本地图像。

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

关键字是remote.

使用前相机胶卷 https://facebook.github.io/react-native/docs/cameraroll.html, 我们应该链接库 https://facebook.github.io/react-native/docs/linking-libraries-ios.html first.

然后,我创建一个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>
    );
  },

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

  _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);
    });
  },

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);
});

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

2.针对您内容中的真正问题

尽管你的标题说remote,您的代码使用local path.

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

现在改变Image使用本地文件:

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

并像这样保存图像:

var promise = CameraRoll.saveImageWithTag('./logo_og.png');

结果是:

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

3. Use RNFS https://github.com/johanneslumpe/react-native-fs保存本地图像

首先运行以下命令:

npm install react-native-fs --save

然后链接库。

将图像放在下面之后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);
});

Thanks.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐