2010-05-31 19 views
2

我使用下面的一段代碼遍歷圖像中的所有像素,並在特定RGB容差範圍內的像素上繪製紅色1x1正方形。我想有一個更有效的方法來做到這一點?任何想法讚賞。 (biBufferedImageg2Graphics2D,其顏色設置爲Color.RED)。如何在BufferedImage中有效地着色像素?

Color targetColor = new Color(selectedRGB); 

    for (int x = 0; x < bi.getWidth(); x++) { 
     for (int y = 0; y < bi.getHeight(); y++) { 
      Color pixelColor = new Color(bi.getRGB(x, y)); 
      if (withinTolerance(pixelColor, targetColor)) { 
       g2.drawRect(x, y, 1, 1); 
      } 
     } 
    } 

private boolean withinTolerance(Color pixelColor, Color targetColor) { 
    int pixelRed = pixelColor.getRed(); 
    int pixelGreen = pixelColor.getGreen(); 
    int pixelBlue = pixelColor.getBlue(); 

    int targetRed = targetColor.getRed(); 
    int targetGreen = targetColor.getGreen(); 
    int targetBlue = targetColor.getBlue(); 

    return (((pixelRed >= targetRed - tolRed) && (pixelRed <= targetRed + tolRed)) && 
      ((pixelGreen >= targetGreen - tolGreen) && (pixelGreen <= targetGreen + tolGreen)) && 
      ((pixelBlue >= targetBlue - tolBlue) && (pixelBlue <= targetBlue + tolBlue))); 
} 
+1

@Ed泰勒:無論如何,現在要爲圖像的每個像素創建一個*新的顏色*:這正是人們如何殺死Java程序的全部內容。對於1920x1200的圖片,您將創建200多萬個Color對象。非常浪費(我知道,我知道,短暫的物體,但仍然是:如果你可以在瞬間創造2百萬個物體,所有的意思是閃避它) – NoozNooz42 2010-06-01 00:52:53

回答

1
if (withinTolerance(pixelColor, targetColor)) { 
    bi.setRGB(x, y, 0xFFFF0000) 
} 

BufferedImagesetRGB方法的第三個參數,如在Javadoc解釋的,取TYPE_INT_ARGB形式的像素。爲阿爾法

  • 8位(FF這裏,完全不透明),用於紅色分量
  • 8位(FF這裏,完全華麗紅色)綠色分量
  • 8位(0,無綠色)
  • 藍色分量的8位。
+0

嗯,我看不到任何紅色像素而不是在調用repaint()之後運行setRGB算法。也許這是微不足道的...我明天會進一步調查。 – 2010-06-01 01:17:12

+0

問題解決了,我忘了在重新繪製之前更新對新圖像的引用。 setRGB方法起作用,但我看不到任何顯着的性能改進。 – 2010-06-01 01:44:45

+0

我想知道爲什麼這個函數沒有被稱爲'setARGB'。 – 2015-02-01 20:08:05