1. service里面这样写
import {Camera} from '@ionic-native/camera'
/**
* 使用cordova-plugin-camera获取照片的base64
*@paramoptions
*/
getPicture=(options)=>{
returnnewPromise((resolve,reject)=>{
this.camera.getPicture(Object.assign({
sourceType:this.camera.PictureSourceType.CAMERA,//图片来源,CAMERA:拍照,PHOTOLIBRARY:相册
destinationType:this.camera.DestinationType.DATA_URL,//返回值格式,DATA_URL:base64,FILE_URI:图片路径
quality:90,//保存的图像质量,范围为0 - 100
allowEdit:true,//选择图片前是否允许编辑
encodingType:this.camera.EncodingType.JPEG,
targetWidth:800,//缩放图像的宽度(像素)
targetHeight:800,//缩放图像的高度(像素)
saveToPhotoAlbum:false,//是否保存到相册
correctOrientation:true//设置摄像机拍摄的图像是否为正确的方向
},options)).then((imageData)=>{
resolve(imageData);
}, (err)=>{
console.log(err);
err==20?this.showToast('没有权限,请在设置中开启权限'):reject(err);
});
});
};
/**
* 通过图库获取照片
*@paramoptions
*/
getPictureByPhotoLibrary=(options={})=>{
returnnewPromise((resolve)=>{
this.getPicture(Object.assign({
sourceType:this.camera.PictureSourceType.PHOTOLIBRARY
},options)).then(imageBase64=>{
resolve(imageBase64);
}).catch(err=>{
String(err).indexOf('cancel')!=-1?this.showToast('取消选择图片',1500):this.showToast('获取 照片失败');
});
});
};
/**
* 通过拍照获取照片
*@paramoptions
*/
getPictureByCamera=(options={})=>{
returnnewPromise((resolve)=>{
this.getPicture(Object.assign({
sourceType:this.camera.PictureSourceType.CAMERA
},options)).then(imageBase64=>{
resolve(imageBase64);
}).catch(err=>{
String(err).indexOf('cancel')!=-1?this.showToast('取消拍照',1500):this.showToast('获取照片失败');
});
});
};
2. **.ts
/**
*--------- 图片上传,相册选择,保存 ---------
*/
isChange:boolean=false;// 头像是否改变标识
avatarPath:string='http://pic.qiantucdn.com/58pic/14/86/69/17F58PICNfK_1024.jpg!/fw/780/watermark/url/L3dhdGVybWFyay12MS4zLnBuZw==/align/center';// 用户默认头像
imageBase64:string;// 保存头像base64,用于上传
isShowSave:boolean=false;
// 2017/10/23
getPicture(type) { // 1拍照,0从图库选择
letoptions={
targetWidth:350,
targetHeight:220,
quality:100
};
if(type===1) {
this.nativeService.getPictureByCamera(options).then(imageBase64=>{
this.getPictureSuccess(imageBase64);
this.isShowSave=true;
});
}else{
this.nativeService.getPictureByPhotoLibrary(options).then(imageBase64=>{
this.getPictureSuccess(imageBase64);
this.isShowSave=true;
});
}
}
privategetPictureSuccess(imageBase64) {
this.isChange=true;
this.imageBase64=imageBase64;
this.avatarPath='data:image/jpeg;base64,'+imageBase64;
}
saveAvatar() {
if(this.isChange) {
alert(this.imageBase64);//这是头像数据.
this.nativeService.showLoading('正在上传....');
// this.viewCtrl.dismiss({avatarPath: this.avatarPath}); // 这里可以把头像传出去.
}else{
this.dismiss();
}
}
// 2017/10/20
presentActionSheet() {
constactionSheet=this.actionSheetCtrl.create({
title:'选择上传',
buttons:[
{
text:'相册选择',
handler:()=>{
this.getPicture(0);
}
},
{
text:'拍照',
handler:()=>{
this.getPicture(1)
}
},
{
text:'取消',
role:'cancel',
handler:()=>{
console.log('Cancel clicked');
}
}
]
});
actionSheet.present();
}
3.HTML
// 上传店铺首图