如何使用Java具有透明度的PNG创建图像遮罩?

时间:2018-11-14 15:42:51

标签: java image-processing png

我需要创建一个Java类来从具有透明性的PNG图像创建图像蒙版。我希望尽可能使用现成的图像处理库来做到这一点。

1 个答案:

答案 0 :(得分:0)

  • 阅读原始图像,
  • 使用新的栅格和新的颜色模型创建新图像:
    • 包裹图像原始数据缓冲区的栅格,只是使用颜色模型不同地解释了
    • 一种颜色模型,它从四个字节中取出第一个字节并将其解释为强度。

原始栅格必须是字节交织的栅格,每个像素四个字节。在此示例中,没有进行安全检查。

BufferedImage orig = ImageIO.read(new File("temp.png"));

DataBuffer dataBuffer = orig.getRaster().getDataBuffer();
ColorSpace cs         = ColorSpace.getInstance(ColorSpace.CS_GRAY);
int[]      nBits      = {8};
int[]      bOffs      = {0};
ColorModel colorModel = new ComponentColorModel(cs, nBits, false, false,
                                                Transparency.TRANSLUCENT,
                                                DataBuffer.TYPE_BYTE);
WritableRaster raster = Raster.createInterleavedRaster(dataBuffer,
                                                       orig.getWidth(), orig.getHeight(),
                                                       orig.getWidth() * 4, 4,
                                                       bOffs, null);

BufferedImage mask = new BufferedImage(colorModel, raster, false, null);