How to serve a transparent 1×1 pixel GIF from a servlet

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

Related posts:

  1. Simple Log4J eclipse template
    Do you use eclipse and log4j? Do you have a template to add a static Logger instance in classes? Do you have to manually add the import? HA! NO MORE!......
  2. Hibernate Naming Strategies
    Using Hibernate annotations with the default naming strategy leaves you with camelCasedColumnNames in your database schema. Gavin King provided a good camelCase to underscore_separated naming strategy with org.hibernate.cfg.ImprovedNamingStrategy. The only......

This entry was posted in Technical HOWTOs and tagged , . Bookmark the permalink.

2 Responses to How to serve a transparent 1×1 pixel GIF from a servlet

  1. Wesley says:

    Matthew, This is exactly what I’ve been looking for. I tried the code above, but cannot resolve pixelAsBase64. Where is this defined?

  2. matthew says:

    Dang, I mucked up the variable name. It’s fixed now. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Additional comments powered by BackType