Using cordova-camera plugin in your Ionic 2 Apps


http://tphangout.com/using-cordova-camera-plugin-in-your-ionic-2-apps/


Hi friends,

Hope you are all well. Now this post deals with using the cordova-camera plugin in your Ionic 2 apps to take photos using your smartphone camera. As with my previous posts I will try to keep this as much simple as possible.

The complete code of this tutorial can be found here.

A screencast of this tutorial is available below

Create an Ionic 2 application using the below command.

Let’s get started. Once you have created the Ionic 2 application; install the camera plugin using the below command.

1
ionic plugin add cordova-plugin-camera --save

Now once the plugin is installed, open up the app in an editor of your choice, navigate to app -> pages -> home and in the home.html file add the below code in between the <ion-content> tags.

Now this will add a button which upon clicking would trigger a takepic function and a card that holds an image.

If you with to use ionic-native to access camera, please skip the below steps and read the update at the end of this post.

Lets wire this up to the takepic function. Open up home.js and add the below code.

Let’s break this down.

  1. NgZone is used to execute services outside of angular and then get back in using run(). Read more about it here.
  2. Options specify the options considered while taking/saving the picture.
  3. navigator.camera is global when you install the plugin and can be used anywhere in the app.
  4. The image is captured and stored in the form of base64 encoding and then placed in this.image which is then used in the src attribute in the img tag.

Now this code is enough to use camera in our app. To execute this in your android phone please add the android platform using the below command.

and then run the app (on your mobile or emulator) using the below command.

This is a very simple way to use the smartphone camera in our app for taking pictures using the cordova camera plugin in our Ionic 2 apps.

Hope this helped you guys. Peace.. :)

Update:

The same could be done using ionic-native a new successor to ngCordova from driftyco. Once you install the plugin install ionic-native using the below command

Now modify the home.js as shown below:

Things to notice:

  1. We use numbers now to denote sourceType, destinationType and encodingType.
  2. Camera.getPicture returns a promise which is then resolved.

I have made a repo on this updated code and this is available here.

Thanks.


posted @ 2016-05-26 10:16  张同光  阅读(116)  评论(0编辑  收藏  举报