简体   繁体   中英

How do I create an image mask from a PNG with transparency in Java?

I need to create a Java class to create an image mask from a PNG image with transparency. I would prefer to do this as much as possible with out-of-the box image processing libraries as possible.

  • Read original image,
  • Create a new image with a new raster and a new colormodel:
    • A raster that wraps the original data buffer of the image, just interpreted differently (using the colormodel),
    • A colormodel that takes the first byte out of every four and interprets it as intensity.

Original raster needs to be a byte-interleaved raster, with four bytes per pixel. No safety checks are in place in this example.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM