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}}" />
4
  • Try converting it to a data uri: data:image/png;base64,<data converted to Base64> Commented May 1, 2017 at 16:40
  • 1
    Possible duplicate of Javascript : How to display image from byte array using Javascript or Servlet? Commented May 1, 2017 at 16:42
  • Actually a better duplicate would be: stackoverflow.com/questions/14979791/… Commented May 1, 2017 at 16:44
  • I added <img ng-src="data:image/JPEG;base64,{{image}}"> 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\//);? Commented May 1, 2017 at 16:53

2 Answers 2

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`;
};
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.