Search code examples
javascriptangularjsfacebookcordovaionic-framework

Convert image extracted from URL to base64


I am fetching the user's Facebook profile picture whenever they login via Facebook. I want to convert the image to base 64 from the URL. What would be the best way of doing this, while ensuring that the user can still see their profile picture in the view (home.view)? At the moment, I am directly referring to the URL.

This is my code so far:

facebook.service.js

function FacebookService($http, config) {
      this.getUserPicture = function(userId, token) {
      return $http({
        method: 'GET',
        url: 'https://graph.facebook.com/' + userId + '/picture?type=large&redirect=false'
      })
    }
  }

home.controller.js

function HomeController($scope, $cordovaNativeStorage, FacebookService, $ionicLoading) {
  if (window.cordova) {
    // Get Facebook access token
    $cordovaNativeStorage.getItem("facebookAccessToken").then(function(value) {
      $scope.facebookAccessToken = value

      // Get Facebook user picture (currently stored as a URL, would want to store it as a base 64 string which can be displayed as an image
      FacebookService.getUserPicture($scope.facebookUserData.id).then(function(dataResponse) {
        $scope.facebookUserPicture = dataResponse.data;

        // Save Facebook user picture
        $cordovaNativeStorage.setItem("facebookUserPicture", $scope.facebookUserPicture).then(function() {}, function(error) {
          console.error("Unable to cache user data: " + result);
          $ionicLoading.show({
            template: 'Unable to cache user data',
            duration: 1500
          })
        });
      }, function(error) {
        console.log(error.data.error.message)
      })
    }, function(error) {
      console.log(error.data.error.message)
    })
  }
};

home.view.js

<img class="icon icon-home img-circle" ng-src="{{ facebookUserPicture.data.url }}">

Solution

  • There's a method to do it via canvas (source):

    var convertImgToDataURLviaCanvas = function(url, callback) {
      var img = new Image();
    
      img.crossOrigin = 'Anonymous';
    
      img.onload = function() {
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var dataURL;
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        dataURL = canvas.toDataURL();
        callback(dataURL);
        canvas = null;
      };
    
      img.src = url;
    }
    
    convertImgToDataURLviaCanvas( 'http://some.com/images/1.jpg', function( base64_data ) {
        console.log( base64_data );
    } );