How to replace colors in BufferedImage in JAVA
<p>I'm wondering if there is a more efficient method for replacing colors in a BufferedImage. At the moment I use the following method:</p>

<p>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:</p>

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

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

      // For each pixel in the image
      // get the red, green and blue value
      clr = img.getRGB(x, y);
      red = (clr &amp; 0x00ff0000) &gt;&gt; 16;
      green = (clr &amp; 0x0000ff00) &gt;&gt; 8;
      blue = clr &amp; 0x000000ff;

      for (i = 1; i &lt;= 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] &amp;&amp; green == Green[i] &amp;&amp; blue == Blue[i])
        {
          g2.setComposite(Transparency[i]);
          g2.setColor(NewColor[i]);
          g2.fillRect(x, y, 1, 1);
        }
      }
    }
</code></pre>

<p>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.</p>
