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......
  3. How to increase maven heapspace in hudson builds
    If your maven-built project fails in hudson (especially when you’re using the assembly plugin) and it isn’t a compile or test failure, check the console output. If it says “java.lang.OutOfMemoryError:......

  • Wesley

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

  • http://matthew.mceachen.us matthew

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

  • Kristian

    Thanks man! You just saved me hours of work.

    I’ll post how I did this in spring 3.0. I think Apache has updated the Base64 library since you posted this too – I had to make a Base64 instance and it didn’t let me call it statically. No biggie though

    Thanks a lot.

    Kristian

  • Viliam Holub

    Base64.decode method in not static and therefore cannot be used on class name.

    Better is to use static Base64.decodeBase64 which works on String as well and makes it cleaner:
    private static final byte[] PIXEL_BYTES = Base64.decodeBase64(PIXEL_B64);