我使用下面的一段代碼遍歷圖像中的所有像素,並在特定RGB容差範圍內的像素上繪製紅色1x1正方形。我想有一個更有效的方法來做到這一點?任何想法讚賞。 (bi
是BufferedImage
和g2
是Graphics2D
,其顏色設置爲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)));
}
@Ed泰勒:無論如何,現在要爲圖像的每個像素創建一個*新的顏色*:這正是人們如何殺死Java程序的全部內容。對於1920x1200的圖片,您將創建200多萬個Color對象。非常浪費(我知道,我知道,短暫的物體,但仍然是:如果你可以在瞬間創造2百萬個物體,所有的意思是閃避它) – NoozNooz42 2010-06-01 00:52:53