如何有效地为BufferedImage中的像素着色?

时间:2010-05-31 23:42:56

标签: java

我正在使用以下代码迭代图像中的所有像素,并在特定RGB容差范围内的像素上绘制红色1x1方形。我想有更有效的方法来做到这一点?任何想法都赞赏。 (biBufferedImageg2Graphics2D,其颜色设置为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)));
}

1 个答案:

答案 0 :(得分:1)

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

BufferedImage的{​​{1}}方法的第三个参数,如Javadoc中所述,采用setRGB形式的像素。

  • alpha的8位(这里是FF,完全不透明)
  • 红色分量的8位(此处为FF,完全闪烁红色)
  • 绿色成分的8位(0,无绿色)
  • 蓝色组件的8位。