對於 Ionic 3 例子
安裝 Cordova 和 Ionic Native 外掛:
$ ionic cordova plugin add cordova-plugin-camera
$ npm install --save @ionic-native/camera
你的 app.module.ts
需要注入相機:
import { Camera } from '@ionic-native/camera';
..........
@NgModule({
declarations: [
MyApp
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
...........
],
bootstrap: [IonicApp],
entryComponents: [
MyApp
],
providers: [
StatusBar,
SplashScreen,
Camera,
{provide: ErrorHandler, useClass: IonicErrorHandler},
..........
]
})
export class AppModule {}
使用 Ionic 3 可輕鬆將相機與 Action 表一起使用,你的 page.ts 將如下所示:
import { Camera, CameraOptions } from '@ionic-native/camera';
.........
export class YourPage {
private base64:any;
constructor(private camera: Camera,private actionsheetCtrl: ActionSheetController) { }
cameragalleryfun(){
let actionSheet = this.actionsheetCtrl.create({
title: 'Camera-Gallery',
cssClass: 'action-sheets-basic-page',
buttons: [
{
text: 'Camera',
icon: 'camera',
handler: () => {
//console.log('Camera');
const options: CameraOptions = {
quality: 60,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType : this.camera.PictureSourceType.CAMERA,
targetWidth: 500,
saveToPhotoAlbum: false,
correctOrientation:true
}
this.camera.getPicture(options).then((imageData) => {
this.base64 = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
},
{
text: 'Gallery',
icon: 'images',
handler: () => {
//console.log('Gallery');
const options: CameraOptions = {
quality: 60,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType : this.camera.PictureSourceType.PHOTOLIBRARY,
targetWidth: 500,
saveToPhotoAlbum: false,
correctOrientation:true
}
this.camera.getPicture(options).then((imageData) => {
this.base64 = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
},
{
text: 'Cancel',
role: 'cancel', // will always sort to be on the bottom
icon: 'close',
handler: () => {
//console.log('Cancel clicked');
}
}
]
});
actionSheet.present();
}
}
從任何事件呼叫 cameragalleryfun
函式,如點選按鈕,這將返回影象的 base64 字串。可以應用更多選項。有關額外選項,請參閱: https : //github.com/apache/cordova-plugin-camera