【问题标题】:Send generated image to browser using Play framework使用 Play 框架将生成的图像发送到浏览器
【发布时间】:2010-11-08 20:43:17
【问题描述】:

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

【问题讨论】:

    标签: java image-processing playframework


    【解决方案1】:

    有许多 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)));
    }
    

    【讨论】:

    • 我应该在我的问题中说得更清楚,但我不只是按原样显示图像。我正在加载一个基础图像,我将在上面覆盖一些信息,然后我需要渲染结果。
    • 啊,在这种情况下,@bemace 的解决方案应该会为您提供答案。
    【解决方案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 中的代码有它,所以我保留了它,至少在我找出为什么没有它它可以工作之前。

    【讨论】:

    • 为什么要创建ImageInputStream,以后不用了?
    • @AlexanderKjäll 从我复制的方法中继承下来的另一个工件——我不确定它做了什么,所以我就离开了它,假设框架作者有理由这样做。您当然可以尝试删除它。
    猜你喜欢
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 2014-06-18
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多