Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace colors in BufferedImage in JAVA

Tags:

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.

like image 902
Rene Avatar asked Mar 03 '10 08:03

Rene


2 Answers

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.

like image 173
objects Avatar answered Oct 16 '22 05:10

objects


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

like image 28
Matthew Flaschen Avatar answered Oct 16 '22 04:10

Matthew Flaschen