Send generated image to browser using Play framework

前端 未结 2 2265
温柔的废话
温柔的废话 2020-12-30 17:10

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:

         


        
相关标签:
2条回答
  • 2020-12-30 17:31

    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);
    }
    

    which is referenced using <img id="map" src="@{Application.map(ts.building.code, ts.code)}" width="100%"> in the view template.

    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.

    0 讨论(0)
  • 2020-12-30 17:34

    There are a number of renderBinary methods, one of which simply takes a File as a parameter. See http://www.playframework.org/documentation/api/1.1/play/mvc/Controller.html#renderBinary(java.io.File)

    So, your code needs to be as simple as

    public static void map(String building_code, String ts_code) throws IOException {
        renderBinary(new File("public/images/maps/" + building_code + "_" + ts_code.charAt(0)));
    }
    
    0 讨论(0)
提交回复
热议问题