2010-11-08 35 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

相關問題