使用Play框架将生成的图像发送到浏览器

我正在尝试使用Play输出生成的图像。 我不确定我的问题是否是Play特定的。 我试图做这个PHP代码做的事情:

header("Content-type: Image/png"); $map = imagecreatefrompng("$_SESSION[ROOT]/it/cabling/maps/${building}_$floor.png"); ... // add annotations imagepng($map); 

看起来我需要使用renderBinary ,但我不知道如何从BufferedImagerenderBinary想要作为其参数的InputStream

Application.map动作:

 public static void map(String building_code, String ts_code) throws IOException { BufferedImage image = ImageIO.read(new File("public/images/maps/" + building_code + "_" + ts_code.charAt(0))); ... // Overlay some additional information on the image // do some sort of conversion renderBinary(inputStream); } 

有许多renderBinary方法,其中一个只是将File作为参数。 见http://www.playframework.org/documentation/api/1.1/play/mvc/Controller.html#renderBinary(java.io.File )

所以,你的代码需要如此简单

 public static void map(String building_code, String ts_code) throws IOException { renderBinary(new File("public/images/maps/" + building_code + "_" + ts_code.charAt(0))); } 

我在Images.Captcha的源代码中找到了一个示例,它导致了这个解决方案:

 public static void map(String building_code, String ts_code) throws IOException { BufferedImage image = ImageIO.read(new File("public/images/maps/" + building_code + "_" + ts_code.charAt(0) + ".png")); ... // add annotations ImageInputStream is = ImageIO.createImageInputStream(image); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "png", baos); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); Response.current().contentType = "image/png"; renderBinary(bais); } 

在视图模板中使用

由于某种原因,它甚至没有指定内容类型,但我不知道如何。 Images.Captcha的代码拥有它,所以我保留了它,至少直到我发现它没有它的原因。