java 如何在JAVA中替换BufferedImage中的颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2369809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to replace colors in BufferedImage in JAVA
提问by Rene
I'm wondering if there is a more efficient method for replacing colors in a BufferedImage. At the moment I use the following method:
我想知道是否有更有效的方法来替换 BufferedImage 中的颜色。目前我使用以下方法:
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.
我正在处理的图像很小,20x20 像素左右。尽管如此,似乎必须有一种更有效的方法来做到这一点。
回答by objects
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.
您可以修改底层 ColorModel,而不是更改图像像素的值。那样快得多,而且不需要遍历整个图像,所以它可以很好地缩放。
回答by Matthew Flaschen
Use a HashMap<Color,Color>. The key should be the original color, and the value the replacement. If the get returns null, do nothing.
使用一个HashMap<Color,Color>. 键应该是原始颜色,值是替换。如果 get 返回 null,则什么都不做。
回答by Adamski
回答by Rahel Lüthy
Have a look at BufferedImageFilter/BufferedImageOpto filter your image in the producer/consumer/observer paradigm.
查看BufferedImageFilter/ BufferedImageOp以在生产者/消费者/观察者范式中过滤您的图像。

