Create a Ridiculously Simple Status Image in a Java Servlet
We 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.
