您的位置:首页 > 其它

ionic2图片保存到相册---利用cordova-plugin-photo-library插件

2017-05-18 16:53 639 查看
ionic中很多功能都是可以利用插件完成的,而且简捷方便,此次图片保存到相册就是利用cordova-plugin-photo-library完成的。

官方文档         ionic: https://ionicframework.com/docs/native/photo-library/

                       GitHub:https://github.com/terikon/cordova-plugin-photo-library 或 npm:https://www.npmjs.com/package/cordova-plugin-photo-library



ionic的官方文档只解释了插件安装和每个方法参数。而GitHub的文档和npm文档都是一样的,都对方法之间有比较清晰的逻辑,认真阅读文档就能找到方法!我在此就是整理了一下实现逻辑。

1、安装插件

ionic plugin add cordova-plugin-photo-library --variable PHOTO_LIBRARY_USAGE_DESCRIPTION="To choose photos"

npm install --save @ionic-native/photo-library

2、实现

1、在html中添加点击事件和图片
<ion-content padding>
<img style="width:300px;height:450px" src="http://img.taopic.com/uploads/allimg/140513/235059-14051310145412.jpg" (press)="onHold()">
</ion-content>


press:长按500ms,类似于手势中的长按;
onHold():点击方法。

2、在.ts中添加方法
引入
import { PhotoLibrary } from '@ionic-native/photo-library';

import {ActionSheetController} from 'ionic-angular';


添加如下,使得可用cordova
declare var cordova: any;


点击执行方法

android,会要求用户允许访问存储;ios,会首先打开权限提示。所以,要想修改相册首先要有权限,允许了,才能保存到相册。

流程:首先要请求授权-----requestAuthorization(),用户给了权限可以了,再执行下一步;

           然后处理获取权限------getLibrary,权限获取成功,执行下一步;

           最后图片保存
4000
-----saveImage。

onHold() {
//alert('kkkkkkk');
var imgSrc = "http://img.taopic.com/uploads/allimg/140513/235059-14051310145412.jpg";
this.presentActionSheet(imgSrc);
}
// 弹出选择框
presentActionSheet(imgUrl:string) {
let actionSheet = this.actionSheetCtrl.create({
title: '提示',
buttons: [
{
text: '保存到相册',
role: 'destructive',
handler: () => {
// 保存图片
this.saveImage(imgUrl);
console.log('Destructive clicked');
}
},
{
text: '取消',
role: 'cancel',
handler: () => {
console.log('Cancel clicked');
}
}
]
});
actionSheet.present();
}

saveImage(imgUrl) {
cordova.plugins.photoLibrary.requestAuthorization(
function () {
// User gave us permission to his library, retry reading it!
cordova.plugins.photoLibrary.getLibrary(
function ({library}) {
//var url = 'file:///...'; // file or remote URL. url can also be dataURL, but giving it a file path is much faster
var album = 'myApp';
cordova.plugins.photoLibrary.saveImage(imgUrl, album,
function (libraryItem) {
alert("保存成功"+libraryItem);
}, function (err) {
alert('保存失败'+err);
});
},
function (err) {
if (err.startsWith('Permission')) {
// call requestAuthorization, and retry
}
// Handle error - it's not permission-related
console.log('权限'+err);

}
);
},
function (err) {
// User denied the access
alert('用户拒绝访问'+err);
}, // if options not provided, defaults to {read: true}.
{
read: true,
write: true
}
);

}


其中图片的URL是外部传入,album就是自己APP的名字。



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: