【问题标题】:PNG transparency without alpha channel没有 Alpha 通道的 PNG 透明度
【发布时间】:2010-12-30 12:34:29
【问题描述】:

我正在尝试从 Java 中的 BufferedImage 创建一个透明的 PNG 图像。

PNG 将被加载到另一个软件中,不支持 alpha 通道

应该没问题,因为根据Chapter 8, section 5, part 4 of the PNG book,我可以通过将像素值指定为透明来实现透明。这通过在 png 文件中创建 tRNS 标头来工作。

我不确定如何将此技术细节转换为 Java 代码。实际图像本身是单色的;每个像素将是黑色或白色。 我想用透明像素替换每个白色像素,而不使用 Alpha 通道。有人可以把我推向正确的方向吗?

【问题讨论】:

    标签: java png


    【解决方案1】:

    您可以使用以下代码。

    创建一个单色透明的BufferedImage:

    public static BufferedImage createTransparentMonochromeBufferedImage(int w, int h)
    {
        // The color map contains the colors black and white
        byte[] cMap = {0, 0, 0, (byte)255, (byte)255, (byte)255};
        // Create an IndexColorModel setting white as the transparent color
        IndexColorModel monochrome = new IndexColorModel(8, 2, cMap, 0, false, 1);
        // Return a new BufferedImage using that color model 
        return new BufferedImage(w, h, BufferedImage.TYPE_BYTE_INDEXED, monochrome);
    }
    

    将 BufferedImage 保存为 PNG 文件:

    public static void saveBufferedImageAsPNG(BufferedImage img, String filename)
                                                                 throws IOException{
        File file = new File(filename); 
        ImageIO.write(img, "png", file);
    }
    

    【讨论】:

    • 完美。我发现这个类相当缺乏 Java API 文档。也许我只是个菜鸟。
    【解决方案2】:

    尝试以下方法:

    1. 找出BufferedImage中第一个白色像素的索引。
    2. 使用所需参数创建IndexColorModel
    3. 创建一个ColorConvertOp。您可以将null 作为RenderingHints 参数传递。
    4. 使用 [ColorConvertOp.createCompatibleDestImage][3] 接收新的 BufferedImage 实例(目标)。
    5. 使用 [ColorConvertOp.filter][4] 执行从源到目标的转换。

    我对此并不完全确定,但ColorConvertOp 似乎是一个很好的起点。告诉我们结果如何!

    [3]:http://java.sun.com/javase/6/docs/api/java/awt/image/ColorConvertOp.html#createCompatibleDestImage(java.awt.image.BufferedImage, java.awt.image.ColorModel) [4]:http://java.sun.com/javase/6/docs/api/java/awt/image/ColorConvertOp.html#filter(java.awt.image.BufferedImage,java.awt.image.BufferedImage)

    【讨论】:

      【解决方案3】:

      我想你会想使用IndexColorModel

      【讨论】:

      • 这证实了我的想法。我已经阅读并重新阅读该链接 2 天了。
      • 好的,如果您已经知道使用 IndexColorModel 并且您已经/知道构造函数参数,具体是什么问题?您需要使用作为 arg trans 传入的正确索引来创建 CM。
      • 我不确定要使用 IndexColorModel,即使现在,我也不确定如何使用它。然而,这个链接看起来很有希望,mindprod.com/jgloss/indexcolormodel.html。感谢您的确认,我会接受作为答案。
      • 啊,好吧,这是有道理的。祝你好运:-)
      【解决方案4】:

      我不知道,但我确定答案在 The png Specification 中。希望这会有所帮助!

      是否有一个用于编写 png 文件的 java 库(也许是 libpng 的 java 绑定?)可以为您完成艰苦的工作? (当事情不太顺利时,可能会为您省去很多麻烦)

      【讨论】:

      • 感谢您的回答,但我已经知道如何在 PNG 图像中处理此问题。我不确定如何将其转换为 Java 代码。我认为这与 BufferedImage 的 ColorModel 有关,但我不确定(双关语?)。很抱歉有任何沟通不畅。
      猜你喜欢
      • 2012-11-24
      • 2019-03-18
      • 2011-12-31
      • 2015-09-25
      • 2012-01-02
      • 2012-11-05
      • 2010-10-25
      • 1970-01-01
      • 2012-12-24
      相关资源
      最近更新 更多