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

javascript - Convert Byte array to Base64 string in Angularjs - Stack Overflow

programmeradmin3浏览0评论

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/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

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./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

Share Improve this question edited May 7, 2016 at 13:58 Anjaney Mishra asked May 7, 2016 at 12:03 Anjaney MishraAnjaney Mishra 1411 gold badge2 silver badges13 bronze badges 3
  • try like this <img src="data:image/jpg;base64,{{yourData}}" /> – Hadi Commented May 7, 2016 at 12:06
  • serverRepo.prescriptionGet(id).then(function(objS) {$scope.picdata = objS.data;}, function(objE) { $ionicLoading.hide(); }); I am getting byte array in objS.data and using picData in my html like: <img ng-src="data:image/JPEG;base64,{{picdata}}"/> – Anjaney Mishra Commented May 7, 2016 at 12:10
  • what display picdata in console? – Hadi Commented May 7, 2016 at 12:14
Add a ment  | 

2 Answers 2

Reset to default 8

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

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();
  });
}
发布评论

评论列表(0)

  1. 暂无评论