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