1

Currently, I am getting the user details in the response from the server. From that response, I want to encode the image and wants it to display on my front end. currently, this what I am doing:

HTML: <img ng-src=data:image/png;base64,{{user_image}}>

Angularjs:

  $http({
  method: 'GET',
  url: 'userimage',
  }).then(function(response) {
     $scope.user_image = response.data;
     var str = _arrayBufferToBase64(response.data.user_image);
  }, function(response) {
    console.error('error.');
});


function _arrayBufferToBase64(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);

}

In response, I am getting user details but I don't know how to encode the image. Please let me know where I am going wrong.

2
  • Just curious as to why the server is returning the actual image, and just its URL Commented Mar 9, 2018 at 9:09
  • 1
    for the image, I am getting '?' in my response @Mawg Commented Mar 9, 2018 at 9:22

1 Answer 1

3

Shouldn't you assign a base64 encoded string to a scope variable rather than response.data? I guess, what you really want is:

$scope.user_image = _arrayBufferToBase64(response.data.user_image);

There is one issue though. Your haven't specified a response type as 'arraybuffer'. Please, add that to your request config object:

responseType: 'arraybuffer'
Sign up to request clarification or add additional context in comments.

12 Comments

I implemented your logic, I am getting the base64 string in my log. But the image is not getting displayed in the browser
Ok. Lets make sure, that all simplest things are there. Is your image really png or it's a jpeg? Is the server really returns us an array buffer and not something else?
And one more thing - please, enclose a content of ng-src with double quotes since it won't be working properly in your case. In case if doesn't work still, please take a look at plunker, which I've prepared for a small demo: plnkr.co/edit/rfTxKctNHYS2Nl7gzgpx?p=preview
I am passing png image format. Even the server is returning the array buffer itself. But I don't know where I am going wrong. I will go through the demo and i'll fix it
Have you enclosed a value of ng-src with double quotes?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.