我想知道是否有更有效的方法來替換BufferedImage中的顏色。目前我使用以下方法:如何在JAVA中替換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);
}
}
}
我正在使用的圖像很小,20x20像素左右。儘管如此,似乎必須有一個更有效的方式來做到這一點。
也許如果你解釋我們可以幫助更多的原始問題 – medopal 2010-03-03 10:07:31
該代碼創建圖像以用作地圖中的圖例。我們有一套四種顏色的模板圖像。黑色,紅色,綠色和藍色。根據地圖中的專題表示,模板圖像必須獲得正確的顏色。黑色將被轉換爲背景色,紅色爲正確的邊框顏色,綠色爲散列圖案,藍色區域將變爲透明。 – Rene 2010-03-03 10:35:33