如何将图像转换为base64字符串?

用户名

您好,我正在尝试使用相机在ionic中进行简单的应用,或者从图库或文件系统中选择文件,然后发送到/或上传到服务器。我发现一个插件可以捕获一张图像并发送base64字符串,这里是插件http://ngcordova.com/docs/plugins/camera/,使用此插件,我可以获取base64字符串

$cordovaCamera.getPicture(options).then(function(imageData) {
      var image = document.getElementById('myImage');
      image.src = "data:image/jpeg;base64," + imageData;
    }, function(err) {
      // error
    });

我用来发送到服务器的那个base64字符串

但是我的问题是,当我使用此插件时,图像库插件

http://ngcordova.com/docs/plugins/imagePicker/它只向我发送图像url(在内存中)。从图像选择器中选择图像后,能否得到base64字符串。

$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
    });

换句话说,当我使用相机时,我得到的是base64字符串,如上所示。但是当我使用图像选择器插件时,我得到的图像是url。我可以得到base64的字符串。以便能够在服务器上发送或上传。如何将图片网址转换为base64字符串?

Anirudh R.Huilgol。

试试这个100%的工作代码。首先,您必须下载ngCordova.min.js文件并将其包含在index.html文件中。请遵循此代码。

angular.module('starter.controllers', [])

.controller('DashCtrl', function($scope,$cordovaCamera) {
	$scope.imgUrl;
	$scope.dataImg;
	$scope.tackPicture = function(){
	  var options = {
      quality: 50,
      destinationType: Camera.DestinationType.DATA_URL,
      sourceType: Camera.PictureSourceType.CAMERA,
      allowEdit: true,
      encodingType: Camera.EncodingType.JPEG,
      targetWidth: 100,
      targetHeight: 100,
      popoverOptions: CameraPopoverOptions,
      saveToPhotoAlbum: false,
	  correctOrientation:true
    };
	 $cordovaCamera.getPicture(options).then(function(imageData) {
      //var image = document.getElementById('myImage');
	  $scope.dataImg = imageData; // <--- this is your Base64 string 
      $scope.imgUrl = "data:image/jpeg;base64," + imageData;
    }, function(err) {
      // error
    });
	}
})

.controller('ChatsCtrl', function($scope, Chats) {
  // With the new view caching in Ionic, Controllers are only called
  // when they are recreated or on app start, instead of every page change.
  // To listen for when this page is active (for example, to refresh data),
  // listen for the $ionicView.enter event:
  //
  //$scope.$on('$ionicView.enter', function(e) {
  //});

  $scope.chats = Chats.all();
  $scope.remove = function(chat) {
    Chats.remove(chat);
  };
})

.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
  $scope.chat = Chats.get($stateParams.chatId);
})

.controller('AccountCtrl', function($scope) {
  $scope.settings = {
    enableFriends: true
  };
});
<ion-view view-title="Dashboard">
  <ion-content class="padding">
   <button class="button icon-left ion-ios-camera button-block button-positive" ng-click="tackPicture()">
   		OPEN CAMERA
   </button>
     <div class="item item-avatar">
    <img ng-src="{{ imgUrl }}">
   
    <p>{{ dataImg }}</p>
  </div>
  </ion-content>
</ion-view>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章