4

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

3
  • try like this <img src="data:image/jpg;base64,{{yourData}}" /> 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}}"/> Commented May 7, 2016 at 12:10
  • what display picdata in console? Commented May 7, 2016 at 12:14

2 Answers 2

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 );
Sign up to request clarification or add additional context in comments.

Comments

3

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

7 Comments

I run the function like this:- serverRepo.prescriptionGet(id).then(function(objS) { $scope.picdata=$window.URL.createObjectURL(new Blob([objS.data], {type: 'image/png'})); },function(err){}); And following is the code of html:- <center><img ng-src="{{picdata}}"/></center> And i got the following response from the function:- blob:file:///a3831c70-79ef-42db-8c9e-6d3548ca1bf2
Forgot to add responseType parameter in get request $http.get(url, {responseType: 'arraybuffer'})
I have added responseType in my service call, but URL which I got back is not showing image in <img>
Are you sure, that you added {responseType: 'arraybuffer'} to $http.get call and not to prescriptionGet? And check your browser's console to see, whether any errors accured.
I made changes in my question.Put my code in question. Please check and let me know where I am committing mistake.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.