1

I have BufferedImage in my spring boot application. Now I want to send that file to user. How can I do that ?

I'm looking for method to convert BufferedImage into ResponseEntity.

ejuhjav
  • 2,660
  • 2
  • 21
  • 32
naimur978
  • 144
  • 8
  • 1
    https://docs.oracle.com/javase/8/docs/api/javax/imageio/ImageIO.html#write-java.awt.image.RenderedImage-java.lang.String-java.io.OutputStream-, https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-async-output-stream – JB Nizet Jan 17 '20 at 11:47

1 Answers1

2

you can also convert it to byte[] using javax.imageio.ImageIO

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage , "png", byteArrayOutputStream);

byte[] imageInByte = baos.toByteArray();

then you controller is simplified:

@RequestMapping(value = "/path", method = GET)
public ResponseEntity<byte[]> getResource() {

   return ResponseEntity.status(HttpStatus.OK)
            .header(HttpHeaders.CONTENT_DISPOSITION, "filename=\"image.png"\")
            .contentType(MediaType.IMAGE_PNG)
            .body(imageInByte);
Beppe C
  • 11,256
  • 2
  • 19
  • 41