In this Ionic 5/4 tutorial, we are going to discuss how to add a floating camera window/ preview which can be switched for front or rear camera with multiple camera filters in Ionic Angular application using Cordova and Native Plugins.
Ionic’s Camera Preview Native plugin provides an awesome floating Camera view on the component in application pages itself without leaving & even opening the Camera application.
The Camera Preview plugin provides native features of a camera that can be easily controlled using built-in class methods.
- Switch FRONT / BACK camera
- Turn On/Off/Autoflash
- Camera Effects;
none
|aqua
|blackboard
|mono
|negative
|posterize
|sepia
|solarize
|whiteboard
- Control Zoom; From 1 to 100
- Floating Camera of defined Height and Width
- Background Camera on page view
- Draggable Floating Camera
and many more …
[lwptoc]
Let’s start and create an awesome app
Install/ Update Ionic CLI
Make sure you have installed the latest version of Ionic CLI or update existing by running the following command
$ npm install -g @ionic/cli
Create an Ionic 5 Angular Application
To create a new Ionic 5 application, you can run $ ionic start which will as further configuration options.
Or run following command with name, template, and framework like Angular or React provided in <span class="lang:js decode:true crayon-inline ">--type</span>Â
option:
$ ionic start ionic-camera-preview-app blank --type=angular
After successfully creating, just move to the application’s root by running
$ cd ionic-camera-preview-app
To open the app in Visual Studio Code IDE, run the <span class="lang:js decode:true crayon-inline ">code .</span>
 command
Install Camera Preview Plugin
To use Camera we need to install the Cordova plugin and Native wrapper for Ionic. Run following commands one by one at project’s root
$ ionic cordova plugin add cordova-plugin-camera-preview
$ npm install @ionic-native/camera-preview
Update App Module
Import the CameraPreview
class to app.module.ts then add in the providers
array:
// app.module.ts
...
import { CameraPreview } from '@ionic-native/camera-preview/ngx';
@NgModule({
...
providers: [
...
CameraPreview,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
Adding Camera Preview
Now we’ll add the Camera Preview functionality on the Home page. Update the Home page component class and its template HTML
Update Home Page Template
In the component HTML template, we will add some buttons, slider, and select controls to use Camera features. Update the home.page.html file content with the following code:
<!-- home.page.html -->
<ion-header [translucent]="true">
<ion-toolbar>
<ion-title>
Ionic 5 Camera Preview App
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content [fullscreen]="true" [ngClass]="{'custom-ion-content': isToBack}">
<ion-grid>
<ion-row>
<ion-col>
<ion-button color="primary" (click)="startCameraAbove()">Start Front</ion-button>
</ion-col>
<ion-col>
<ion-button color="primary" (click)="startCameraBelow()">Start Back</ion-button>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<ion-button color="danger" (click)="stopCamera()">Stop Camera</ion-button>
</ion-col>
<ion-col>
<ion-label>Color Effect:</ion-label>
<ion-select interface="popover" placeholder="Select Effect" [(ngModel)]="colorEffect"
(ionChange)="changeColorEffect()">
<ion-select-option value="none">none</ion-select-option>
<ion-select-option value="aqua">aqua</ion-select-option>
<ion-select-option value="blackboard">blackboard</ion-select-option>
<ion-select-option value="mono">mono</ion-select-option>
<ion-select-option value="negative">negative</ion-select-option>
<ion-select-option value="posterize">posterize</ion-select-option>
<ion-select-option value="sepia">sepia</ion-select-option>
<ion-select-option value="solarize">solarize</ion-select-option>
<ion-select-option value="whiteboard">whiteboard</ion-select-option>
</ion-select>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<ion-button color="success" (click)="takePicture()">Take Picture</ion-button>
</ion-col>
<ion-col>
<ion-button color="warning" (click)="switchCamera()">Switch</ion-button>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<ion-button color="danger" (click)="hide()">Hide</ion-button>
</ion-col>
<ion-col>
<ion-button color="tertiary" (click)="show()">Show</ion-button>
</ion-col>
<ion-col>
<ion-button color="primary" (click)="showSupportedPictureSizes()">Supported Sizes</ion-button>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<ion-label>Flash:</ion-label>
<ion-select interface="popover" placeholder="Select Flash" [(ngModel)]="flashMode"
(ionChange)="changeFlashMode()">
<ion-select-option value="off">Off</ion-select-option>
<ion-select-option value="on">On</ion-select-option>
<ion-select-option value="auto">Auto</ion-select-option>
<ion-select-option value="torch">Torch</ion-select-option>
</ion-select>
</ion-col>
<ion-col>
<ion-label>Zoom:</ion-label>
<ion-range min="1" max="100" pin color="secondary" [(ngModel)]="setZoom" (ionChange)="changeZoom()">
<ion-icon slot="start" size="small" name="search-outline"></ion-icon>
<ion-icon slot="end" name="search-outline"></ion-icon>
</ion-range>
</ion-col>
</ion-row>
<ion-row *ngIf="IMAGE_PATH">
<ion-col>
<img [src]="IMAGE_PATH">
</ion-col>
</ion-row>
</ion-grid>
</ion-content>
The ion-content
element is having ngClass
directive to add the 'custom-ion-content'
class when isToBack
is true
.
Update Home Page Class
Let’s update the home.page.ts file with the following code:
// home.page.ts
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { CameraPreview } from '@ionic-native/camera-preview/ngx';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss']
})
export class HomePage implements OnInit {
smallPreview: boolean;
IMAGE_PATH: any;
colorEffect = 'none';
setZoom = 1;
flashMode = 'off';
isToBack = false;
constructor(
private cameraPreview: CameraPreview
) { }
ngOnInit() {
}
startCameraAbove() {
this.cameraPreview.stopCamera().then(() => {
this.isToBack = false;
this.cameraPreview.startCamera({ x: 80, y: 450, width: 250, height: 300, toBack: false, previewDrag: true, tapPhoto: true });
})
}
startCameraBelow() {
this.cameraPreview.stopCamera().then(() => {
this.isToBack = true;
this.cameraPreview.startCamera({ x: 0, y: 50, width: window.screen.width, height: window.screen.height, camera: "front", tapPhoto: true, previewDrag: false, toBack: true });
})
}
stopCamera() {
this.cameraPreview.stopCamera();
}
takePicture() {
this.cameraPreview.takePicture({
width: 1280,
height: 1280,
quality: 85
}).then((imageData) => {
this.IMAGE_PATH = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
console.log(err);
this.IMAGE_PATH = 'assets/img/test.jpg';
});
}
switchCamera() {
this.cameraPreview.switchCamera();
}
show() {
this.cameraPreview.show();
}
hide() {
this.cameraPreview.hide();
}
changeColorEffect() {
this.cameraPreview.setColorEffect(this.colorEffect);
}
changeFlashMode() {
this.cameraPreview.setFlashMode(this.flashMode);
}
changeZoom() {
this.cameraPreview.setZoom(this.setZoom);
}
showSupportedPictureSizes() {
this.cameraPreview.getSupportedPictureSizes().then((sizes) => {
console.log(sizes);
}, (err) => {
console.log(err);
});
}
}
In the above code, there are methods to control Camera settings.
The startCameraAbove()
 method is called with provided configuration define position and height, width of Camera Preview in page.
When toBack
is false, floating Camera Preview is shown. The previewDrag
enables draggable Preview in page. The tapPhoto
option will capture a photo on tap on the preview.
The startCameraAbove
and startCameraBelow
can be called after calling stopCamera
method.
The takePicture
method takes the Picture event if Preview is the background.
The switchCamera
Switches between rear and front camera.
Add SCSS Style
In the global.scss file at application root add the following style:
.custom-ion-content{
--background:transparent;
}
This will turn the home page background to transparent to view the Camera as a background.
Run Application on Real Device
We are done with Camera Preview implementation, you need to run this application on a real device to use camera feature. You can run your application in a real device by running following command for Android:
$ ionic cordova run android -l
You need to connect your phone with USB debug mode.
Source Code
Find the source code of this application in my GitHub repository here.
Conclusion
Finally, we have implemented the Camera Preview functionality using Cordova and Native plugins. This adds an awesome feature for a user to access device camera floating on the page with lots of cool features without even leaving the application
Hope you enjoyed this tutorial, do share with your friends. Please share your suggestions and feedback in the comment section or directly contact us.
Stay connected keep reading …
Leave a Reply