在 AngularJS 中渲染远程 PNG 图像

Render remote PNG image in AngularJS

我正在开发一个 AngularJS 应用程序,它显示从服务器检索到的 PNG 图像。

如果我在浏览器中输入 URL(见下文),我可以很好地看到图像。但是,如果我想从我的 Angular 应用程序中检索这样的图像,我将无法显示它(尽管我确实收到了数据!)。

JS代码如下:

$scope.receivedImage = null;

var url = 'https://subdomain.mydomain.uk/img?latitude=55.57&longitude=-5.16&extent=2000';

$http(
    {
        method: 'GET',
        url: url,
        headers: {
            Accept: 'image/png'
        }
    }
).then(
    function successCallback(response) {
        var data = response.data;
        $scope.receivedImage = data;
    },
    function errorCallback(response) {
        console.error(response);
    }
);

问题是我看不到检索到的图像。为了更好地了解情况,我在 HTML 页面中添加了以下代码:

<div ng-show="receivedImage">
    <pre>{{receivedImage}}</pre>
    <img data-ng-src="{{receivedImage}}" />
    <img data-ng-src="data:image/png;{{receivedImage}}" />
</div>

'' 显示类似于

�PNG IHDR�R9�%IDATx��̱ ������ �2��'��j�Z�V��w����LxIEND�B`�

第一个 '' 没有显示任何内容。

第二个“”显示图像图标并在控制台中抛出错误:

GET data:image/png;%EF%BF%BDPNG%1A%00%00%00IHDR%00%00%00%1E%00%00%00%1E%08%02%0…%BD%EF%BF%BD%EF%BF%BD%EF%BF%BDL%0E%17x%00%00%00%00IEND%EF%BF%BDB`%EF%BF%BD net::ERR_INVALID_URL

如何正确渲染此图像?

尝试将 ng-src 属性设置为一个变量,即 url。

$scope.url = 'https://subdomain.mydomain.uk/img?latitude=55.57&longitude=-5.16&extent=2000';

并在标记中

<img ng-src="{{url}}" />

如果 url 未受保护,那么 Anthony 中的方法会有很大帮助。对于我的 use-case,其中 URL 受到保护,我不得不采用以下方法。在这种情况下,我必须通过覆盖 angular 的 http 身份验证拦截器来注入身份验证 headers 以访问受保护的 URL.

    // http call inside a service under a function named getImage()
    $http(
        {
            method: 'GET',
            url: 'YOUR_PROTECTED_RESOURCE_URL',
            // This is required for getting your data as buffer array
            {
                responseType: 'arraybuffer'
            }
        }
    ).then(
        function successCallback(response) {
            return response;
        },
        function errorCallback(response) {
            console.error(response);
        }
    );

在您的控制器或指令中,来自上述调用的数据必须像这样处理:

// Function to get the image from the server
var handleImage = function(){
    MyHttpService.getImage()
    .then(function(response){
      // Can be used within ng-src fro displaying image
      $scope.receivedImage = 'data:image/png;base64,'+_arrayBufferToBase64(response);
    }, function(error){
      console.error(error);
    });
};

// Convert the buffer to base64
var _arrayBufferToBase64 = function( buffer ) {
        var binary = '';
        var bytes = new Uint8Array( buffer );
        var len = bytes.byteLength;
        console.log(len);
        for (var i = 0; i < len; i++) {
            binary += String.fromCharCode( bytes[ i ] );
        }
        return window.btoa( binary );
      };

希望这对试图从受保护资源 URI 访问资源的人有所帮助。