神刀安全网

Use The Device Camera In An Ionic 2 Android And iOS App

As I continue to port my Ionic Framework tutorials to Ionic 2, I figured it was time to discuss how to make use of the device camera within an application.  There are often needs to obtain pictures within an application.  Maybe you’re creating an application like Imgur, or maybe you just want to be able to obtain a profile picture.  Like I mentioned, I had written a camera tutorial a few years back on how to use the camera in an Ionic Framework application .

This time around we’re going to see how to snap pictures within an Ionic 2 Android and iOS mobile application.

Let’s start by creating a fresh Ionic 2 project.  From the Command Prompt (Windows) or Terminal (Mac and Linux), execute the following commands:

ionicstartCameraProjectblank --v2 --typescript cd CameraProject ionicplatformaddios ionicplatformaddandroid 

A few things to note above.  We are creating an Ionic 2 TypeScript project.  This means that you need to have the appropriate Ionic CLI installed.  If you are not using a Mac then you cannot add and build for the iOS platform.

To use the Android and iOS device camera there are a few options.  Both options require the Apache Cordova camera plugin .  You can use vanilla JavaScript with the plugin or you can use Ionic Native .

We’re going to use Ionic Native, but first lets install the Apache Cordova plugin:

ionicpluginaddcordova-plugin-camera 

Let me start by saying that as of now, April 2016, the official Ionic Native documentation for the camera plugin is terrible.  To learn how to use this plugin I had to dig into the source code .  I’m going to save you the trouble.

Developing the Ionic 2 Device Camera Logic

The logic file won’t be too complicated.  Essentially we’ll be creating a function that uses Camera class with various options.  There are some catches though which we’ll see.  First open the project’s  app/pages/home/home.ts file and include the following code:

import {Page} from 'ionic-angular'; import {Camera} from 'ionic-native'; import {NgZone} from "angular2/core";   declare varnavigator: any;   @Page({     templateUrl: 'build/pages/home/home.html' }) export class HomePage {       base64Image: string;     zone: any;       constructor() {         this.base64Image = "https://placehold.it/150x150";         this.zone = new NgZone({enableLongStackTrace: false});     }       takePicture() {         Camera.getPicture({             quality : 75,             destinationType : navigator.camera.DestinationType.DATA_URL,             sourceType : navigator.camera.PictureSourceType.CAMERA,             allowEdit : true,             encodingType: navigator.camera.EncodingType.JPEG,             targetWidth: 300,             targetHeight: 300,             saveToPhotoAlbum: false         }).then(imageData => {             this.zone.run(() => {                 this.base64Image = "data:image/jpeg;base64," + imageData;             });         }, error => {             console.log("ERROR -> " + JSON.stringify(error));         });     } } 

Let’s break everything down because I’m sure some of it won’t make sense.

The first import that didn’t ship with our blank template is as follows:

import {Camera} from 'ionic-native'; 

This allows us to use some Angular 2 friendly camera functionality with Ionic Native.

Notice how I’m declaring a navigator variable.  This is for the camera options.  Since it is vanilla JavaScript, TypeScript will throw some errors if we try to use it without first declaring it.

The next import is where things can get a little nutty.  We are including the NgZone class because as of now in the current Angular 2 and Ionic 2 beta, scope variables don’t always refresh the way they should.  If you’re familiar with AngularJS 1, you’ll remember the  $scope.apply() function that would refresh the scope.  I like to think of this as similar.  My hope is that it changes in the future.

With the imports out of the way we find ourselves in the constructor method:

constructor() {     this.base64Image = "https://placehold.it/150x150";     this.zone = new NgZone({enableLongStackTrace: false}); } 

In the constructor we are defining a placeholder image to be used when no camera image exists.  We are also initializing our NgZone object for future use.

Like I said previously, the takePicture function just calls the Ionic Native camera class and passes it a bunch of options that I dug out of the Ionic source code.  You can choose to use the  navigator variable that we declared earlier or the numeric values directly.  My preference is the  navigator because then you can refer to the official Apache Cordova camera documentation for appropriate properties.

Finally you see this:

this.zone.run(() => {     this.base64Image = "data:image/jpeg;base64," + imageData; }); 

This is how we are force refreshing the base64Image variable that is bound to the UI.  If we don’t do this, the UI will still contain the placeholder image even after we’ve taken a picture.

The logic at this point is done.

Designing the Ionic 2 UI

With the logic out of the way, let’s cook up a simple UI.  Essentially we’re only going to have a placeholder image and navigation button on the screen.  Open the project’s app/pages/home/home.html file and include the following code:

<ion-navbar*navbar>     <ion-title>         Home     </ion-title>     <ion-buttonsend>         <button(click)="takePicture()">             <ion-iconname="camera"></ion-icon>         </button>     </ion-buttons> </ion-navbar>   <ion-contentclass="home">     <imgsrc="{{ base64Image }}"/> </ion-content> 

The navigation button will be of a camera and appear on the right side.  The placeholder image will exist until a camera photo is taken.

This application will probably not work in an iOS simulator or web browser.  iOS simulators have issues when it comes to the device camera, and since this uses native platform code, the web browser won’t understand it.

Conclusion

You just saw how to create a simple application that will take pictures and display them on the screen.  Things are a little different than the Ionic Framework 1 camera tutorial that I wrote in the sense that we are now using Angular 2 with TypeScript and that we are using the  NgZone class.  Nothing was particularly difficult and it should put you on the right track towards using the device camera within your mobile application.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Use The Device Camera In An Ionic 2 Android And iOS App

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址