ra170 ra170 - 1 year ago 119
AngularJS Question

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")
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



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}}">
<img ng-src="{{myImage}}.jpeg">
<img ng-src="data:image/JPEG;base64,{{myImage}}">

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


Answer Source

The image that's coming back is in binary encoding, rather than Base64.

Understandably, <img> tags don't support sourcing from binary through attributes, so you'll have to look at another solution.

You could try converting the binary encoding to Base64 at the client side using TypedArrays together with the btoa function. Then you'd be able to use

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

This guide a by Mozilla covers making an XHR request for and image and reading it directly into a UInt8Array. It should be a good starting place.

It's written for plain old Javascript, but translating it to Angular should be a good exercise if you are just learning the ropes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download