【问题标题】:AngularJS show image from byte array sent in responseAngularJS 显示来自响应发送的字节数组中的图像
【发布时间】:2017-09-29 01:59:32
【问题描述】:

我有一项服务,它向文件添加一些属性并将其作为字节数组在响应中发送回,但我很难显示它,因为它是字节,我试图将它转换为 base64 但它仍然没有工作.它显示原始字节

�PNG

IHDR&��LCv�IDATx��......

解决这个问题的最佳解决方案是什么,也许我应该更改响应类型是否可以不发送字节?

@RequestMapping(path = "image/decode", method = POST, consumes = "multipart/form-data", produces = {"image/png", "image/jpeg"})
public byte[] decodeImage(@RequestParam("file") MultipartFile file) throws Exception {
    File file1 = addProperties(file);
    return FileUtils.readFileToByteArray(file1);
}

js代码

$scope.extractImage = function (sourceFile) {
    Upload.upload({
        url: '/image/decode',
        objectKey: '',
        data: {
            file: sourceFile
        }
    }).then(function (response) {
        console.log('Success ' +'Response: ' + response);
        $scope.image = response.data;
    }, function (response) {
        console.log('Error status: ' + response);
    });
};

HTML代码

<img class="thumb image-properties" ng-if="image" ng-src="{{image}}" />

【问题讨论】:

标签: javascript java image angular response


【解决方案1】:

您肯定已经找到了解决方案。如果没有

  var bytes = response.data;
  var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(bytes)));
  $scope.image = "data:image/png;base64," + base64String;

对于有同样问题的其他人,这个问题有一个更简单的解决方案:

@GetMapping(path = "image/decode/{img}", produces = {"image/png", "image/jpeg"})
public byte[] decodeImage(@PathVariable String img) throws Exception {
  // return your file's bytes
}

在 JS 中:

$scope.extractImage = function (sourceFile) {
  $scope.image = `/image/decode/$sourceFile`;
};

【讨论】:

    【解决方案2】:

    好的,我的搜索将我带到了这里。这是我解决“从响应发送的字节数组中显示图像”问题的方法。来自show-byte-array-content-as-image 的@amdev 的评论特别有帮助。以下是重点:

    1. 后端必须返回一个 base 64 编码的字符串。
    2. 将字符串作为响应正文而不是字符串响应发送。如果您立即将其作为字符串响应发送,则可能由于图像太大而导致图像不完整。
    3. 前端使用data URL 显示它。

    Java Spring 后端

    @RequestMapping(value = "/**")
    public @ResponseBody JsonResponse getImage(...) throws URISyntaxException {
        ...
        // the meat
        RestTemplate restTemplate = new RestTemplate();
        JsonResponse response = new JsonResponse(); // our own JSON marshaller class
    
        try {
            // pull image from a web api returning a byte array but this could be a call
            // to a database returning a byte array
            ResponseEntity<byte[]> imageBytes = restTemplate.exchange(url, method, httpEntity, byte[].class);
            byte[] imageBytesBody = imageBytes.getBody();
            String b64 = Base64.encodeBase64String(imageBytesBody);
            response.setSuccess(b64);
            // JSON message is {status: 'success', result: 'b64 - the image in base 64 format'}
        }
        catch(RestClientException x) {
            response.setError(x);
            // JSON message is {status: 'error', result: 'error blah blah blah'}
        }
    
        return response;
    }
    

    Javascript jQuery 前端

    $.ajax({
      type: 'GET',
      url: '/image',
      ...
    })
    .done(function(response) {
      $('body').append('<img src="data:image/png;base64,' + response.result + '" />');
    });
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-02-22
      • 2014-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多