How to return image from $http.get in AngularJS

None of the methods seems to be complete, this is a complete solution:

  $http({
    method: 'GET',
    url: imageUrl,
    responseType: 'arraybuffer'
  }).then(function(response) {
    console.log(response);
    var str = _arrayBufferToBase64(response.data);
    console.log(str);
    // str is base64 encoded.
  }, function(response) {
    console.error('error in getting static img.');
  });


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

Then I am able to use it directly:

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

The function to convert arraybuffer into base64 is directly taken from ArrayBuffer to base64 encoded string

Leave a Comment