Spring Return Image

Posted by Adam on August 24, 2022
```java /** * 嘗試繪圖 */ @GetMapping("/img/") public ResponseEntity<byte[]> draw(@PathVariable("width") int width, @PathVariable("height") int height) throws IOException, Exception { // Convert the BufferedImage to a byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); // some code ... ImageIO.write(image.appendRow(img1, img2, img3), "png", baos); byte[] bytes = baos.toByteArray(); // Create and return a ResponseEntity with the image byte array and the appropriate headers HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_PNG); // headers.setContentType(MediaType.IMAGE_JPEG); headers.setContentLength(bytes.length); return new ResponseEntity<>(bytes, headers, HttpStatus.OK); } ```