我想知道是否有更有效的方法来替换BufferedImage中的颜色.目前我使用以下方法:
我用一个阵列填充要替换的颜色和替换它们的颜色,包括透明度.然后我遍历图像中的每个像素.如果它匹配数组中的一种颜色,我将其替换为数组中的新颜色.这是代码:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用的图像很小,20x20像素左右.然而,似乎必须有一种更有效的方法来做到这一点.
obj*_*cts 10
您可以修改基础ColorModel,而不是更改图像像素的值.这种方式更快,无需迭代整个图像,因此可以很好地扩展.