Ionic 3 and Angular 2: Using the Native Camera, Take Multiple Photos with Delete Action.
Wall Script
Wall Script
Friday, April 07, 2017

Ionic 3 and Angular 2: Using the Native Camera, Take Multiple Photos with Delete Action.

Are you searching for easy camera access for taking multiple pictures in your mobile application? Then here is the post explaining on how to access camera and take pictures. In most recent days, this is achieved easily with the combination of Ionic framework and AngularJS. We have already discussed in my previous article, how easy it is to use pre-built it in components of Ionic with AngularJS and build awesome mobile apps. Today’s article explains Cordova plugin provided by Ionic framework to access camera , take picture and see the output. The most exciting thing about this article is, it explains you to upload multiple images you take in camera. Let’s follow the article and also the video tutorial on this.

Ionic 2 and Angular 2: Using the Native Camera



Video Tutorial - Ionic 2 Using the Native Camera, Take Multiple Photos with Delete Action


Install NodeJS
You need node.js to create a development server, download and install the latest version.

Installing Ionic and Cordova
You will find these instructions in Ionic Framework installation document..
$ npm install -g cordova ionic

$ ionic start --v2 YourAppName tabs

$ cd YourAppName

$ npm install

$ ionic serve

Open your web browser and launch your application at http://localhost:8100.


Take Photo
Ionic 2 and Angular 2 using the Camera

Delete Photo
Ionic 2 and Angular 2 using the Camera

Launch Camera
Ionic 2 and Angular 2 using the Camera

Use Photo & Retake
Ionic 2 and Angular 2 using the Camera

Ionic Native Camera API
Install Ionic native plugin, you will find more information here
$ ionic cordova plugin add cordova-plugin-camera
$ npm install --save @ionic-native/camera

Ionic Camera Permissions
This plugins adds camera permission messages for ios.
$ ionic cordova plugin add cordova-plugin-ios-camera-permissions

app.module.ts
Now go to src/app/app.module.ts and import Ionic camera module.

import { NgModule, ErrorHandler } from '@angular/core';
import {Camera} from '@ionic-native/camera';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { CameraPage } from '../pages/camera/camera';
import { TabsPage } from '../pages/tabs/tabs';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    CameraPage,
    TabsPage
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    CameraPage,
    TabsPage
  ],
  providers: [
    StatusBar,
    SplashScreen,Camera,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

home.html
Now include your design in src/pages/home/home.html
<ion-header>
  <ion-navbar>
    <ion-title>
      Home
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding class="card-background-page">

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

  <ion-grid>
    <ion-row>
      <ion-col col-6 >
        <ion-card class="block">
        <ion-icon  name="trash" class="deleteIcon"></ion-icon>
        <img src="someimage.png" />
        </ion-card>
      </ion-col>
    </ion-row>
  </ion-grid>

</ion-content>

home.scss
SASS nested styles for home.html page.
page-home {
.block {
  position: relative
  .deleteIcon {
    position: absolute !important;
    color: #ffffff !important;
    margin-left: 80% !important;
  }
  .deleteIcon:before {
    font-size: 30px !important;
  }
  }
}

home.ts
Now modify home module, here imported ionic camera module. Include functions for takePhoto and deletePhoto.
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {Camera, CameraOptions} from '@ionic-native/camera';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  public photos : any;
  public base64Image : string;
  constructor(public navCtrl: NavController) {

  }

  ngOnInit() {
    this.photos = [];
  }

  deletePhoto(index) {
   console.log("Delete Photo");
  }

  takePhoto(){
  console.log("Take Photo");
  }

}

Modify Home Constructor
Call camera module in constructor.
constructor(public navCtrl : NavController, private camera : Camera) {

}

Take Photo
This function will help you to capture mobile camera snap, image response will be in base64 encoding format.
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) => {
        this.base64Image = "data:image/jpeg;base64," + imageData;
        this.photos.push(this.base64Image);
        this.photos.reverse();
      }, (err) => {
        console.log(err);
      });
  }

home.html
Now loop your HTML design with photos data.
<ion-col col-6 *ngFor="let photo of photos; let id = index">
        <ion-card class="block">
          <ion-icon name="trash" class="deleteIcon" (click)="deletePhoto(id)"></ion-icon>
          <img [src]="photo" *ngIf="photo" />
        </ion-card>
</ion-col>

Delete Photo
Simple javascript function for photos array value based on index value.
deletePhoto(index){
   this.photos.splice(index, 1);
}

Ionic Delete Confirmation
Make following changes to import ionic alert confirmation module.

home.ts
import {NavController, AlertController} from 'ionic-angular';

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

}


Delete Photo
Final code for deleting photo with alert confirmation.
deletePhoto(index) {
    let confirm = this.alertCtrl.create({
        title: 'Sure you want to delete this photo? There is NO undo!',
        message: '',
        buttons: [
          {
            text: 'No',
            handler: () => {
              console.log('Disagree clicked');
            }
          }, {
            text: 'Yes',
            handler: () => {
              console.log('Agree clicked');
              this.photos.splice(index, 1);
            }
          }
        ]
      });
    confirm.present();
  }

Build iOS App
Following commands for executing Xcode build, watch the video tutorial you will understand more.
$ cordova add platform ios
$ ionic cordova build ios

Build Android App
Open Android build using Android SDK>
cordova add platform android
ionic cordova build android

Video Tutorial - Ionic 2 Using the Native Camera, Take Multiple Photos with Delete Action

web notification

28 comments:

  1. Thank you for this article.This is the best list I have found on Ionic 2 and Angular 2: Using the Native Camera, Take Multiple Photos with Delete Action. Looking for more articles like this.

    ReplyDelete
  2. its best. i am working on ionic 1. now i am moving on ionic 2 and its very helpfull for me

    ReplyDelete
  3. hey Srinivas
    great work sir.
    i really admire your blog and the information you provide in this post was of a lot of help to me.
    kudos to you...!!

    thankyou

    ReplyDelete
  4. Thanks, almost everything worked well, except that the photo didn't show up in the card as thumbnails after shooting for me. I have added to the cameraOptions: saveToPhotoAlbum: True, and the photos save nice to the camera roll, but they don't display in the card. Any idea why?

    ReplyDelete
    Replies
    1. I have the same problem. I can take a picture but the thumbnails dont show.

      Delete
  5. GitHub code has been updated with Ionic3 and Angular 4

    ReplyDelete
  6. Thanks for the tutorial .... but is it possible to take the multiple images from gallery instead of camera using this method ?? if yes then what changes should be made in this ?

    ReplyDelete
  7. Thanks, everything worked well.
    What about select multiple images from gallery ?

    ReplyDelete
  8. Any idea why it does not show the thumbnails after taking a photo?

    ReplyDelete
  9. Change in home.ts this.base64Image = "file://" + imageData; -> this.base64Image = imageData; and it works. Tested on Samsung S7 edge.

    ReplyDelete
    Replies
    1. it is not working for me. Can you please help

      Delete
  10. how can i use native/file-transfer to upload those photos to remote server

    ReplyDelete
    Replies
    1. have you found any solution to upload multiple files at once

      Delete
  11. How to upload form containing image to server??

    ReplyDelete
  12. Thanks worked really fine with me. How to upload all the pictures taken to firebase?

    ReplyDelete
  13. hello All ,I have one problem ,in whatsapp application when I click on camera icon …how that list
    of images are display from gallery directly ??… please help me …am not
    able to find solution to this task “how to display list of horizontal
    images in ionic application” …i use camera ,imagepicker,imageviewer…
    plugin but still not find solution

    ReplyDelete
  14. Im actually unable to launch the Camera App at the first place. Any idea why?

    ReplyDelete
  15. Error: Template parse errors: Property binding ngforOf not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations". (" [ERROR ->] <ion-card class="block""): ng:///AppModule/HomePage.html@30:12

    ReplyDelete
  16. Hi thanks for the great tutorial. Can you please tell how to add delete button to images inside ion-scroll?

    ReplyDelete
  17. hello,first of all thanks for this tutorial. I want to a query ,i am using this method in my app ,but is it a good idea for using base64 or is there any other way to upload multiple files.please help me i am confused.

    ReplyDelete
  18. Excellent and useful guide/tutorial. Unlike the many other boring ones around the web that recycle what everybody else is saying just for a quick cash.

    ReplyDelete
  19. Hi SRINIVAS TAMADA thanks for giving this best tutorial my question is i want to capture multiple image with out exist the camera and all the capture image display on camera screen like in whatsapp when we capture more than image please let me know if you have any idea.
    Thanks

    ReplyDelete
  20. Thanks for giving excellent tutorial.I just want to know that in my application i want to implement the same functionality but in my case i want to capture multiple images without close the camera like in whatsapp when we capture more than one image it display the images on camera and when we press send button it send all the capture images please let me know how can i implement this.
    Thanks

    ReplyDelete
  21. Thank you. you saved my life.i was stress couldnt find a way about camera.. ive tried the tutorials... still no luck. when i tried your code. it works! thank you so much

    ReplyDelete

mailxengine Youtueb channel
Make in India
X