简体   繁体   中英

How to replace colors in BufferedImage in JAVA

I'm wondering if there is a more efficient method for replacing colors in a BufferedImage. At the moment I use the following method:

I fill an array with colors to be replaced and the colors to replace them with, including transparency. Then I loop through every pixel in the image. If it matches one of the colors in the array I replace it with the new color from the array. Here is the code:

  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);
        }
      }
    }

The images I'm working with are small, 20x20 pixels or so. Nevertheless It seems there must be a more efficient way to do this.

Instead of changing the value of the image pixels you can modify the underlying ColorModel. Much faster that way and no need to iterate over the whole image so it scales well.

Use a HashMap<Color,Color> . The key should be the original color, and the value the replacement. If the get returns null, do nothing.

It looks like the idiomatic way to do this is to implement a LookupOp and then apply this operation to create a new target BufferedImage . There is a great answer here .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM