How to return the Image as ResponseEntity<byte[]> and display same using Thyme leaf

14,513

Just send a HTTP request to your controller.

In your Thymeleaf template, set the source of your image to the url of your Spring MVC controller:

<img th:src="@{/controller/qr/${id}}" />

Provide a method in your controller that returns the image as ResponseEntity:

@RequestMapping (value="/qr/{id}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getQRImage(@PathVariable final String id) {
    byte[] bytes = ...; // Generate the image based on the id

    // Set headers
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_PNG);

    return new ResponseEntity<byte[]> (bytes, headers, HttpStatus.CREATED);
}

More answers can be found in this question: Spring MVC: How to return image in @ResponseBody?

Share:
14,513
Mohankumar D
Author by

Mohankumar D

Updated on June 04, 2022

Comments

  • Mohankumar D
    Mohankumar D almost 2 years

    I am using thyme leaf for one my project, I have problem in generating a QRCode and display the same in browser and I am using spring mvc framework.

    1. I will send the product id to API layer, that has to create QR code for that id. That should not save in anywhere and return as response as byte[]
    2. using thyme leaf framework have to display the image in browser

    Please help on the same.

    Regards Mohan

  • KNDheeraj
    KNDheeraj over 5 years
    Retrieve the byte[] content and convert it into Base64.getEncoder().encodeToString(byte[] content) then set it as a Context Variable and then process the templateEngine to the pass the variable as <img th:src="@{'data:image/png;base64,' + ${Base64String object's Context key} }" /> in Thymeleaf