我正在使用以下代码迭代图像中的所有像素,并在特定RGB容差范围内的像素上绘制红色1x1方形。我想有更有效的方法来做到这一点?任何想法都赞赏。 (bi
是BufferedImage
,g2
是Graphics2D
,其颜色设置为Color.RED
。)
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)));
}
答案 0 :(得分:1)
if (withinTolerance(pixelColor, targetColor)) {
bi.setRGB( x, y, 0xFFFF0000 )
}
BufferedImage
的{{1}}方法的第三个参数,如Javadoc中所述,采用setRGB
形式的像素。