代码之家  ›  专栏  ›  技术社区  ›  Rene

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

  •  5
  • Rene  · 技术社区  · 14 年前

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

      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像素左右。然而,似乎必须有一个更有效的方法来做到这一点。

    4 回复  |  直到 14 年前
        1
  •  10
  •   objects    14 年前

        2
  •  3
  •   Matthew Flaschen    14 年前

    使用 HashMap<Color,Color>

        3
  •  3
  •   Community c0D3l0g1c    7 年前

    这样做的惯用方法似乎是实现 LookupOp 然后应用此操作创建新目标 BufferedImage here .

        4
  •  1
  •   Rahel Lüthy    14 年前

    看一看 BufferedImageFilter / BufferedImageOp 在生产者/消费者/观察者范式中过滤图像。