Search code examples
javaspringimagefile-ioinputstream

Black background when display an image in a REST API with Spring


I want to return a link to the image (or the image itself) when making a GET-request. I saw the tutorial from Baeldung and decided to use it. The code looks like this:

@RequestMapping(value = "/image-manual-response", method = RequestMethod.GET)
public void getImageAsByteArray(HttpServletResponse response) throws IOException {
    InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg");
    response.setContentType(MediaType.IMAGE_JPEG_VALUE);
    IOUtils.copy(in, response.getOutputStream());
}

Since I could not figure out what servletContext is and find the information I needed, I slightly changed the method:

    @GetMapping("/image")
    public void getImageAsByteArray(HttpServletResponse response) throws IOException {

        InputStream in = new ByteArrayInputStream(("C:\\Users\\vartanyan\\Desktop\\images\\Puer").getBytes());
        response.setContentType(MediaType.IMAGE_JPEG_VALUE);
        IOUtils.copy(in, response.getOutputStream());
    }

As a result, in Swagger I got the following:

enter image description here

And when I open the image in a separate window, I get the following: enter image description here

How can this problem be corrected? I am writing Rest MVC app using Spring Boot, Hibernate, PostgreSQL.


Solution

  • I add FileInputStream() realisation. For example:

    public void getDrinkImage(HttpServletResponse response, Long drinkId) throws IOException {
    
            String imageURL = drinkRepository.getById(drinkId).getImage();
    
            InputStream in = new FileInputStream(uploadPath + imageURL);
            response.setContentType(MediaType.IMAGE_JPEG_VALUE);
            IOUtils.copy(in, response.getOutputStream());
        }