How to use the Cordova Camera Plugin to capture the image in Ionic App

How to use the Cordova Camera Plugin to capture the image in Ionic App

In this Ionic 4 Cordova Camera Plugin tutorial, we'll learn how to use the Cordova camera plugin to capture the image in an Ionic 4 app. Learn how to take pictures using Ionic Native & Cordova Camera plugin. Ionic Native support is fantastic to access the native devices.

Ionic 4 Camera tutorial is going to be today’s main topic, In this tutorial, we will learn how to take pictures using Ionic Native & Cordova Camera plugin.

Creating a Hybrid app doesn’t take a lot of time; however, in most of the cases, we get stuck in building any feature which is directly related to hardware accessibility. To access Network, Sensors, GPS, File System, Storage and Camera in Native devices sometimes becomes a bit tedious.

In this tutorial, we are going to create a basic camera app using Ionic/Angular. This allows a user to click a picture via a native camera device and returns the images in Base64 URL format.

To access native device camera, we will use Ionic Native, Its a wrapper for Cordova plugins that offers easy and better integration with Angular.

Table of Contents

  • Installing Cordova
  • Setting Up Ionic 4 Camera App
  • Adding Platform in Ionic
  • Install Ionic Cordova and Native Camera Plugin
  • Importing Camera Plugin in App Module
  • Using Camera Plugin in Ionic 4 Component
  • Test Camera App in Browser
  • Conclusion

Installing Cordova

You must have the Node and NPM installed in your device, to get started with Ionic 4 Camera tutorial.

Run the following command to install Cordova to access the native device.

npm install -g cordova

If throws an error, then use the below command.

sudo npm install -g cordova

Password:******

We will test our Ionic camera app on a real device. You must have Java SDK installed to build the camera app on Android. If you are creating a camera app for iOS, then you must have an Xcode app installed on macOS.

Setting Up Ionic 4 Camera App

Make sure you must have the latest version of Ionic CLI installed on your system.

npm install -g [email protected]

Once the Ionic CLI is updated, Run the following command to create a brand new blank Ionic/Angular app.

ionic start ionic-cordova-camera-app blank --type=angular

Get into the project folder.

cd ionic-cordova-camera-app

Adding Platform in Ionic

Next, we have to add the target platform. We can add the target platform by running the following commands based on your platform.

ionic platform add ios
ionic platform add android

Install Ionic Cordova and Native Camera Plugin

Next, run the command to install Native camera plugin to access the camera features.

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

[Note] Since IOS 10 the camera requires permissions to be placed in your config.xml add

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

Add the above code inside of the <platform name='ios> section

Ionic Supports Following Platforms

  • iOS
  • Android
  • Windows
  • Browser

Importing Camera Plugin in App Module

Now, we have installed and configured everything we required in our Ionic app. Next, To use the camera plugin, we need to import the Cordova Camera plugin and also register in the providers array in 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: [
    Camera,
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }

Using Camera Plugin in Ionic 4 Component

Finally, we are going to use camera plugin in an Ionic home component. Navigate to home.page.html file and place the following code inside of it.

<ion-button (click)="captureImage()">
   Click Picture
</ion-button>

<img [src]="clickedImage" />

Navigate to home.page.ts file and add the following code inside of it.

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

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

  constructor(private camera: Camera) { }

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

Have a look what we did above using Cordova Camera plugin.

quality: We can set the image quality from 1 to 100, above we set the image size to 30 to control the image size.

destinationType: Choose the format of the return value.

encodingType: Refers to the Image file type (JPEG or PNG).

mediaType: Used to get media type, refers to either Picture or Video.

captureImage(): This method triggers the getPicture() method, It takes the camera options in the parameter and return the data which we are setting in the variable to show the clicked image.

Test Camera App in Browser

To test the camera app in the browser, we have to run the below command.

ionic cordova platform add browser

Next, to test the camera app we need to run the following command.

ionic cordova run browser

Do not run ionic serve otherwise Ionic won’t be able to access the camera.

You can also use the following commands if you are developing the app for iOS or Android.

# Android
ionic cordova run android

# iOS
ionic cordova run ios

Conclusion

Finally, we have completed the Ionic 4 Cordova Camera Plugin Tutorial with Example. In this tutorial, we learned how to use the Cordova camera plugin to capture the image in an Ionic app. Ionic Native support is fantastic to access the native devices. I hope you liked this tutorial and share it with others.

Ionic Angular WebDev

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Install Angular - Angular Environment Setup Process

Install Angular in easy step by step process. Firstly Install Node.js & npm, then Install Angular CLI, Create workspace and Deploy your App.

Pros and Cons of Ionic Development

If you think Ionic is the right cross-platform application development, here are a few pros and cons of Ionic development. 

Ionic 5 Tutorial: Create Offline Price Checker (Angular 9)

In this Ionic 5 tutorial, we will create an offline price checker using SQLite, Barcode Scanner, and Angular 9. The price checker usually uses by the store or retail business to check the actual price of the item, product, or goods. So, inside this app will contain an SQLite database table of products that have fields id, price look-up (PLU) or product code, barcode, product name, product description, and product sell price.

Angular 9, Ionic 5, React Navigation 5 - Web Dev Update February 2020

Here's an update on what's important in web development! Angular 9, Ionic 5, React Navigation 5 and more - I'll bring you up-to-date with what you need to know!

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular. Angular is a Typesc