如何将BufferedImage转换为特定颜色?

特别是我的图像在透明的情况下都是纯黑色的。我想在绘制图像时为图像分配简单的颜色,以便将黑色区域更改为新颜色。

我尝试使用仅返回所需颜色的RGBImageFilter,但出现了问题,根本没有绘制任何内容。(ColourFilter扩展了RGBImageFilter,并仅在其filterRGB()方法中返回设置的颜色。)

BufferedImage tileImage = _tiles.get( tileID );

ColourFilter cFilt = new ColourFilter();

cFilt.setColour( colour );

FilteredImageSource filteredSrc = new FilteredImageSource( tileImage.getSource(), cFilt );

Image finalImage = Toolkit.getDefaultToolkit().createImage(filteredSrc);

bufferGraphics2D.drawImage(finalImage.....

回答:

查看AlphaComposites,尤其是DST_IN:

BufferedImage original = ... // dimensions width x height, black on transparent

// create red image

BufferedImage redVersion = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

Graphics2D g = (Graphics2D) redVersion.getGraphics();

g.setColor(Color.red);

g.fillRect(0, 0, width, height);

// paint original with composite

g.setComposite(AlphaComposite.DstIn);

g.drawImage(image, 0, 0, width, height, 0, 0, width, height, null);

// redVersion is now a red version of original

以上是 如何将BufferedImage转换为特定颜色? 的全部内容, 来源链接: utcz.com/qa/414970.html

回到顶部