如何在JAVA中替换BufferedImage中的颜色

我想知道是否有更有效的方法来替换BufferedImage中的颜色。 目前我使用以下方法:

我用一个arrays填充要替换的颜色和替换它们的颜色,包括透明度。 然后我遍历图像中的每个像素。 如果它匹配数组中的一种颜色,我将其替换为数组中的新颜色。 这是代码:

Graphics2D g2; g2 = img.createGraphics(); int x, y, i,clr,red,green,blue; for (x = 0; x < img.getWidth(); x++) { for (y = 0; y > 16; green = (clr & 0x0000ff00) >> 8; blue = clr & 0x000000ff; for (i = 1; i <= Arraycounter; i++) { // for each entry in the array // if the red, green and blue values of the pixels match the values in the array // replace the pixels color with the new color from the array if (red == Red[i] && green == Green[i] && blue == Blue[i]) { g2.setComposite(Transparency[i]); g2.setColor(NewColor[i]); g2.fillRect(x, y, 1, 1); } } } 

我正在使用的图像很小,20×20像素左右。 然而,似乎必须有一种更有效的方法来做到这一点。

您可以修改基础ColorModel,而不是更改图像像素的值。 这种方式要快得多,无需迭代整个图像,因此可以很好地扩展。

使用HashMap 。 关键应该是原始颜色,以及替换值。 如果get返回null,则不执行任何操作。

看起来这样做的惯用方法是实现LookupOp ,然后应用此操作来创建新的目标BufferedImage 。 这里有一个很好的答案。

看看BufferedImageFilter / BufferedImageOp来过滤生产者/消费者/观察者范例中的图像。