Create a Ridiculously Simple Status Image in a Java Servlet
Thursday, February 19th, 2009We were recently working on a project at work that required we submit some data by appending a dynamic image tag with JavaScript. The data was transmitted in a GET request through a query string defined in the src attribute. We wanted to return a 1×1 image that could be tiled as a background image to indicate the status of the request. With such a simple image requirement, I wanted to find a more elegant solution than streaming an existing image from a file. My experience dealing with images in Java is extremely limited, and a quick Google search didn’t turn up a concise example, so this is mostly just here for reference (mine and others’).
BufferedImage buffer = new BufferedImage(IMG_SIZE, IMG_SIZE, BufferedImage.TYPE_INT_RGB);
Graphics g = buffer.createGraphics();
g.setColor(new Color(Integer.parseInt(success ? SUCCESS_COLOR : FAILURE_COLOR, 16)));
g.fillRect(0,0,IMG_SIZE,IMG_SIZE);
resp.setContentType("image/png");
OutputStream os = resp.getOutputStream();
ImageIO.write(buffer, "png", os);
os.close();
IMG_SIZE in this case is 1 and assumes a square image. You’ll notice the parseInt method call specifies a radix of 16, so that allows SUCCESS_COLOR and FAILURE_COLOR to be defined as hex strings, which to a web developer are second nature.


My favorite part of the job was creating the shot tracker program, which is an interactive shot chart, similar to the one shown at left. Coaches can input their players’ makes and misses with a rich user interface, tracking a wide variety of criteria such as opponent, quarter, shot type, etc. The coach can then report on the players’ shooting statistics, broken down by these criteria, and visualize that data in a heat map overlay. The result is knowing exactly where and under what conditions their players should take their shots.