【问题标题】:How to create BufferedImage with BITMASK Transparency?如何使用 BITMASK 透明度创建 BufferedImage?
【发布时间】:2015-01-28 19:18:55
【问题描述】:

BufferedImage 类实现了 Transparency,它具有三个值:

不透明表示不透明。

半透明表示每个像素都有一个介于 0 和 1 之间的 Alpha 值。

BITMASK 表示每个像素要么不透明,要么完全透明。

我可以用 getTransparency() 方法检查这个值。就我而言,我有一个透明的 PNG 文件:

pic = ImageIO.read(new File(filename));
int transparency = pic.getTransparency(); // returns Transparency.TRANSLUCENT

现在我读到使用 Transparency.BITMASK 的图像可以比使用 Transparency.TRANSLUCENT 的图像绘制得更快,在我的情况下 BITMASK 就足够了。我只会用一种特定的颜色为所有透明像素着色,然后保存不透明的 png。

问题:如何通过仅将一种颜色定义为透明来从现有的 BufferedImage 创建一个具有 Transparency.BITMASK 的 BufferedImage 对象?

【问题讨论】:

    标签: java png transparency bufferedimage bitmask


    【解决方案1】:

    接受的答案没有错,只是提供了一个完整的替代方案(我认为它可以在无头模式下工作)。 :-)

    BufferedImage 的透明度由其ColorModel 控制。

    所以要使用给定的Transparency 常量创建BufferedImage,您可以使用如下代码:

    // Use default RGB color space, no discrete alpha channel, 
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    ColorModel colorModel = new ComponentColorModel(cs, true, false, Transparency.BITMASK, DataBuffer.TYPE_BYTE);
    
    WritableRaster raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, w, h, 4, null);
    
    BufferedImage image = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);
    

    【讨论】:

      【解决方案2】:

      你的意思是……

      // Create the buffered image
      GraphicsDevice gs = ge.getDefaultScreenDevice();
      GraphicsConfiguration gc = gs.getDefaultConfiguration();
      
      BufferedImage bimage = gc.createCompatibleImage(width, height, Transparency.BITMASK);
      

      注意事项:

      • 如果您的 PNG 包含 > 0 和
      • 如果您改用Transparency.TRANSLUCENTBufferedImage 的颜色模式将与GraphicsDevice 兼容,从而加快渲染速度

      几年前我做了一个动画序列,它由 5 个独立的图像组成,相互叠加并以不同的速度播放,所有这些都在一个透明窗口的顶部......当我第一次尝试运行它时,播放很糟糕,在这个地方跳来跳去。

      经过一番尝试,我发现使用Transparency.TRANSLUCENT 将图像转换为与GraphicsDevice 兼容的颜色模型就像一个魅力......

      【讨论】:

      • 好的,那么如何在这个BufferedImage上画一个png,这样特定的颜色就透明了?
      • 您使用bimage.createGraphics() 创建一个Graphics2D 实例并为其绘制png 图像,完成后处理Graphics2D 实例...
      • 我一般都知道如何在 BufferedImage 上绘图。我的问题更多地涉及确定透明度颜色。如果我只是在其上绘制 png,它不会有任何透明像素,因为 png 没有透明度。例如,颜色为#ff00ff 的所有像素都应成为透明像素。该怎么做?
      • 这就是重点,你不知道。 API 可能会将 alpha 舍入为 0 或 1...
      • 哦,太好了,我没想到它会这样工作。非常感谢!
      猜你喜欢
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 2019-12-01
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多