Camera

The camera plugin provides access to the device's camera in order to take pictures. This plugin also allows you to pick images from the device's image library.

In order to use the camera in our Apache Cordova project, we need to use the following cordova plugin add command:

> cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-camera.git

Demo

In order to access the camera demo, you need to click on the camera list item. You will be introduced to the Camera page. You can click on the Get Picture button in order to select whether to get a picture from the device's gallery or the device's camera. If you choose the Camera menu item, the default camera application of the device will be launched for you to capture a picture. If you choose the Gallery menu item, the device's gallery will be opened for you to pick an image. After getting the image from the camera or the gallery, you will be able to view the image on the Camera page, as shown in the following screenshot:

Demo

A selected image is shown on the camera page

The HTML page

The following code snippet shows the "camera" page:

<div data-role="page" id="camera">
    <div data-role="header">
        <h1>Camera</h1>
        <a href="#" data-role="button" data-rel="back" data-icon="back">Back</a>
    </div>
    <div data-role="content">
        <h1>Welcome to the Camera Gallery</h1>
        <p>Click 'Get Picture' button below</p>
        <div class="center-wrapper">
            <input type="button" id="getPicture" data-icon="camera" value="Get Picture" 
                   class="center-button" data-inline="true"/>
        </div>
        <br/>
        
        <div style="width: 100%;">
            <img id="imageView" style="width: 100%;"></img>
        </div>
        
        <div data-role="popup" id="pictureTypeSelection">
            <ul data-role="listview" data-inset="true" style="min-width:210px;">
                <li data-role="divider" data-theme="a">Get Picture From</li>
                <li><a id="pictureFromGallery" href="#">Gallery</a></li>
                <li><a id="pictureFromCamera" href="#">Camera</a></li>
            </ul>
        </div>
    </div>
</div>

As shown in the preceding "camera" page code snippet, it contains the following:

  • A page header that includes a back button
  • Page content that includes the following main elements:
    • "getPicture": This button is used to get a picture
    • "imageView": This is used in order to display the selected or captured image
    • "pictureTypeSelection": This div element is a pop up that will be displayed to allow the user to select whether to get a picture from the camera or from the gallery

View controller

The following code snippet shows the page view controller JavaScript object that includes the action handlers of the page (camera.js):

(function() {
    var cameraManager = CameraManager.getInstance();

    $(document).on("pageinit", "#camera", function(e) {
        e.preventDefault();
        $("#imageView").hide();  

        $("#getPicture").on("tap", function(e) {
            e.preventDefault();

            $("#pictureTypeSelection").popup("open");
        });        

        $("#pictureFromGallery").on("tap", function(e) {
            e.preventDefault();
            $("#pictureTypeSelection").popup("close");

            getPhoto(true);
        });    

        $("#pictureFromCamera").on("tap", function(e) {
            e.preventDefault();
            $("#pictureTypeSelection").popup("close");

            getPhoto(false);
        });
    });

    function getPhoto(fromGallery) {
        var callback = {};

        callback.onSuccess = onSuccess;
        callback.onError = onError;

        cameraManager.getPicture(callback, fromGallery);
    }

    function onSuccess(fileURI) {
        $("#imageView").show();  
        $("#imageView").attr("src", fileURI);
    }

    function onError(message) {
        console.log("Camera capture error");
    }
})();

The "pageinit" event handler registers the following event handlers:

  • "getPicture" tap event handler: This opens the "pictureTypeSelection" pop up to allow the user to select the way to get a picture
  • "pictureFromGallery" tap event handler: This closes the currently opened "pictureTypeSelection" pop up and calls getPhoto(true) to pick a photo from the device's gallery
  • "pictureFromCamera" tap event handler: This closes the currently opened "pictureTypeSelection" pop up and calls getPhoto(false) to capture a photo using the device's camera

The getPhoto(fromGallery) method can get a photo (from the gallery or using the camera) by calling cameraManager.getPicture(callback, fromGallery) and specifying the following parameters:

  • The callback object that contains the following attributes:
    • onSuccess: This callback will be called if the operation succeeds. It receives the fileURI of the picked image as a parameter, this allows the callback to display the picked image in "imageView".
    • onError: This callback will be called if the operation fails.
  • The fromGallery parameter informs cameraManager.getPicture() to get the photo from the device's gallery if it is set to true, and if fromGallery is set to false, then it informs cameraManager.getPicture() to get the photo using the device's camera

API

The following code snippet shows the camera manager JavaScript object that interacts with the Apache Cordova Camera API (CameraManager.js):

var CameraManager = (function () {     
  var instance;

  function createObject() {
      var fileManager = FileManager.getInstance();      

      return {
          getPicture: function (callback, fromGallery) {      
              var source = Camera.PictureSourceType.CAMERA;

              if (fromGallery) {
                  source = Camera.PictureSourceType.PHOTOLIBRARY;  
              }

              navigator.camera.getPicture(callback.onSuccess, 
                                          callback.onError, 
                                          { 
                                              quality: 80, 
                                              destinationType: Camera.DestinationType.FILE_URI, 
                                              sourceType: source,
                                              correctOrientation: true 
                                          });
          }
    };
  };

  return {
    getInstance: function () {
      if (!instance) {
          instance = createObject();
      }

      return instance;
    }
  }; 
})();

As you can see, CameraManager is a singleton object that has a single method as highlighted in the preceding code. The getPicture(callback, fromGallery) function uses the Cordova navigator.camera.getPicture() method to get a picture.

The navigator.camera.getPicture(cameraSuccess, cameraError, [cameraOptions]) function has the following parameters:

  • cameraSuccess: This callback will be called if the operation succeeds. It receives a parameter that represents a file URI, or a native URI, or a Base-64 encoded string based on the specified cameraOptions parameter. In CameraManager, cameraSuccess is set to callback.onSuccess.
  • cameraError: This parameter will be called if the operation fails. In CameraManager, cameraError is set to callback.onError. Note that CameraError receives a string that represents the error description.
  • cameraOptions: This is an optional parameter that holds the camera's configuration.

The cameraOptions parameter has many attributes. The attributes in the following table are used by our CameraManager object:

Attribute name

Description

quality

This represents the quality of the saved image. It is expressed in a range of 0-100, where 100 is typically the full resolution with no loss due to file compression. In our CameraManager object, the quality is set to 80.

As per the Cordova documentation, setting the quality below 50 is recommended to avoid memory errors on some iOS devices. Setting the quality to 80 has always given me a good picture quality and has worked fine with me in my Cordova projects; however, if you find any memory errors because of the navigator.camera.getPicture() method, then please set the quality below 50 and rebuild/rerun the project again in your iOS device.

destinationType

This represents the type of the operation's returned value. It can have one of the following values:

  • Camera.DestinationType.DATA_URL: This means that the returned value will be a Base64-encoded string that represents the image
  • Camera.DestinationType.FILE_URI: This means that the returned value will be a file URI of the image
  • Camera.DestinationType.NATIVE_URI: This means that the returned value will be a native URI of the image

In our CameraManager object, destinationType is set to Camera.DestinationType.FILE_URI, which means that the success callback of the navigator.camera.getPicture() method will receive the image file URI.

sourceType

This represents the source of the picture. It can have one of the following values:

  • Camera.PictureSourceType.PHOTOLIBRARY
  • Camera.PictureSourceType.CAMERA
  • Camera.PictureSourceType.SAVEDPHOTOALBUM

In our CameraManager object, sourceType is set to Camera.PictureSourceType.PHOTOLIBRARY if fromGallery is set to true. If fromGallery is set to false, then sourceType is set to Camera.PictureSourceType.CAMERA.

correctOrientation

If this is set to true, then it will rotate the image to correct it for the orientation of the device during capture.

We are now done with the Camera functionality in our Cordova Exhibition app. However, before exploring the compass functionality, note that the navigator.camera.getPicture() function's CameraOptions parameter has also the attributes shown in the following table:

Attribute name

Description

allowEdit

If set to true, this will allow the user to edit an image before selection.

cameraDirection

This represents the type of camera to use (front facing or back facing). It can have one of the following values:

  • Camera.Direction.BACK
  • Camera.Direction.FRONT

encodingType

This represents the returned image file's encoding; it can have one of the following values:

  • Camera.EncodingType.JPEG
  • Camera.EncodingType.PNG

mediaType

This represents the type of media to select from. It only works when PictureSourceType is set to PHOTOLIBRARY or SAVEDPHOTOALBUM.

It can have one of the following values:

  • Camera.MediaType.PICTURE: This allows the selection of only pictures
  • Camera.MediaType.VIDEO: This allows the selection of only videos
  • Camera.MediaType.ALLMEDIA: This allows the selection of all media types

popoverOptions

This represents the popover location in iPad. It works only for iOS.

saveToPhotoAlbum

If set to true, then this will save the image to the photo album on the device after capture.

targetWidth

This represents the width in pixels to scale image. It must be used with targetHeight.

targetHeight

This represents the height in pixels to scale image. It must be used with targetWidth.

The navigator.camera object has also the method shown in the following table:

Method name

Description

navigator.camera.cleanup(cameraSuccess, cameraError)

This forces the removal of the intermediate image files that are kept in temporary storage after calling the camera.getPicture() method. This API applies only when the value of Camera.sourceType is Camera.PictureSourceType.CAMERA and the value of Camera.destinationType is Camera.DestinationType.FILE_URI. This works only on iOS.

In iOS, the temporary images in /tmp might be deleted when exiting the application. Using this API will force an instant cleanup of the temporary images.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.136.226