SprintBoot从Controller的RequestMapping

时间:2016-08-24 04:03:41

标签: rest http spring-boot png

我一直在网上搜索资源,我觉得我几乎有答案,但我似乎无法将BufferedImage返回到浏览器窗口。

该项目会生成一个迷宫,然后可以创建BufferedImage

以下是我的Controller的代码。

    @RequestMapping(method = RequestMethod.GET, path = "/image", params = {"rows", "columns"})
    public ResponseEntity<byte[]> image(@RequestParam(name = "rows") int rows, @RequestParam(name = "columns") int columns) throws IOException, InterruptedException {
        try {
            BasicCartesianGrid requestedMaze = new BasicCartesianGrid(rows, columns);
            requestedMaze.forEach(CellAlgorithms.BINARY_TREE);
            BufferedImage bufferedImage = requestedMaze.toDisplayImage();
            {   // Dumping to file for debugging <- this works as expected
                File outputFile = new File("save.png");
                ImageIO.write(bufferedImage, "png", outputFile);
            }
            ByteArrayOutputStream pngByteStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", pngByteStream);
            byte[] pngBytes = pngByteStream.toByteArray();
            final HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            headers.setContentLength(pngBytes.length);
            headers.setCacheControl(CacheControl.noCache().getHeaderValue());

            return new ResponseEntity<>(pngBytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            // This hasn't occurred yet, but is for just in case
            Thread.sleep(1000);
            System.err.println(e.getLocalizedMessage());

            final HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_PLAIN);
            return new ResponseEntity<>(e.getLocalizedMessage().getBytes("ASCII"), headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

我已确定PNG正在正确生成,因为该文件存在且可在我的硬盘驱动器上查看。我的浏览器返回一个损坏的图像。从我的终端,我可以获得更多信息。

curl "http://localhost:8080/maze/image?rows=10&columns=10"

转储以下内容(引号是响应的一部分,而省略号表示的数据会因请求而变化,因为每个迷宫都是随机生成且唯一的):

"iVBORw0KGgoAAAANSUhEUgAAA......"

我用Google搜索了这个字符串前缀,找到了this page。这表明该字符串应该用作数据uri,如下所示:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA…" >

我不知道从哪里开始。看起来我的图像生成正确,但我必须在我的响应中缺少一个标题,告诉浏览器/ spring这些字节应该被解释为图像而不仅仅是一个字符串。

更新 基于我和答案部分Shawn Clark之间的对话,这就是我现在所拥有的。

@SpringBootApplication
@Log4j
public class SpringMazesApplication {

    @Bean
    public HttpMessageConverter<BufferedImage> bufferedImageHttpMessageConverter() {
        log.debug("Registering BufferedImage converter");
        return new BufferedImageHttpMessageConverter();
    }

    public static void main(String[] args) throws IOException {
        SpringApplication.run(SpringMazesApplication.class, args);
    }
}

实际的控制器:

@Controller
@RequestMapping(path = "/maze/basic", method = RequestMethod.GET)
@Log4j
public class BasicMazeController {

    @RequestMapping(params = {"format", "format=text"}, produces = MediaType.TEXT_PLAIN_VALUE)
    @ResponseBody
    public String simpleMazeText(@RequestParam(name = "rows", defaultValue = "10", required = false) int rows,
                                 @RequestParam(name = "columns", defaultValue = "10", required = false) int columns) throws IOException {
        BasicCartesianGrid requestedMaze = new BasicCartesianGrid(rows, columns);
        requestedMaze.forEach(CellAlgorithms.BINARY_TREE);
        return requestedMaze.toDisplayString();
    }

    @RequestMapping(params = {"format=image"}, produces = MediaType.IMAGE_PNG_VALUE)
    @ResponseBody
    public BufferedImage simpleMazeImage(@RequestParam(name = "rows", defaultValue = "10", required = false) int rows,
                                         @RequestParam(name = "columns", defaultValue = "10", required = false) int columns) throws IOException {
        log.debug("Starting image generation");
        BasicCartesianGrid requestedMaze = new BasicCartesianGrid(rows, columns);
        requestedMaze.forEach(CellAlgorithms.BINARY_TREE);
        BufferedImage bufferedImage = requestedMaze.toDisplayImage();
        {   // Dumping to file for debugging <- this works as expected
            log.debug("Dumping image to hd");
            File outputFile = new File("save.png");
            ImageIO.write(bufferedImage, "png", outputFile);
        }
        log.debug("Returning from image generation");
        return bufferedImage;
    }

    @RequestMapping
    @ResponseBody
    public ResponseEntity<String> simpleMazeInvalid(@RequestParam(name = "rows", defaultValue = "10", required = false) int rows,
                                                    @RequestParam(name = "columns", defaultValue = "10", required = false) int columns,
                                                    @RequestParam(name = "format") String format) throws IOException {
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity<>("Invalid format: " + format, headers, HttpStatus.BAD_REQUEST);
    }
}

从我的终端我可以curl -D - "url"我可以看到记录/调试和我终端的输出,转换器在应用程序的乞讨时正确注册,我得到你的响应期望从除了实际图像uri以外的所有图像返回406 Not Acceptable。如果我从图片方法中移除@ResponseBody,则只返回500。我可以验证图像是否正确地生成,因为它正如我所希望的那样写入磁盘。

Terminal output from curling my restpoints

1 个答案:

答案 0 :(得分:1)

查看produces上的@RequestMapping属性。您可能希望将其设置为image/png

这是一个完整的例子:

@RestController
public class ProduceImage {
    @GetMapping(path = "/image", produces = "image/png")
    public BufferedImage image() throws Exception {
        BufferedImage bufferedImage = ImageIO.read(new File("E:\\Downloads\\skin_201305121633211421.png"));
        return bufferedImage;
    }
}

My BufferedImage来自我的计算机,但它可以很容易地从requestedMaze.toDisplayImage()获得BufferedImage,而无需完成所有其他工作。为了完成这项工作,您希望在上下文中包含BufferedImageHttpMessageConverter

@Bean
public HttpMessageConverter<BufferedImage> bufferedImageHttpMessageConverter() {
    return new BufferedImageHttpMessageConverter();
}