javaimagetransparencypixel

Dynamically Generate Transparent Tracking Pixel


I'm trying to generate a clear tracking pixel dynamically in Java, but running into some issues. I have no problem returning this to the user, but I can't seem to get the pixel right. What am I doing wrong?

This is what I have, which gives me a 1x1 white pixel. How do I make this as small as possible (file size) and make it transparent?

BufferedImage singlePixelImage = new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_GRAY_TYPE);
singlePixelImage.setRGB(0, 0, 0xFFFFFF);

Solution

  • I believe the GRAY image type doesn't support transparency. Only modified Łukasz's answer to show exactly what's going on. When you create new image all of it's pixels have initial value set to 0. So that means it's completely transparent. In following code I'm making it explicitly:

        BufferedImage singlePixelImage = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
        Color transparent = new Color(0, 0, 0, 0);
        singlePixelImage.setRGB(0, 0, transparent.getRGB());
    
        File file = new File("pixel.png");
        try {
            ImageIO.write(singlePixelImage, "png", file);
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }