使用Play Framework将生成的图像发送到浏览器
-
29-09-2019 - |
题
我正在尝试使用Play输出生成的图像。我不确定我的问题是否特定于游戏。我正在尝试做同样的事情,此PHP代码也是如此:
header("Content-type: Image/png");
$map = imagecreatefrompng("$_SESSION[ROOT]/it/cabling/maps/${building}_$floor.png");
... // add annotations
imagepng($map);
看起来我需要使用 renderBinary
, ,但我不确定如何从 BufferedImage
到 InputStream
那 renderBinary
想要作为论点。
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);
}
解决方案 2
我在源代码中找到了一个示例 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
有了它,所以我保留了它,至少直到我发现它为什么没有它。
其他提示
有许多渲染方法,其中一种只是将文件作为参数。看 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)));
}
不隶属于 StackOverflow