开发者

Send generated image to browser using Play framework

I'm trying to output a generated image using Play. I'm not sure if my issue is Play-specific or not. 开发者_高级运维 I'm trying to do the same thing this PHP code does:

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

It looks like I need to use renderBinary, but I'm not sure how to get from a BufferedImage to the InputStream that renderBinary wants as its argument.

Application.map action:

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


There are a number of renderBinary methods, one of which simply takes a File as a parameter. See http://www.playframework.org/documentation/api/1.1/play/mvc/Controller.html#renderBinary(java.io.File)

So, your code needs to be as simple as

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


I found an example in the source code for Images.Captcha which led to this solution:

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

which is referenced using <img id="map" src="@{Application.map(ts.building.code, ts.code)}" width="100%"> in the view template.

For some reason it works even without specifying the content type but I'm not sure how. The code in Images.Captcha had it so I kept it, at least until I find out why it works without it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜