0

In my AngularJS webapp I need to load an image from a file and then display it. But it doesn't work.

My plunk is: http://plnkr.co/edit/gpwyUd3Hh6HvrBnt2dR6

My JavaScript is:

var test = function() {
var getImgBytes = function() {
    return $http({    url: 'Spa_03.jpg', 
                      method: 'GET', 
                      headers: {'Content-Type': 'image/jpeg'}})
    .then(
      function(result) {
        console.log('load img from file');
        $scope.imgTest = result.data;
    });
  }();
$scope.height = 853;
$scope.width = 1280;   }();

My HTML is:

<img ng-src="data:image/JPEG,{{imgTest}}" width="320px" height="213px"/>

Could someone help me to fix the problem ?

Regards.

user3181983
  • 153
  • 1
  • 4
  • 13

2 Answers2

0

If you downloading image via $http request, it's not base64 encoded value.Its binary formatted file and you need to convert it to base64 via Javascript or canvas. Try this https://stackoverflow.com/a/6150397

Community
  • 1
  • 1
0

This code worked for me directly from the above answer with minor edits

  function toDataURL(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    var reader = new FileReader();
    reader.onloadend = function() {
      callback(reader.result);
    }
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  // xhr.setRequestHeader("username", auth.username);
  // xhr.setRequestHeader("password", auth.password);
  xhr.responseType = 'blob';

  xhr.send();
}


toDataURL('http://whatever/file/fid/'+ xRequest,  function(dataUrl) {
  //console.log('RESULT:', dataUrl)
  $scope.loading = false;
  $scope.image = dataUrl;
})

Then you can use the image scope withing your html like this

<div class="content-avatar"><img ng-src="{{image}}" />
soloproper
  • 31
  • 6
  • *What* "above answer"? Please link directly to the answer you're modifying (using the "share" link) and indicate what changes you made. – Nathan Tuggy May 22 '17 at 19:08