2016-06-30 132 views
3

我得到不过从ReactNative CameraRoll的saveImageWithTag功能错误。保存本地图像的东西,如:将React Native中的远程图像保存到相机胶卷中?

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

回答

8

0简短的回答

使用RNFS找到当地的形象。

1.为了您的标题“保存远程图像在相机胶卷阵营原住民”

的关键词是remote

使用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.对于你真正的问题在您的内容

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

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

,然后链接库。

Library/Caches下把图像后:

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

感谢。

+0

很好的回答。谢谢!是的,我发现我可以使用远程URL但忘记更改问题标题。尽管如此,仍在苦苦挣扎着本地文件。我会看看react-native-fs。你使用CachesDirectory而不是DocumentDirectory的任何原因? – nicholas

+0

@nicholas CachesDirectory或DocumentDirectory只是一个例子:) –

+0

谢谢!后续问题:保存动画gif仅保存iOS上的第一帧。照片应用通常不会在任何情况下显示动画,但即使在发送电子邮件或以其他方式分享gif并将其打开后,它似乎只是一个静态gif ...关于发生了什么的任何想法? – nicholas

相关问题