参考了很多网上的资料,但是每个人遇到的问题都不一样,我这里出现的问题,可能是node版本,还有插件版本之类的问题,问题以及解决方式可以看这个图。
一、插件依赖引入
(1)配置相机
在控制行输入命令:
ionic cordova plugin add cordova-plugin-camera
npm install --save @ionic-native/camera
在app.module.ts问价中配置信息
import {Camera,CameraOptions} from '@ionic-native/camera';
然后注册依赖即可
providers: [
Camera
]
(2)保存数据到指定相册中
$ ionic cordova plugin add cordova-plugin-photo-library --variable PHOTO_LIBRARY_USAGE_DESCRIPTION="To choose photos"
$ npm install --save @ionic-native/photo-library
(3)从相册中获取
$ ionic cordova plugin add cordova-plugin-telerik-imagepicker --variable PHOTO_LIBRARY_USAGE_DESCRIPTION="your usage message"
$ npm install --save @ionic-native/image-picker
import {ImagePicker, ImagePickerOptions} from "@ionic-native/image-picker";
二、组件使用
在需要用到的文件中这样使用调用插件
responseActionEvent() {
let actionSheet = this.actionSheetCtrl.create({
buttons: [{
text: '拍照',
role: 'takePhoto',
handler: () => {
this.takePhoto();
}
}, {
text: '从相册选择',
role: 'chooseFromAlbum',
handler: () => {
this.chooseFromAlbum();
}
}, {
text: '取消',
role: 'cancel',
handler: () => {
console.log("cancel");
}
}]
});
actionSheet.present().then(value => {
return value;
});
}
// 照相
takePhoto() {
const options: CameraOptions = {
//图片质量,越高质量越好(0~100)
quality: 100,
//允许编辑
allowEdit: true,
targetWidth: 200,
targetHeight: 200,
//是否允许保存到相册
saveToPhotoAlbum: true,
//图片路径
destinationType:this.camera.DestinationType.FILE_URI,
//媒体类型,图片、视频等
mediaType:this.camera.MediaType.PICTURE,
};
this.camera.getPicture(options).then(imageURI => {
let base64Image = 'data:image/jpeg;base64,' + imageURI;
alert(base64Image);
console.log('Image URI: ' + imageURI);
this.avatar = imageURI.slice(7);
}, error => {
console.log('Error: ' + error);
alert("版本不兼容,从相册选择!");
});
}
// 从相册中选择
chooseFromAlbum() {
const options: ImagePickerOptions = {
maximumImagesCount: 1,
width: 200,
height: 200
};
this.imagePicker.getPictures(options).then(images => {
if (images.length > 1) {
this.presentAlert();
} else if (images.length === 1) {
console.log('Image URI: ' + images[0]);
this.avatar = images[0].slice(7);
}
}, error => {
console.log('Error: ' + error);
});
}
presentAlert() {
let alert = this.alertCtrl.create({title: "上传失败", message: "只能选择一张图片作为头像哦", buttons: ["确定"]});
alert.present().then(value => {
return value;
});
}
//保存照片
saveImage() {
const actionSheet = this.actionSheetCtrl.create({
title: '提示',
buttons: [
{
text: '保存本地',
handler: () => {
//1、请求用户授权
this.photoLibrary.requestAuthorization().then(() => {
//2、授权成功
this.photoLibrary.getLibrary().subscribe(
{
next: library => {
library.forEach(function (libraryItem) { });
//3、保存图片
this.photoLibrary.saveImage(ImageUrl图片的url, '相册名字').then(() => {
alert('保存成功')
})
},
error: err => {
alert('保存失败!')
},
complete: () => {
console.log('没有获取图片信息');
}
});
})
.catch(err => alert('获取失败!'));
}
},
{
text: '取消',
role: 'cancel'
}
]
})
actionSheet.present();
}
如有不懂,推荐查阅文章:https://segmentfault.com/a/1190000011099097