加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:16:22 所属栏目:百科 来源:网络整理
导读:我只得到了ReactNative CameraRoll的save ImageWithTag函数的错误.使用以下内容保存本地图像: CameraRoll.saveImageWithTag('./path/to/myimage.png'); .then(res = console.log(res)) .catch(err = console.log(err)); 给我错误: Error: The file “myima
我只得到了ReactNative CameraRoll的save ImageWithTag函数的错误.使用以下内容保存本地图像:

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是我用来要求Image源图像的路径.本地图像的完整路径应该是什么?我是否需要以不同方式存储它们以使其可访问?

解决方法

简短的回答

使用RNFS找到本地图像.

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

关键字是远程的.

在使用CameraRoll之前,我们应该先link the library.

enter image description here

然后,我创建一个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.对于您内容中的真实问题

尽管您的标题是远程的,但您的代码使用本地路径.

给出路径’./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');

这导致:

enter image description here

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

3.使用RNFS保存本地图像

首先运行以下命令:

npm install react-native-fs --save

然后链接库.

将图像放在库/缓存之后:

enter image description here

我们可以保存本地图像:

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

enter image description here

谢谢.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读