动态生成透明跟踪像素
我试图在 Java 中动态生成清晰的跟踪像素,但遇到了一些问题。我可以毫无问题地将其返回给用户,但我似乎无法获得正确的像素。我做错了什么?
这就是我所拥有的,它给了我一个 1x1 的白色像素。如何使其尽可能小(文件大小)并使其透明?
BufferedImage singlePixelImage = new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_GRAY_TYPE);
singlePixelImage.setRGB(0, 0, 0xFFFFFF);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我相信灰色图像类型不支持透明度。只是修改了 Łukasz 的答案以准确显示发生了什么。当您创建新图像时,它的所有像素的初始值都设置为 0。这意味着它是完全透明的。在下面的代码中我明确地做到了这一点:
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:
这是 @Rekin 的答案的改编,用于写入字节数组而不是文件。
动态生成的跟踪图像
获取静态跟踪图像
Here's an adaptation of @Rekin's answer to write to a byte array instead of a file.
Tracking Image Generated Dynamically
Get Static Tracking Image
如果这是一个跟踪像素,为什么要每次都生成它?生成一次,将其编码为 GIF 或 PNG 图像,然后仅将这些字节发送回 HTTP 客户端。这样就容易多了。
If this is a tracking pixel, why would you want to generate it each time again? Generate it once, encode it as a GIF or PNG image and only send those bytes back to the HTTP client. That's much easier.
我认为创建具有正确类型的 BufferedImage 就足够了。没有必要调用setRGB方法。试试这个:
我在 Adobe PhotoShop 中检查了 Pixel.png 文件,它是透明的。
BufferedImage.TYPE_4BYTE_ABGR 指示添加一个额外的第四个字节,用于存储有关 Alpha 通道值(像素透明度)的信息。
I think that it is enough to create a BufferedImage with proper type. It's not necessary to call setRGB method. Try this:
I've checked pixel.png file in Adobe PhotoShop and it was transparent.
BufferedImage.TYPE_4BYTE_ABGR
tells to add an additional, fourth byte which stores information about alpha channel value (transparency of a pixel).