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


问题内容

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

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

  Graphics2D g2;
  g2 = img.createGraphics();
  int x, y, i,clr,red,green,blue;

  for (x = 0; x < img.getWidth(); x++) {
    for (y = 0; y < img.getHeight(); y++) {

      // For each pixel in the image
      // get the red, green and blue value
      clr = img.getRGB(x, y);
      red = (clr & 0x00ff0000) >> 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);
        }
      }
    }

我正在处理的图像很小,约为20x20像素。但是,似乎必须有一种更有效的方法来执行此操作。


问题答案:

您可以修改基础ColorModel而不是更改图像像素的值。这种方式要快得多,并且不需要遍历整个图像,因此可以很好地缩放。