Ionic 1 Cordova Camera





0. Add Cordova





cordova plugin add cordova-plugin-camera

1. HTML



<button class = "button" ng-click = "takePicture()">
Take Picture</button>
<button class = "button" ng-click = "takePictureResize()">
Take Picture (Resize)</button>
<button class = "button" ng-click = "openPicture()">
Open Gallery</button>
<img ng-src = "{{mediafile}}">

2.JS


function($scope, $stateParams) {
    $scope.mediafile = '';
    var options = {};
    /*options
    quality: 50,
    destinationType: 1, 
    //0=DATA_URL, 1=FILE_URI, 2=NATIVE_URI
    //https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-camera/index.html#cameradestinationtype--enum
    sourceType: 1,
    //0=PHOTOLIBRARY, 1=CAMERA 2=SAVEDPHOTOALBUM
    //https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-camera/index.html#camerapicturesourcetype--enum
    encodingType: 0,
    //0=JPEG 1=PNG
    mediaType: 0,
    //0=PICTURE, 1=VIDEO, 2=ALLMEDIA
    //https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-camera/index.html#cameramediatype--enum
    allowEdit: true,
    //Allow simple editing of image before selection.
    correctOrientation: true //Corrects Android orientation quirks 
    Note: If you want to use ENUM instead of NUMBERS, set options in DeviceReady event.
    */

    var initOptions = function() {
        options = {
            quality: 50,
            destinationType: 1,
            sourceType: 1,
            encodingType: 0,
            mediaType: 0,
            allowEdit: true,
            correctOrientation: true
        }
    }
    $scope.takePicture = function() {
        initOptions();
        cdvGetPicture(options);
    };
    $scope.takePictureResize = function() {
        initOptions();
        options.targetWidth = 200;
        options.targetWidth = 200;
        cdvGetPicture(options);
    };
    $scope.openPicture = function() {
        initOptions();
        options.sourceType = 0;
        cdvGetPicture(options);
    };
    var cdvGetPicture = function(options) {
        console.log('begin getPicture');
        document.addEventListener("deviceready", function() {
            console.log('deviceReady');
            /*cordova task begin*/
            navigator.camera.getPicture(function cameraSuccess(imageUri) {
                console.log(imageUri);
                $scope.mediafile = imageUri;
                $scope.$apply();
                // You may choose to copy the picture, save it somewhere, or upload.
                //createFileEntry(imageUri);
            }, function cameraError(error) {
                console.debug("Unable to obtain picture: " + error, "app");
            }, options);
            /*cordova task end*/
        }); /*device ready*/
    } /*app task*/
}

0 Comments: