最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cordova Image Picker convert to base64 - Stack Overflow

programmeradmin4浏览0评论

I am having trouble converting an image to base64 format that has been selected using the ngCordova imagePicker.

To keep things simple, the code provided on the Cordova site (which works) is this:

module.controller('ThisCtrl', function($scope, $cordovaImagePicker) {

  var options = {
   maximumImagesCount: 10,
   width: 800,
   height: 800,
   quality: 80
  };

  $cordovaImagePicker.getPictures(options)
    .then(function (results) {
     for (var i = 0; i < results.length; i++) {
    console.log('Image URI: ' + results[i]);
  }
}, function(error) {
  // error getting photos
});
});

The results array returns an array of results like: file///... but how to convert from here? I would like a function that you pass in a value to (the file) and returns the base64 string.

Here is a function that attempts this:

function convertImgToBase64URL(url, callback, outputFormat){

        var canvas = document.createElement('CANVAS'),
            ctx = canvas.getContext('2d'),
            img = new Image();
        img.crossOrigin = 'Anonymous';
        img.onload = function(){
            var dataURL;
            canvas.height = img.height;
            canvas.width = img.width;
            ctx.drawImage(img, 0, 0);
            dataURL = canvas.toDataURL(outputFormat);
            callback(dataURL);
            canvas = null; 
        };
        img.src = url;
    };

But how to integrate it into the code?

I have tried this (only need to pick one image):

$cordovaImagePicker.getPictures(options)
                .then(function (results) {
                    convertImgToBase64URL(results[0], function(base64Img){

                        self.chosenImage = base64Img;                                
                    });                          

             }, function(error) {
                console.log(error);
             }); 

but self.chosenImage gets set to blank.

Might be an async issue but how best to resolve it?

I am having trouble converting an image to base64 format that has been selected using the ngCordova imagePicker.

To keep things simple, the code provided on the Cordova site (which works) is this:

module.controller('ThisCtrl', function($scope, $cordovaImagePicker) {

  var options = {
   maximumImagesCount: 10,
   width: 800,
   height: 800,
   quality: 80
  };

  $cordovaImagePicker.getPictures(options)
    .then(function (results) {
     for (var i = 0; i < results.length; i++) {
    console.log('Image URI: ' + results[i]);
  }
}, function(error) {
  // error getting photos
});
});

The results array returns an array of results like: file///... but how to convert from here? I would like a function that you pass in a value to (the file) and returns the base64 string.

Here is a function that attempts this:

function convertImgToBase64URL(url, callback, outputFormat){

        var canvas = document.createElement('CANVAS'),
            ctx = canvas.getContext('2d'),
            img = new Image();
        img.crossOrigin = 'Anonymous';
        img.onload = function(){
            var dataURL;
            canvas.height = img.height;
            canvas.width = img.width;
            ctx.drawImage(img, 0, 0);
            dataURL = canvas.toDataURL(outputFormat);
            callback(dataURL);
            canvas = null; 
        };
        img.src = url;
    };

But how to integrate it into the code?

I have tried this (only need to pick one image):

$cordovaImagePicker.getPictures(options)
                .then(function (results) {
                    convertImgToBase64URL(results[0], function(base64Img){

                        self.chosenImage = base64Img;                                
                    });                          

             }, function(error) {
                console.log(error);
             }); 

but self.chosenImage gets set to blank.

Might be an async issue but how best to resolve it?

Share Improve this question asked Apr 5, 2015 at 11:43 James Satori-BrunetJames Satori-Brunet 9012 gold badges13 silver badges29 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 10

Could you use $cordovaCamera and change the sourceType to Camera.PictureSourceType.PHOTOLIBRARY ?

document.addEventListener("deviceready", function () {

    var options = {
      quality: 50,
      destinationType: Camera.DestinationType.DATA_URL,
      sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
      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;
    }, function(err) {
      // error
    });

  }, false);

Interestingly, the ngCordova ImagePicker does not have the function to convert a picture to base64. However, the ngCordova $cordovaCamera function does, albeit only for immediately captured photos.

Here the equivalent options would be

 var options = {
  quality: 80,
  destinationType: Camera.DestinationType.DATA_URL,
  sourceType: Camera.PictureSourceType.CAMERA,
  allowEdit: true,
  encodingType: Camera.EncodingType.JPEG,
  targetWidth: 800,
  targetHeight: 800,
  popoverOptions: CameraPopoverOptions,
  saveToPhotoAlbum: false
};

Source: http://ngcordova./docs/plugins/camera/

This is an old question, but I think the main request is not answered although the alternative proposal is great. So just to point out a method that follows the suggested way, you could use this Base64 plugin.

Install it as usual

cordova plugin add https://github./hazemhagrass/phonegap-base64

and use it within the $cordovaImagePicker.getPictures success callback

$cordovaImagePicker.getPictures(options)
        .then(function (results) {
            for (var i = 0; i < results.length; i++) {
                console.log('Image URI: ' + results[i]);
                $scope.imageUri = results[i];

               // Encode URI to Base64
               window.plugins.Base64.encodeFile($scope.imageUri, function(base64){
                  // Save images in Base64
                  $scope.images.push(base64);
               });
            }

        }, function(error) {
            // error getting photos
        });

If you just want transfer image to serve, you haven't do this. You can use fileTransferPlugin. Hope this will hepl you.

发布评论

评论列表(0)

  1. 暂无评论