前言
因为APP里面有一个类似于朋友圈的功能,需要给用户提供拍照或者选择本地照片然后发布的能力,我们今天就来讲一下如何在Ionic2 APP中实现调用本地摄像头的功能。不过注意,因为是涉及到客户端的,单纯的网页版是没有权限完成该功能的,所以本功能只有在Android或iOS客户端版本才可以用。
步骤
1、按照惯例安装Cordova插件
Image Picker(相册选择)
ionic plugin add https://github.com/Telerik-Verified-Plugins/ImagePicker
Camera(拍照)
ionic plugin add cordova-plugin-camera
Transfer(上传文件)
ionic plugin add cordova-plugin-file-transfer
2、通过摄像头上传文件的函数
//
// upload imgs by native camera
uploadImgsByNativeCamera(type) {
let options = {
quality: 60,
saveToPhotoAlbum: true,
sourceType: 1,
mediaType: 0,
targetWidth: 1200,
targetHeight: 1600,
};
if (type === 'library') {
options.quality = 100;
options.saveToPhotoAlbum = false;
options.sourceType = 0;
options.mediaType = 2;
}
Camera.getPicture(options).then((result) => {
this.waiting = true;
this.heyApp.utilityComp.presentLoading();
console.log('the file', result);
this.uploadFileByFileTransfer(result, this.heyApp.fileUploadService.imageUploadAPI);
}, (err) => {
console.log('Camera getPictures err', err);
});
}
//
// upload imgs by file transfer
uploadFileByFileTransfer(file, api) {
const fileTransfer = new Transfer();
let options: any;
options = {
fileKey: 'file',
fileName: file.replace(/^.*[\\\/]/, ''),
headers: {},
}
fileTransfer.upload(file, api, options)
.then((ret) => {
this.waiting = false;
this.heyApp.utilityComp.dismissLoading();
let result = [{"uri": ret.response}];
// merge imgs
this.mergeImgs(result);
}, (err) => {
this.heyApp.utilityComp.dismissLoading();
this.waiting = false;
})
}
3、通过选择本地相册上传文件的函数
//
// upload imgs by native library
uploadImgsByNativeLibrary() {
let options = {
width: 1200,
height: 1600,
};
ImagePicker.getPictures(options).then((results) => {
this.waiting = true;
for (var i = 0; i < results.length; i++) {
this.heyApp.utilityComp.presentLoading();
this.uploadFileByFileTransfer(results[i], this.heyApp.fileUploadService.imageUploadAPI);
}
}, (err) => {
console.log('ImagePIcker getPictures err', err);
});
}
//
// upload imgs by file transfer
uploadFileByFileTransfer(file, api) {
const fileTransfer = new Transfer();
let options: any;
options = {
fileKey: 'file',
fileName: file.replace(/^.*[\\\/]/, ''),
headers: {},
}
fileTransfer.upload(file, api, options)
.then((ret) => {
this.waiting = false;
this.heyApp.utilityComp.dismissLoading();
let result = [{"uri": ret.response}];
}, (err) => {
this.heyApp.utilityComp.dismissLoading();
this.waiting = false;
})
}
4、业务逻辑只需要调用以上两个函数便可实现拍照上传的功能
最后
如果有兴趣,可以自己动手做一个图片裁剪的功能。
网友评论