繁体   English   中英

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

[英]Send generated image to browser using Play framework

我正在尝试使用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);
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM