1

I have a service which adds some properties to file and sends it back in a response as byte array, but i have hard time displaying it as it is bytes, i tried to convert it to base64 but it still didn't worked. It shows raw bytes

�PNG

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

What would be best solution to solve this maybe i should change response type is it possible to send not bytes?

@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 code

$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 code

<img class="thumb image-properties" ng-if="image" ng-src="{{image}}" />
DanJo
  • 83
  • 1
  • 9
  • Try converting it to a data uri: `data:image/png;base64,` – Riiverside May 01 '17 at 16:40
  • 1
    Possible duplicate of [Javascript : How to display image from byte array using Javascript or Servlet?](http://stackoverflow.com/questions/20756042/javascript-how-to-display-image-from-byte-array-using-javascript-or-servlet) – adam-beck May 01 '17 at 16:42
  • Actually a better duplicate would be: http://stackoverflow.com/questions/14979791/angularjs-show-byte-array-content-as-image – adam-beck May 01 '17 at 16:44
  • I added `` as it says in the answer but still image is not displayed, where to put this `$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|ftp|blob):|data:image\//);`? – DanJo May 01 '17 at 16:53

2 Answers2

0

surely you already find the solution. if not

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

for other people with the same issue, this problem have a far easier solution:

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

and in JS:

$scope.extractImage = function (sourceFile) {
  $scope.image = `/image/decode/$sourceFile`;
};
alizelzele
  • 892
  • 2
  • 19
  • 34
0

Ok, my search led me here. Here's how I solve the "show image from byte array sent in response" problem. The comment from @amdev from show-byte-array-content-as-image was particularly helpful. Here are the key points:

  1. The backend must return a base 64 encoded string.
  2. Send the string as a response body and not a string response. If you send it as a string response straight away, there is a possibility that the image will be incomplete because it is too large.
  3. The frontend displays it using data URL.

Java Spring Backend

@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 Frontend

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

Hope this helps.

jpllosa
  • 2,066
  • 1
  • 28
  • 30