Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Byte array to Base64 string in Angularjs

I am getting byte array in service response and that image would be shown in an image field of my html page. Any idea how can i implement this. I tried to find out solution for this over stack overflow but not able to get valid solution. Please help. My code is:

this.getPrescription = function(pres_id) {
     var deff = $q.defer();
     $http({
           method: "GET",
           url: "www.abc.com/api/&prescriptionOnly=false&page=1",
           headers: {
           'Authorization': 'Bearer ' + localStorage.getItem("chemist_access_token"),
           'Content-Type': 'application/json'
           },
           responseType: 'arraybuffer'
           }).then(function(objS) {
                   console.log("getPrescription:\n" + JSON.stringify(objS))
                   deff.resolve(objS);
                   }, function(objE) {
                   errorHandler.serverErrorhandler(objE);
                   deff.reject(objE);
                   });
     return deff.promise;
     };

and in my controller I am calling like:

$scope.getPrescription = function(id) {
    $ionicLoading.show({
        template: '<ion-spinner icon="spiral"></ion-spinner>',
        noBackdrop: false
    });
    serverRepo.prescriptionGet(id).then(function(objS) {
        console.log("orderByCustomer:\n" + JSON.stringify(objS));
        $scope.picdata=$window.URL.createObjectURL(new Blob([objS.data], {type: 'image/png'}));

        $ionicLoading.hide();
        console.log("getOrderByNew_success_loadMore:\n" +$scope.picdata);
    }, function(objE) {
        $ionicLoading.hide();
    });
}

and when I check my console it showing: getOrderByNew_success_loadMore: blob:file:///0aa86d9f-61a1-4049-b18c-7bf81e05909f

like image 815
Anjaney Mishra Avatar asked Dec 18 '22 17:12

Anjaney Mishra


2 Answers

Use this filter to convert byte array to base64

app.filter('bytetobase', function () {
    return function (buffer) {
        var binary = '';
        var bytes = new Uint8Array(buffer);
        var len = bytes.byteLength;
        for (var i = 0; i < len; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa(binary);
    };
});

to bind it as image use

<img ng-src="data:image/JPEG;base64,{{picture | bytetobase}}" alt="..." width="100" height="100">

Or if you need to assign it a variable use

var image = $filter('bytetobase')($scope.picture );
like image 128
Nair Athul Avatar answered Dec 28 '22 06:12

Nair Athul


If you need to display and image from byte array you can create an object using Blob and get it's URL to pass into the image tag source. The last parameter in Blob constructor contains information about blob type, so you should set correct type during blob creation.

$http.get(url, {responseType: 'arraybuffer'})
  .then(function(response) {
    return $window.URL.createObjectURL(new Blob([response.data], {type: 'image/png'}));
  });

And when you don't plan to work with your object any longer (e.g. after image has been loaded in appropriate img tag)

Update

Alternative solution with base64

$scope.getPrescription = function(id) {
  $ionicLoading.show({
    template: '<ion-spinner icon="spiral"></ion-spinner>',
    noBackdrop: false
  });
  serverRepo.prescriptionGet(id).then(function(objS) {
    console.log("orderByCustomer:\n" + JSON.stringify(objS));
    // Creating file reader
    var reader = new window.FileReader();
    // Creating blob from server's data
    var data = new Blob([objS.data], {type: 'image/jpeg'});
    // Starting reading data
    reader.readAsDataURL(data); 
    // When all data was read
    reader.onloadend = function() {
      // Setting source of the image
      $scope.picdata = reader.result;
      // Forcing digest loop
      $scope.$apply();
    }

    $ionicLoading.hide();
    console.log("getOrderByNew_success_loadMore:\n" +$scope.picdata);
    }, function(objE) {
    $ionicLoading.hide();
  });
}
like image 45
k10der Avatar answered Dec 28 '22 07:12

k10der