Posts tagged web
How to serve a transparent 1×1 pixel GIF from a servlet
Nov 24th
The first issue was how to build the smallest possible byte array that represents a 1×1 GIF. Using ImageMagick piped to base64 made it easy to embed into java code:
convert -size 1x1 xc:transparent gif:- | base64
At servlet load time, un-base64 the gif back into the byte array:
import org.apache.commons.codec.binary.Base64; ... private static final String PIXEL_B64 = "R0lGODlhAQABAPAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="; private static final byte[] PIXEL_BYTES = Base64.decode(PIXEL_B64.getBytes());
in your handle method, then write those bytes to the output stream:
httpServletResponse.setContentType("image/gif");
httpServletResponse.getOutputStream().write(PIXEL_BYTES);