Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

How to return image from $http.get in AngularJS

In my controller I call a service that returns a promise

var onComplete = function(data) {
               $scope.myImage = data;           
            };

In my service I make a call to get the image by passing url directly to the image itself:

   return $http.get("http://someurl.com/someimagepath")
         .then(function(response){          
          return response.data;
         });

All the calls are succeeding and the response.data appears to be holding in an image inside:

????JFIF??;CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 90
??C




??C      

????"?? 
???}!1AQa"q2???#B??R??$

although I'm not sure if it actually does because I'm having trouble displaying it. I've tried (inside index.html)

 <img ng-src="{{myImage}}"> 
  and
<img ng-src="{{myImage}}.jpeg"> 
  and   
 <img ng-src="data:image/JPEG;base64,{{myImage}}">

Ideas? Is it possible to return an actual image from $http.get and convert its response back to image (jpeg, etc.)

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...