Ionic 5|4 Adding Camera using Native plugin in Ionic Application

In this Ionic 5 tutorial, we’ll discuss how to use Native Camera feature in an Ionic application and get pictures returning images as Base64 URL to show user Image taken.

Hybrid applications are very quick to build but sometimes it becomes challenging to achieve some features which involve access to hardware like GPS, Network, Storage, File Storage, Camera. Cordova comes in charge to provide plugins to make a connection with java libraries to use them.

We have already discussed How to access the camera in Ionic’s version 3, in this article we will use Camera feature in Ionic application with the latest version 5 using Cordova and Ionic Native

 

 

Let’s start…

Version Check

The current version of @ionic/cli  is 6.4.1

 

Create a new Ionic 5 Application

We will create an application using the latest version of Ionic CLI v6.4.1

Make sure you have installed the latest version by running following npm command

$ npm install -g @ionic/cli</pre>
After updating the Ionic CLI run following command to create a new Angular Ionic 5 application with a <em>blank</em> template.
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ ionic start Ionic5Camera blank --type=angular</pre>
<h2></h2>
<h2>Install Cordova and Native Camera Plugin</h2>
Next, run following Cordova and Ionic Native commands to install camera plugin to access camera features.
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ ionic cordova plugin add cordova-plugin-camera
$ npm install @ionic-native/camera</pre>
If using CAPACITOR run following command instead:
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ npm install cordova-plugin-camera
$ npm install @ionic-native/camera
$ ionic cap sync</pre>
 

<strong>For IOS</strong>: Add following configuration in <strong>config.xml</strong> inside of the <span class="lang:js decode:true crayon-inline"><platform name='ios></span>  section as IOS 10 asks for camera permission.
<pre class="wp-block-prismatic-blocks"><code class="language-javascript"><config-file parent="NSCameraUsageDescription" platform="ios" target="*-Info.plist">
<string>You can take photos</string>
</config-file></pre>
 
<h2>Import Camera Plugin in App Module</h2>
To use camera plugin in the application we will import it then add in the <code>providers array.

Navigate to app.module.ts file then replace the below code in it.
//app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

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

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    Camera,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

we are done with configuration.

Use the Camera in Home Component

In the blank template we already have home component, add a button in home.page.html file to open the camera by calling takeSnap() method in (click) event handler

  <ion-button (click)="takeSnap()">
    Take Snap
  </ion-button>

  <img [src]="capturedSnapURL" /></pre>
<code><img> tag will show the Image clicked using the camera.

Now open the home.page.ts file, then replace the following code in it.
//home.page.ts
import { Component } from '@angular/core';

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

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  capturedSnapURL:string;

  cameraOptions: CameraOptions = {
    quality: 20,
    destinationType: this.camera.DestinationType.DATA_URL,
    encodingType: this.camera.EncodingType.JPEG,
    mediaType: this.camera.MediaType.PICTURE
  }

  constructor(private camera: Camera) { }

  takeSnap() {
    this.camera.getPicture(this.cameraOptions).then((imageData) => {
      // this.camera.DestinationType.FILE_URI gives file URI saved in local
      // this.camera.DestinationType.DATA_URL gives base64 URI
      
      let base64Image = 'data:image/jpeg;base64,' + imageData;
      this.capturedSnapURL = base64Image;
    }, (err) => {
      
      console.log(err);
      // Handle error
    });
  }


}

 

Ionic Native Camera Options

Here we have imported for <strong>Camera</strong> & <strong>CameraOptions</strong> classes to control features. The CameraOptions have parameters that are very important to control how images are handles clicked using the camera.

<strong>quality</strong>: can be from 1-100, due larger image size app becomes unstable so 20 is ok for reasonable image quality

<strong>destinationType</strong>: it can be FILE_URI (.jpg file path) or DATA_URI (base64)
<strong>encodingType</strong>: Image file type is returned in JPEG or PNG
<strong>mediaType</strong>: Used to get ALLMEDIA(Pictures or Videos), PICTURE or VIDEO

 

The takeSnap() method calls getPicture which returns a promise to get data url or base64 url based on the option provided in destinationType.

 

How to test Camera feature in Ionic Application

To test your application just connect your mobile with computer via USB cable and run following command:

$ ionic cordova run android -l

Note: Make sure you have USB debug mode enabled on your mobile under developer mode.

To create an APK file to test in mobile you can run the following command:

$ ionic cordova build android

Conclusion

Finally, we have implemented the Native Camera functionality in our Ionic 5 Angular application by installing Cordova nad Native plugins. Also, we discussed options available to use methods available in the Camera class. We hope you enjoyed this tutorial. Consider sharing with others. Thanks for reading!

 

4 thoughts on “Ionic 5|4 Adding Camera using Native plugin in Ionic Application”

Leave a Comment

Your email address will not be published. Required fields are marked *