如何从 AngularJS 中的 $http.get 返回图像 [英] How to return image from $http.get in AngularJS

查看:20
本文介绍了如何从 AngularJS 中的 $http.get 返回图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器中,我调用了一个返回承诺的服务

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

在我的服务中,我通过将 url 直接传递给图像本身来调用以获取图像:

 return $http.get("http://someurl.com/someimagepath").then(功能(响应){返回 response.data;});

所有调用都成功并且 response.data 似乎保存在里面的图像中:

    ?JFIF  ;CREATOR: gd-jpeg v1.0(使用IJG JPEG v80),质量= 90C?????????????  C?"?   ?}!1A?Qa"q2   #B  R  $

虽然我不确定它是否真的存在,因为我无法显示它.我试过(在 index.html 内)

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

想法?是否可以从 $http.get 返回实际图像并将其响应转换回图像(jpeg 等)

谢谢!

解决方案

返回的图像在 a Mozilla 涵盖了制作XHR 请求和图像并将其直接读入 UInt8Array.这应该是一个不错的起点.

它是为普通的旧 Javascript 编写的,但如果您只是在学习绳索,将其翻译成 Angular 应该是一个很好的练习.

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!

解决方案

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.

这篇关于如何从 AngularJS 中的 $http.get 返回图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆