Search code examples
javaspringthymeleaf

how insert image from db to page in thymeleaf


I can't understand how send to browser my image from server. My code down below. Why it doesn't working? When I'm getting bytes from DB and save them to disk image opens fine. In html there is next code:

<div th:fragment="image_list">
    image will be here
    <p>
        <img class="picture" th:src="@{/image/1}"/>
</div>

Java controller class:

    @GetMapping(value = "/{id}")
    @ResponseBody
    public ResponseEntity<InputStreamResource> getCarImage(@PathVariable Long id) {
        var image = imageService.getOne(id);
            
        var imageDecompressed = decompressBytes(image.getImage());
        InputStream inputStream = new ByteArrayInputStream(imageDecompressed);
        return ResponseEntity.ok()
                .contentLength(image.getImage().length)
                .contentType(MediaType.IMAGE_JPEG)
                .body(new InputStreamResource(inputStream));
    }



    public static byte[] decompressBytes(byte[] data) {
        Inflater inflater = new Inflater();
        inflater.setInput(data);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
        byte[] buffer = new byte[1024];
        try {
            while (!inflater.finished()) {
                int count = inflater.inflate(buffer);
                outputStream.write(buffer, 0, count);
            }
            outputStream.close();
        } catch (IOException ioe) {
        } catch (DataFormatException e) {
        }
        return outputStream.toByteArray();
    }

enter image description here


Solution

  • Using this sample

    @ResponseBody
    @GetMapping(value = "/{id}")
    public byte[] getImageAsByteArray(@PathVariable int id) {
         return imageService.getOne(id).getImage();
    }