动态生成透明跟踪像素

时间:2010-12-28 19:20:31

标签: java image transparency pixel

我正在尝试在Java中动态生成清晰的跟踪像素,但遇到了一些问题。我没有问题将此返回给用户,但我似乎无法使像素正确。我做错了什么?

这就是我所拥有的,它给了我一个1x1的白色像素。如何使其尽可能小(文件大小)并使其透明?

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

4 个答案:

答案 0 :(得分:11)

我相信GRAY图像类型不支持透明度。只修改了Łukasz的答案,以准确显示正在发生的事情。当您创建新图像时,所有像素的初始值都设置为0.这意味着它完全透明。在下面的代码中,我明确地说明了这一点:

    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
    }

答案 1 :(得分:3)

这是@Retkin对写入字节数组而不是文件的回答。

动态生成跟踪图像

public static byte[] get1x1PixelImage() throws IOException{

    // The following code was used to generate the tracking pixel.
    BufferedImage singlePixelImage = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
    Color transparent = new Color(0, 0, 0, 0);
    singlePixelImage.setRGB(0, 0, transparent.getRGB());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(singlePixelImage, "png", baos);
    byte[] imageInBytes = baos.toByteArray();
    baos.close();

    return imageInBytes;
}

获取静态跟踪图像

// Use either format, tracking gif is smaller then the png.
static 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 };
static byte[] trackingPng = {(byte)0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,0x00,0x00,0x00,0x0D,0x49,0x48,0x44,0x52,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x08,0x06,0x00,0x00,0x00,0x1F,0x15,(byte)0xC4,(byte)0x89,0x00,0x00,0x00,0x0B,0x49,0x44,0x41,0x54,0x78,(byte)0xDA,0x63,0x60,0x00,0x02,0x00,0x00,0x05,0x00,0x01,(byte)0xE9,(byte)0xFA,(byte)0xDC,(byte)0xD8,0x00,0x00,0x00,0x00,0x49,0x45,0x4E,0x44,(byte)0xAE,0x42,0x60,(byte)0x82};

public static byte[] get1x1PixelImage() {
    return trackingGif;   // trackingGif is about 38 bytes where trackingPng is 68
}

答案 2 :(得分:2)

我认为创建一个具有适当类型的BufferedImage就足够了。没有必要调用setRGB方法。试试这个:

BufferedImage singlePixelImage = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);

// then I'm saving the generated image in file:
File file = new File("pixel.png");
try {
   ImageIO.write(singlePixelImage, "png", file);
} catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
}

我在Adobe PhotoShop中检查了pixel.png文件,它是透明的。

BufferedImage.TYPE_4BYTE_ABGR告诉我添加一个额外的第四个字节,它存储有关alpha通道值的信息(像素的透明度)。

答案 3 :(得分:1)

如果这是跟踪像素,为什么要再次生成它?生成一次,将其编码为GIF或PNG图像,并仅将这些字节发送回HTTP客户端。这更容易。