Search code examples
angularjscordovaionic-frameworkcordova-pluginsngcordova

ngCordova file_uri to base64


I'm trying to use ngCordova's camera plugin (http://ngcordova.com/docs/plugins/camera/) to get pictures from my iphone and send it to my server. The backend developer wants me to encode it to base64. my data model looks like this

[{image_name:"foo", link: //base64 string}]

this is what my code looks like

$scope.getPictureFromGallery = function() {  $cordovaCamera.getPicture(options).then(function(imageURI) {


     $scope.image = imageURI;


    }, function(err) {
      // error
    });

  };

Solution

  • the documentation states that you can just set the destinationType to get the proper results.

    module.controller('PictureCtrl', function($scope, $cordovaCamera) {
    
      document.addEventListener("deviceready", function () {
    
        var options = {
          quality: 50,
          destinationType: Camera.DestinationType.DATA_URL, // <== HERE
          sourceType: Camera.PictureSourceType.CAMERA,
          allowEdit: true,
          encodingType: Camera.EncodingType.JPEG,
          targetWidth: 100,
          targetHeight: 100,
          popoverOptions: CameraPopoverOptions,
          saveToPhotoAlbum: false
        };
    
        $cordovaCamera.getPicture(options).then(function(imageData) {
          var image = document.getElementById('myImage');
          image.src = "data:image/jpeg;base64," + imageData; // <== HERE is how you create the actual string to send to server
        }, function(err) {
          // error
        });
    
      }, false);
    });
    

    I have a complete working example here https://github.com/aaronksaunders/dcww/blob/master/www/js/services.js#L39