How to use the Ionic Cordova plugin camera in Ionic 6?

Ionic Cordova plugin camera allows us to use a native camera to take a picture and allows us to choose images from the mobile device image library. With the release of ionic 4 and above, we can also use the Ionic capacitor camera plugin to achieve the same functionality as the ionic Cordova camera in  Progressive Native Web, Mobile, and Desktop applications. The Cordova camera plugin uses the native camera for taking pictures or getting images from the image gallery.

In this article, we’ll learn how to used the Ionic Cordova camera plugin to trigger the camera picture and get an image from a gallery of the phone. Our image is in Base64 or URI format.

Ionic Cordova camera example screenshot

If you are building an application only for a mobile device, then we can use the Ionic Cordova plugin camera plugin otherwise is recommended to use the capacitor camera plugin. We’ll demonstrate how to use the Ionic Cordova camera in the Ionic 5 project. We have two buttons in our example, one to take the photo using the device camera and the other is to load an existing picture from the device image library.

Screenshot of ionic Cordova camera example

ionic cordova plugin camera example

Setting and configure the Ionic project for ionic Camera Cordova

If you have not yet installed an Ionic CLI on your system. Then we need to install an Ionic CLI first. Ionic CLI allows us to create an Ionic project, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment. To install the Ionic CLI, open a terminal, and run the following command:

npm install -g @ionic/cli

With the release of ionic version 4, no longer limited to angular, we can create the ionic projects in different front-end frameworks like Angular, Vue, and React.  In this example, we’re using an Ionic angular project. Let create an Ionic angular project.

ionic start cordovaCameraApp

Once we execute the above command, it will allow us to select a framework and template. We have to select the Angular framework. The ionic framework already had lots of pre-made built-in templates. In our case, we are using a blank template.

ionic cordova camera plugin
Ionic Cordova plugin camera

Installing ionic Cordova plugin camera

We must have the Node and NPM installed in your device, to get started with the Ionic 5 Camera tutorial. Let install the Ionic Cordova camera.

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

Ionic Cordova plugin camera supported many platforms and these include.

  • Android
  • Browser
  • iOS
  • Windows
Note:Since IOS 10 the camera requires permissions to be placed in your config.xml add.

We need to add the code below inside of the <platform name='ios> section for IOS platform.

<config-file parent="NSCameraUsageDescription" platform="ios" target="*-Info.plist">
 <string>You can take photos</string>
</config-file>

Importing Ionic cordova Camera Plugin in App Module

To use the Cordova camera in our ionic application, we need to import the Cordova camera class reference as a provider inside our app.module.ts file.

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,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    Camera
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

What we will learn in ionic cordova plugin camera ?

In this article on the Cordova camera plugin, we’re learning the following.

  1. Access the Cordova camera plugin to trigger the camera picture and get the image back in the Base64 or URI format.
  2. Parse the Base64 data or URI on an image tag DOM object.
  3. Display the URI if it’s in the URI format.

Addning and using Ionic Cordova camera plugin in component

Now we had finished the camera configuration in our application and now let’s start working on the Ionic camera. In our blank ionic angular page have a home component. Let first create two buttons in our home component template.

  1. Button show camera for taking photos from the device camera
  2. Button show Album for taking images from the device image gallery.

Once we have an image, we are displaying it in our template using the image variable. Edit home.page.html templates.

<ion-header [translucent]="true">
  <ion-toolbar color="danger">
    <ion-title>
      Ionic 5 cordova camera
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <img [src]="image" *ngIf="image">
  <ion-grid>
    <ion-row class="ion-align-self-center">
      <ion-col size="6">
        <ion-button (click)="takePhoto(1)">Show Camera</ion-button>
      </ion-col>
      <ion-col size="6">
        <ion-button (click)="takePhoto(0)">Show Album</ion-button>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

We have an image tag with ngIf directive, whenever we have an image, we’re displaying it otherwise there is no image tag. In our takePhoto() method we have passed one argument, this argument indicates sourceType of the camera. Sourcetype 1 indicates from taking image from camera and 0 indicates we want to use an image from our phone gallery. Using sourceType 0 or Zero will open a dialog popup instead of a camera and allow you to choose the image you want from the device.

Add the following code in home.page.ts, we have to import Camera and CameraOptions,  class as a dependency in our home.page.ts file

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 {
  image: string;

  constructor(private camera: Camera) { }

  async takePhoto(sourceType) {
    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      sourceType
    };

    this.camera.getPicture(options).then((imageData) => {
      // imageData is either a base64 encoded string or a file URI
      // If it's base64 (DATA_URL):
      this.image = 'data:image/jpeg;base64,' + imageData;
    }, (err) => {
      // Handle error
      console.error(err);
    });
  }

}

We can have an image in base64 string or image file URI, in-camera option by specifying DestinationType as DATA_URL allows us to take an image in base64 string.  Cordova camera had a list of properties which is optional we can customize to use it and here is the list of Ionic Cordova camera options we can use.

NameTypeDefaultDescription
qualitynumber50The quality of the saved image is expressed as a range of 0-100, where 100 is typically full resolution with no loss from file compression. (Note that information about the camera’s resolution is unavailable.)
destinationTypeDestinationTypeFILE_URIChoose the format of the return value.
sourceTypePictureSourceTypeCAMERASet the source of the picture.
allowEditBooleanfalseAllow simple editing of the image before selection.
encodingTypeEncodingTypeJPEGChoose the returned image file’s encoding.
targetWidthnumberWidth in pixels to scale image. Must be used with targetHeight. The aspect ratio remains constant.
targetHeightnumberHeight in pixels to scale image. Must be used with targetWidth. The aspect ratio remains constant.
mediaTypeMediaTypePICTURESet the type of media to select from. Only works when PictureSourceType is PHOTOLIBRARY or SAVEDPHOTOALBUM.
correctOrientationBooleanRotate the image to correct the orientation of the device during capture.
saveToPhotoAlbumBooleanSave the image to the photo album on the device after capture.
popoverOptionsCameraPopoverOptionsiOS-only options that specify popover location in iPad.
cameraDirectionDirectionBACKChoose the camera to use (front- or back-facing).
Ionic Cordova camera options list to customize camera setting

Adding Platform in our ionic camera project

Once we have completed our project, we need to test it on our real device. For that, we need to dd the target platform and in our case, we have tested in android 9. We can add the target platform by running the following commands based on your platform. Running ionic Cordova camera application in a mobile device, for android follow these steps.

ionic cordova build android
ionic cordova run android
ionic cordova run android

Conclusion
In this article, we have explored details on how to use the Ionic Cordova camera in ionic angular applications. We had used to take pictures from the camera or image gallery of the phone. I hope that this article was able to get you up and running with the Ionic Cordova camera.

Related Articles

Spread the love

Leave a Comment

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

Scroll to Top