How To Use Camera Native in Ionic 3

How To Create Bootable Pen Drive with Command Prompt
September 13, 2018
On Page SEO Update for 2019
February 18, 2019

How To Use Camera Native in Ionic 3

1. Installing Ionic and Cordova

2. First of all Create a project in ionic 3
follow Steps

npm install -g cordova ionic
ionic start --v2 YourAppName tabs
cd YourAppName
npm install
ionic serve

3. Stop Your project “Ctrl C” and run this command

ionic cordova plugin add cordova-plugin-camera
npm install --save @ionic-native/camera

5. import Ionic camera module in your project src/app/app.module.ts

import {Camera} from '@ionic-native/camera'; 

6. add Camera in providers

providers: [
Camera
]

6. Add Html in src/pages/home/home.html

<button ion-button full (click)=”takePhoto()” >
<ion-icon name=”camera”></ion-icon>Take Photo
</button>

<ion-col>
<ion-card>
<ion-icon name=”trash” (click)=”deletePhoto()”></ion-icon>
<img *ngIf=”base64Image” [src]=”base64Image” />
<img *ngIf=”!base64Image” src=”assets/imgs/camera.png” (click)=”takePhoto()” />
</ion-card>
</ion-col>

home.ts
Now modify home module, here imported ionic camera module. Include functions for takePhoto and deletePhoto.

import {Camera, CameraOptions} from '@ionic-native/camera';
import { AlertController } from 'ionic-angular';

export class HomePage add this line

public base64Image : string;

Modify Home Constructor Call camera and alert module in constructor

constructor(public navCtrl : NavController, private camera : Camera,private alertCtrl: AlertController) {
}

Take Photo This function will help you to capture mobile camera snap

takePhoto() {
const options : CameraOptions = {
quality: 50, // picture quality
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options) .then((imageData) =&gt; {
this.base64Image = "data:image/jpeg;base64," + imageData;
}, (err) =&gt; {
console.log(err);
});
}

Deleting photo with alert confirmation.

deletePhoto() {
let confirm = this.alertCtrl.create({
title: 'Sure you want to delete this photo? There is NO undo!',
message: '',
buttons: [
{
text: 'No',
handler: () =&gt; {
console.log('Disagree clicked');
}
}, {
text: 'Yes',
handler: () =&gt; {
console.log('Agree clicked');
this.base64Image = ' ' ;
}
}
]
});
confirm.present();
}

save the file and see the camera in your app

Leave a Reply