JPanel 到 BufferedImage

JPanel to BufferedImage

我正在尝试将 JPanel 的内容转换为 BufferedImage。环顾四周后,我得到了这段代码。

    BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();
    this.paint(g);

我使用以下方法遍历图像以查找黑色像素。

for(int i = 0; i < image.getWidth(); i++){
        for(int j = 0; j < image.getHeight(); j++){
            Color tempColor = new Color(image.getRGB(i, j));
            if(tempColor == Color.BLACK){
                System.out.println(tempColor); //Debugging
            }
        }
    }

JPanel 包含许多使用 Color.BLACK 绘制的像素(所以是的,它们是黑色的),尽管当 运行 此代码时,它从不打印调试行。

我认为我的代码中的错误与我将 JPanel 的内容复制到 BufferedImage 的方式有关,我似乎无法弄清楚我做错了什么。非常感谢任何帮助,谢谢。

感谢@Holger 的回答。

for(int i = 0; i < image.getWidth(); i++){
    for(int j = 0; j < image.getHeight(); j++){
        Color tempColor = new Color(image.getRGB(i, j));
        if(tempColor.equals(Color.BLACK)){ // Error was here
            System.out.println(tempColor); //Debugging
        }
    }
}

原来我有代码

if(tempColor == Color.BLACK)

而不是

if(tempColor.equals(Color.BLACK))

我必须开始的总是评估为 false,这就是错误。

您在测试 tempColor == Color.BLACK 时正在执行引用相等性测试。但是 new Color(…) 总是创建一个新对象,它永远不会与预定义的 Color.BLACK 实例相同,因此 == 检查将始终是 false.

使用 equals 或根本不处理 Color 对象,只检查是否 image.getRGB(i, j) == 0 或者如果你不想对黑色使用零,你也可以使用 image.getRGB(i, j) == Color.BLACK.getRGB()