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.