2010-11-08 46 views
3

我试图使用Play输出生成的图像。我不确定我的问题是否是特定于游戏的。我试图做到这一点PHP代码做同样的事情:使用Play框架将生成的图像发送到浏览器

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

它看起来像我需要使用renderBinary,但我不知道如何从BufferedImage获取到InputStreamrenderBinary希望其论据。

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); 
} 

回答

3

我发现在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); 
} 

这是在视图模板中使用<img id="map" src="@{Application.map(ts.building.code, ts.code)}" width="100%">引用。

由于某种原因,即使没有指定内容类型,它的工作原理,但我不知道如何。 Images.Captcha中的代码有它,所以我保留它,至少直到我找出它没有它的原因。

+0

为什么你创建的ImageInputStream是,它不会在以后使用? – 2013-08-26 13:42:02

+0

@AlexanderKjäll从我复制的方法中继承了另一个工件 - 我不确定它做了什么,因此我只是离开了它,假设框架作者有一个原因。你当然可以尝试删除它。 – 2013-08-26 16:12:13

3

有许多的方法renderBinary,其中一个简单地取一个文件作为参数。 见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))); 
} 
+0

我应该在我的问题中说得更清楚一些,但我不只是按照原样显示图像。我正在加载一个基础图像,我将覆盖一些信息,然后我需要呈现结果。 – 2010-11-08 22:20:50

+0

啊,在这种情况下,@bemace的解决方案应该为您提供答案。 – Codemwnci 2010-11-09 08:35:30