使用 Play 框架将生成的图像发送到浏览器 [英] Send generated image to browser using Play framework
问题描述
我正在尝试使用 Play 输出生成的图像.我不确定我的问题是否与 Play 相关.我正在尝试做与此 PHP 代码相同的事情:
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);
看起来我需要使用 renderBinary
,但我不确定如何从 BufferedImage
到 InputStream
code>renderBinary 想要作为它的参数.
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
动作:
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);
}
推荐答案
我在 Images.Captcha
的源代码中找到了一个示例,导致了这个解决方案:
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);
}
使用 <img id="map" src="@{Application.map(ts.building.code, ts.code)}" width="100%">
在视图模板中.
which is referenced using <img id="map" src="@{Application.map(ts.building.code, ts.code)}" width="100%">
in the view template.
出于某种原因,即使不指定内容类型它也能工作,但我不确定如何.Images.Captcha
中的代码有它,所以我保留了它,至少直到我发现它没有它的原因.
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.
这篇关于使用 Play 框架将生成的图像发送到浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!