代码之家  ›  专栏  ›  技术社区  ›  Brad Mace Mike King

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

  •  3
  • Brad Mace Mike King  · 技术社区  · 14 年前

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

    看起来我需要用 renderBinary ,但我不知道如何从 BufferedImage 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);
    }
    
    2 回复  |  直到 14 年前
        1
  •  3
  •   Codemwnci    14 年前

    有很多renderBinary方法,其中一个方法只是将文件作为参数。 见 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)));
    }
    
        2
  •  3
  •   Brad Mace Mike King    13 年前

    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%"> 在视图模板中。

    出于某种原因,它甚至在不指定内容类型的情况下也能工作,但我不确定如何工作。密码输入 图片。验证码 所以我把它留着,至少在我弄清楚没有它为什么能用之前。