Reputation: 10541
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.
Upvotes: 5
Views: 15234
Reputation: 8677
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.
Upvotes: 10
Reputation: 7007
Have a look at BufferedImageFilter/BufferedImageOp to filter your image in the producer/consumer/observer paradigm.
Upvotes: 1
Reputation: 54697
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.
Upvotes: 3
Reputation: 284786
Use a HashMap<Color,Color>
. The key should be the original color, and the value the replacement. If the get returns null, do nothing.
Upvotes: 3