Search code examples
javaspring-bootapibufferedimage

How to create an endpoint which takes a path, load the image and serve it to the client


I want to serve an image to a client by converting it to a byte but for some reason byteArrayOutputStream.toByteArray() is empty. I get a response status of 200 which means it is served. I looked at various documentations on reading an image file from a directory using BufferedImage and then converting BufferedImage to a byteArray from oracle https://docs.oracle.com/javase/tutorial/2d/images/loadimage.html and https://docs.oracle.com/javase/tutorial/2d/images/saveimage.html but for some reason byteArray is still empty

This controller

@GetMapping(path = "/get/image/{name}")
public ResponseEntity<byte[]> displayImage(String name) throws IOException {
        String photoPathFromDatabase = productRepository.findPhotoByName(name);
        Path path = Paths.get(photoPathFromDatabase);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();



        BufferedImage image = ImageIO.read(path.toFile()); // Reading the image from path or file
        String fileType = Files.probeContentType(path.toFile().toPath()); // Getting the file type
        ImageIO.write(image, fileType, byteArrayOutputStream); // convert from BufferedImage to byte array
        byte[] bytes = byteArrayOutputStream.toByteArray();

        return ResponseEntity
                .ok()
                .contentType(MediaType.valueOf(fileType))
                .body(bytes);
    }

After I debugged the method enter image description here


Solution

  • You should read the bytes of the file directly, rather than use an excessive amount of methods from different classes. This can be done with the class java.nio.file.Files.

    byte[] contentBytes = Files.readAllBytes(path); //Throws IOException