React Native - 使用CameraRoll将图片保存到本地相册
作者:hangge | 2017-04-06 08:10
React Native 的 CameraRoll API 提供了访问本地相册的功能,本文演示如何使用 CameraRoll 将图片保存到系统相册中。




1,saveToCameraRoll(tag, type?)方法介绍
(1)这个是 CameraRoll 的一个静态方法,作用是保存一张图片到相册。
(2)参数 tag 是图片的地址,为字符串类型。其内容根据不同的设备也有所不同:
- 在 Android 上:tag 是本地地址,例如:"file:///sdcard/img.png"
- 在 iOS 上:tag 可以是 url、assets-library、内存图片中的一种。
(3)参数 type 不是必须的,可选值是'photo' 或 'video'。用来表示存的是图片还是视频。不指定的话程序也会根据后缀自行判断。(结尾为 .mov 或 .mp4 为视频,其它为图片)
2,准备工作
(1)如果要在 iOS 上使用这个模块,我们首先要链接 RCTCameraRoll 库。进入到工程项目中的 node_module/react-native/Libraries/CameraRoll

(2)把 RCTCameraRoll.xcodeproj 添加到在项目工程的 Liberaries 文件夹下

(3)在 Build Phases -> Link Binary With Libraries 里添加 libRCTCameraRoll.a

(4)由于苹果安全策略更新,还需要在 Info.plist 配置请求照片相的关描述字段(Privacy - Photo Library Usage Description)

3,使用样例
(1)效果图
程序启动时会将一张网络图片显示在 Image 组件上。
当点击“保存图片到相册”按钮时,会将这张图片保存到设备相簿中。同时保存成功后还会将存放的 URI 路径给弹出显示。


(2)样例代码
import React, {Component} from 'react'; import { AppRegistry, StyleSheet, Text, View, Image, CameraRoll, } from 'react-native'; //网络图片地址 var imgURL = "http://www.hangge.com/blog/images/logo.png" //默认应用的容器组件 class App extends Component { //渲染 render() { return ( <View style={styles.container}> <View style={styles.image}> <Image style={styles.img} source={{uri: imgURL}} resizeMode="contain" /> </View> <View> <Text onPress={this.saveImg.bind(this, imgURL)} style={[styles.saveImg]}> 保存图片到相册 </Text> </View> </View> ); } //保存图片 saveImg(img) { var promise = CameraRoll.saveToCameraRoll(img); promise.then(function(result) { alert('保存成功!地址如下:\n' + result); }).catch(function(error) { alert('保存失败!\n' + error); }); } } //样式定义 const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 30, alignItems:'center' }, image:{ borderWidth:1, width:300, height:100, borderRadius:5, borderColor:'#ccc' }, img:{ height:98, width:300, }, saveImg:{ height:30, padding:6, textAlign:'center', backgroundColor:'#3BC1FF', color:'#FFF', marginTop:10, } }); AppRegistry.registerComponent('ReactDemo', () => App);
全部评论(1)
你好,之前你的Swift教程帮我度过了Swift的新手期,现在很高兴看到你的RN教程,只不过在存储图片时,有一处报错undefined is not an object(evaluating RCTCameraRoll.saveToCameraRoll),请求指教
已经解决了,重新运行一次就好啦
站长回复:解决了就好 :)