piet
piet

Reputation: 406

Creating 1x1 transparent gif in a Servlet

following issue gets me a lack of understanding. I want to create a 1x1 transparent gif which will be provided by a servlet:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


    response.setContentType("image/gif");


    byte[] trackingGif = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x1, 0x0, 0x1, 0x0, (byte) 0x80, 0x0, 0x0,
            (byte) 0xff, (byte) 0xff, (byte) 0xff, 0x0, 0x0, 0x0, 0x2c, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x1, 0x0,
            0x0, 0x2, 0x2, 0x44, 0x1, 0x0, 0x3b };


    BufferedImage singlePixelImage = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
    Color transparent = new Color(0, 0, 0, 0);
    singlePixelImage.setRGB(0, 0, transparent.getRGB());

    response.setContentType("image/gif");
    response.getOutputStream().write(trackingGif);
}

If i call the Servlet from Firefox, the Servlet is always called twice and Firebug tells me "The URL could not be loaded" and shows a broken Image.

Chrome for example does not call it twice.

Waht is wrong? is it really not a valid image?

Thanks in advance.

Upvotes: 2

Views: 1092

Answers (1)

mprivat
mprivat

Reputation: 21902

The GIF data looks ok. But why recreate it if you already have the data?

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    byte[] trackingGif = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x1, 0x0, 0x1, 0x0, (byte) 0x80, 0x0, 0x0,
            (byte) 0xff, (byte) 0xff, (byte) 0xff, 0x0, 0x0, 0x0, 0x2c, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x1, 0x0,
            0x0, 0x2, 0x2, 0x44, 0x1, 0x0, 0x3b };

    response.setContentType("image/gif");
    response.setContentLength(trackingGif.length);

    OutputStream out = response.getOutputStream();
    out.write(trackingGif);
    out.close();
}

The calling the servlet twice I believe is a side effect of having Firefox + Firebug running. bug

Upvotes: 2

Related Questions