简体   繁体   English

如何在 Java 中从具有透明度的 PNG 创建图像蒙版?

[英]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.我需要创建一个 Java 类来从具有透明度的 PNG 图像创建图像蒙版。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在处理中加载的 png 图像上创建颜色剪贴蒙版? - How do I create a color clipping mask on a loaded png image in processing? 如何使用Java在png图像上创建网格图? - How do i create a grid map on a png image with java? JAVA:如何从byte []创建.PNG图像? - JAVA : How to create .PNG image from a byte[]? 如何在 scala/java 中将图像裁剪为 svg/png 蒙版的形状 - How can I crop an image to the shape of a svg/png mask in scala/java 在Java中将透明度应用于具有透明性的灰度png图像 - Apply tint to grayscale png image with transparency in Java Java:如何创建使用掩码从字节数组中提取整数拆分位的方法 - Java: How do I create a Method to extract an Integer's split bits from a byte array using a mask 如何从Java中的文件夹目录中获取png图像名称,路径,高度和宽度? - How do I get png image names, paths, heights, and widths from a directory of folders in java? 如何使用java在现有的png图像上绘制矩形 - How do I draw a rectangle on an existing png image using java Java-从PNG图像创建形状(NullPointerException) - Java - Create Shape From PNG Image (NullPointerException) 在SWT上具有透明度的PNG图像 - PNG image with transparency on SWT
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM