动态生成透明跟踪像素

问题描述 投票:0回答:4

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

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

BufferedImage singlePixelImage = new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_GRAY_TYPE);
singlePixelImage.setRGB(0, 0, 0xFFFFFF);
java image transparency pixel
4个回答
10
投票

我认为灰色图像类型不支持透明度。只是修改了 Ł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
    }

5
投票

这是 @Rekin 答案的改编,用于写入字节数组而不是文件。

跟踪动态生成的图像

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
}

1
投票

如果这是一个跟踪像素,为什么每次都要再次生成它?生成一次,将其编码为 GIF 或 PNG 图像,然后仅将这些字节发送回 HTTP 客户端。这样就容易多了。


1
投票

我认为创建一个具有正确类型的 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) {
   e.printStackTrace();
}

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

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

© www.soinside.com 2019 - 2024. All rights reserved.